diff --git a/packages/rlc-common/src/buildIndexFile.ts b/packages/rlc-common/src/buildIndexFile.ts index cfc029164e..634b16039c 100644 --- a/packages/rlc-common/src/buildIndexFile.ts +++ b/packages/rlc-common/src/buildIndexFile.ts @@ -311,7 +311,8 @@ function generateRLCIndex(file: SourceFile, model: RLCModel) { hasMultiCollection(model) || hasSsvCollection(model) || hasPipeCollection(model) || - hasTsvCollection(model) + hasTsvCollection(model) || + hasCsvCollection(model) ) { file.addExportDeclarations([ { 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..45bf0addde 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 @@ -325,7 +325,12 @@ export function _addOrUpdateBlockItemsSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { blockItems: blockItems }, + body: { + blockItems: (blockItems ?? []).map((p) => ({ + description: p["description"], + text: p["text"], + })), + }, }); } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts index 4cbeee4732..9354b21e20 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts @@ -63,8 +63,7 @@ export function _publishCloudEventSend( ? uint8ArrayToString(event["dataBase64"], "base64") : undefined, type: event["type"], - time: - event["time"] !== undefined ? new Date(event["time"]) : undefined, + time: event["time"]?.toISOString(), specversion: event["specversion"], dataschema: event["dataschema"], datacontenttype: event["datacontenttype"], @@ -123,7 +122,7 @@ export function _publishCloudEventsSend( ? uint8ArrayToString(p["dataBase64"], "base64") : undefined, type: p["type"], - time: p["time"] !== undefined ? new Date(p["time"]) : undefined, + time: p["time"]?.toISOString(), specversion: p["specversion"], dataschema: p["dataschema"], datacontenttype: p["datacontenttype"], 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..906665a52d 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 @@ -37,9 +37,9 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; testId?: string; } @@ -48,9 +48,9 @@ export interface CreateOrUpdateServerMetricsConfigOptions extends OperationOptio // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; metrics?: Record; testId?: string; } @@ -61,7 +61,7 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -69,7 +69,7 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; secrets?: Record; @@ -114,7 +114,7 @@ export interface ErrorDetails { // @public export interface FileInfo { - expireDateTime?: any; + expireDateTime?: Date; fileName?: string; fileType?: FileType; url?: string; @@ -187,8 +187,8 @@ export interface ListTestFilesOptions extends OperationOptions { // @public (undocumented) export interface ListTestRunsOptions extends OperationOptions { - executionFrom?: any; - executionTo?: any; + executionFrom?: Date; + executionTo?: Date; maxpagesize?: number; orderby?: string; search?: string; @@ -198,8 +198,8 @@ export interface ListTestRunsOptions extends OperationOptions { // @public (undocumented) export interface ListTestsOptions extends OperationOptions { - lastModifiedEndTime?: any; - lastModifiedStartTime?: any; + lastModifiedEndTime?: Date; + lastModifiedStartTime?: Date; maxpagesize?: number; orderby?: string; search?: string; @@ -289,9 +289,9 @@ export interface LoadTestRunClientCreateOrUpdateAppComponentsOptions extends Ope // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; testRunId?: string; } @@ -300,9 +300,9 @@ export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions exten // (undocumented) contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; metrics?: Record; testRunId?: string; } @@ -332,7 +332,7 @@ export interface LoadTestRunClientErrorDetails { // @public export interface LoadTestRunClientFileInfo { - expireDateTime?: any; + expireDateTime?: Date; fileName?: string; fileType?: LoadTestRunClientFileType; url?: string; @@ -475,7 +475,7 @@ export type LoadTestRunClientStatus = string; export interface LoadTestRunClientTest { certificate?: LoadTestRunClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -483,7 +483,7 @@ export interface LoadTestRunClientTest { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; passFailCriteria?: LoadTestRunClientPassFailCriteria; secrets?: Record; @@ -504,21 +504,21 @@ export interface LoadTestRunClientTestInputArtifacts { export interface LoadTestRunClientTestRun { certificate?: LoadTestRunClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: any; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: LoadTestRunClientErrorDetails[]; - readonly executedDateTime?: any; + readonly executedDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; passFailCriteria?: LoadTestRunClientPassFailCriteria; readonly portalUrl?: string; secrets?: Record; - readonly startDateTime?: any; + readonly startDateTime?: Date; readonly status?: LoadTestRunClientStatus; readonly subnetId?: string; readonly testArtifacts?: LoadTestRunClientTestRunArtifacts; @@ -699,7 +699,7 @@ export interface StopTestRunOptions extends OperationOptions { export interface Test { certificate?: CertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; @@ -707,7 +707,7 @@ export interface Test { keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; secrets?: Record; @@ -719,9 +719,9 @@ export interface Test { export interface TestAppComponents { components: Record; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; readonly testId?: string; } @@ -738,21 +738,21 @@ export interface TestInputArtifacts { export interface TestRun { certificate?: CertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: any; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: ErrorDetails[]; - readonly executedDateTime?: any; + readonly executedDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; readonly portalUrl?: string; secrets?: Record; - readonly startDateTime?: any; + readonly startDateTime?: Date; readonly status?: Status; readonly subnetId?: string; readonly testArtifacts?: TestRunArtifacts; @@ -783,22 +783,22 @@ export interface TestRunOptions extends OperationOptions { certificate?: LoadTestRunClientCertificateMetadata; contentType?: string; createdBy?: string; - createdDateTime?: any; + createdDateTime?: Date; description?: string; displayName?: string; duration?: number; - endDateTime?: any; + endDateTime?: Date; environmentVariables?: Record; errorDetails?: LoadTestRunClientErrorDetails[]; - executedDateTime?: any; + executedDateTime?: Date; lastModifiedBy?: string; - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; oldTestRunId?: string; passFailCriteria?: LoadTestRunClientPassFailCriteria; portalUrl?: string; secrets?: Record; - startDateTime?: any; + startDateTime?: Date; status?: LoadTestRunClientStatus; subnetId?: string; testArtifacts?: LoadTestRunClientTestRunArtifacts; @@ -835,9 +835,9 @@ export interface TestRunStatistics { // @public export interface TestServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: any; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; metrics?: Record; readonly testId?: string; } 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..4fd7d0a0b0 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 @@ -187,7 +187,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -208,7 +214,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -229,7 +241,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -257,7 +275,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -273,7 +297,10 @@ export async function _createOrUpdateTestDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -284,9 +311,15 @@ export async function _createOrUpdateTestDeserialize( subnetId: result.body["subnetId"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -334,9 +367,15 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -389,9 +428,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -435,9 +480,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -477,9 +528,15 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -572,7 +629,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -593,7 +656,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -614,7 +683,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -642,7 +717,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -658,7 +739,10 @@ export async function _getTestDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -669,9 +753,15 @@ export async function _getTestDeserialize( subnetId: result.body["subnetId"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -713,7 +803,10 @@ export async function _getTestFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -757,7 +850,10 @@ export async function _listTestFilesDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -789,8 +885,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime, - lastModifiedEndTime: options?.lastModifiedEndTime, + lastModifiedStartTime: options?.lastModifiedStartTime?.toUTCString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toUTCString(), maxpagesize: options?.maxpagesize, }, }); @@ -857,7 +953,12 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.configFileInfo?.["fileName"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"], + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.["expireDateTime"] + ) + : undefined, validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -872,7 +973,14 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.inputArtifacts?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: @@ -887,7 +995,12 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] + ) + : undefined, validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -907,7 +1020,13 @@ export async function _listTestsDeserialize( expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -923,7 +1042,10 @@ export async function _listTestsDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -934,9 +1056,15 @@ export async function _listTestsDeserialize( subnetId: p["subnetId"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -988,7 +1116,10 @@ export async function _uploadTestFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts index adc1c2c27a..3631274756 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/models.ts @@ -34,11 +34,11 @@ export interface Test { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -171,7 +171,7 @@ export interface FileInfo { /** File type */ fileType?: FileType; /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: any; + expireDateTime?: Date; /** Validation status of the file */ validationStatus?: FileStatus; /** Validation failure error details */ @@ -194,11 +194,11 @@ export interface TestAppComponents { /** Test identifier */ readonly testId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -238,11 +238,11 @@ export interface TestServerMetricConfig { */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -326,11 +326,11 @@ export interface TestRun { /** The test run status. */ readonly status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: any; + readonly startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: any; + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: any; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ @@ -338,11 +338,11 @@ export interface TestRun { /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts index 6f7df207bb..b622d3dfe4 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/options.ts @@ -44,11 +44,11 @@ export interface CreateOrUpdateTestOptions extends OperationOptions { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -58,11 +58,11 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { /** Test identifier */ testId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -79,11 +79,11 @@ export interface CreateOrUpdateServerMetricsConfigOptions */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -115,12 +115,12 @@ export interface ListTestsOptions extends OperationOptions { * Start DateTime(ISO 8601 literal format) of the last updated time range to * filter tests. */ - lastModifiedStartTime?: any; + lastModifiedStartTime?: Date; /** * End DateTime(ISO 8601 literal format) of the last updated time range to filter * tests. */ - lastModifiedEndTime?: any; + lastModifiedEndTime?: Date; /** Number of results in response. */ maxpagesize?: number; } 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..720decaa83 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 @@ -209,7 +209,13 @@ export async function _testRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -231,7 +237,13 @@ export async function _testRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -253,7 +265,13 @@ export async function _testRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -275,7 +293,14 @@ export async function _testRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -293,7 +318,10 @@ export async function _testRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -315,7 +343,13 @@ export async function _testRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -337,7 +371,13 @@ export async function _testRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -353,15 +393,30 @@ export async function _testRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -409,9 +464,15 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -464,9 +525,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -544,9 +611,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -589,9 +662,15 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -694,7 +773,13 @@ export async function _getTestRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -716,7 +801,13 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -738,7 +829,13 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -760,7 +857,14 @@ export async function _getTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -778,7 +882,10 @@ export async function _getTestRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -800,7 +907,13 @@ export async function _getTestRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -822,7 +935,13 @@ export async function _getTestRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -838,15 +957,30 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -888,7 +1022,10 @@ export async function _getTestRunFileDeserialize( url: result.body["url"], fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -1082,7 +1219,12 @@ export function _listMetricsSend( metricNamespace: options?.metricNamespace, timespan: options?.timespan, }, - body: { filters: options?.filters }, + body: { + filters: (options?.filters ?? []).map((p) => ({ + name: p["name"], + values: p["values"], + })), + }, }); } @@ -1134,8 +1276,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom, - executionTo: options?.executionTo, + executionFrom: options?.executionFrom?.toUTCString(), + executionTo: options?.executionTo?.toUTCString(), status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1222,7 +1364,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1249,7 +1397,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -1276,7 +1430,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1300,7 +1460,14 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1317,7 +1484,10 @@ export async function _listTestRunsDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1343,7 +1513,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1370,7 +1546,13 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1388,15 +1570,28 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: p["startDateTime"], - endDateTime: p["endDateTime"], - executedDateTime: p["executedDateTime"], + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, + executedDateTime: + p["executedDateTime"] !== undefined + ? new Date(p["executedDateTime"]) + : undefined, portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -1500,7 +1695,13 @@ export async function _stopTestRunDeserialize( ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -1522,7 +1723,13 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1544,7 +1751,13 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -1566,7 +1779,14 @@ export async function _stopTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1584,7 +1804,10 @@ export async function _stopTestRunDeserialize( url: p["url"], fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1606,7 +1829,13 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1628,7 +1857,13 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1644,15 +1879,30 @@ export async function _stopTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts index 753b02bd58..545db894d9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/models.ts @@ -34,11 +34,11 @@ export interface Test { /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -171,7 +171,7 @@ export interface FileInfo { /** File type */ fileType?: FileType; /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: any; + expireDateTime?: Date; /** Validation status of the file */ validationStatus?: FileStatus; /** Validation failure error details */ @@ -270,11 +270,11 @@ export interface TestRun { /** The test run status. */ readonly status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: any; + readonly startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: any; + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: any; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ @@ -282,11 +282,11 @@ export interface TestRun { /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -375,11 +375,11 @@ export interface TestRunAppComponents { /** Test run identifier */ readonly testRunId?: string; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -395,11 +395,11 @@ export interface TestRunServerMetricConfig { */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: any; + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: any; + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts index 7be901a85c..85aa3bc985 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/options.ts @@ -53,11 +53,11 @@ export interface TestRunOptions extends OperationOptions { /** The test run status. */ status?: Status; /** The test run start DateTime(ISO 8601 literal format). */ - startDateTime?: any; + startDateTime?: Date; /** The test run end DateTime(ISO 8601 literal format). */ - endDateTime?: any; + endDateTime?: Date; /** Test run initiated time. */ - executedDateTime?: any; + executedDateTime?: Date; /** Portal url. */ portalUrl?: string; /** Test run duration in milliseconds. */ @@ -65,11 +65,11 @@ export interface TestRunOptions extends OperationOptions { /** Subnet ID on which the load test instances should run. */ subnetId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; /** This request has a JSON Merge Patch body. */ @@ -87,11 +87,11 @@ export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { /** Test run identifier */ testRunId?: string; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -108,11 +108,11 @@ export interface CreateOrUpdateServerMetricsConfigOptions */ metrics?: Record; /** The creation datetime(ISO 8601 literal format). */ - createdDateTime?: any; + createdDateTime?: Date; /** The user that created. */ createdBy?: string; /** The last Modified datetime(ISO 8601 literal format). */ - lastModifiedDateTime?: any; + lastModifiedDateTime?: Date; /** The user that last modified. */ lastModifiedBy?: string; contentType?: string; @@ -185,9 +185,9 @@ export interface ListTestRunsOptions extends OperationOptions { /** Unique name of an existing load test. */ testId?: string; /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: any; + executionFrom?: Date; /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: any; + executionTo?: Date; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts index b62bba1cb0..661e7bc19d 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts @@ -242,8 +242,29 @@ export function _getChatCompletionsSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: messages, - functions: options?.functions, + messages: (messages ?? []).map((p) => ({ + role: p["role"], + content: p["content"], + name: p["name"], + function_call: !p.functionCall + ? undefined + : { + name: p.functionCall?.["name"], + arguments: p.functionCall?.["arguments"], + }, + context: !p.context + ? undefined + : { + messages: !p.context?.messages + ? undefined + : (p.context?.messages as any), + }, + })), + functions: (options?.functions ?? []).map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), function_call: options?.functionCall, max_tokens: options?.maxTokens, temperature: options?.temperature, @@ -256,7 +277,10 @@ export function _getChatCompletionsSend( frequency_penalty: options?.frequencyPenalty, stream: options?.stream, model: options?.model, - dataSources: options?.dataSources, + dataSources: (options?.dataSources ?? []).map((p) => ({ + type: p["type"], + parameters: p["parameters"], + })), }, }); } @@ -400,8 +424,29 @@ export function _getChatCompletionsWithAzureExtensionsSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: messages, - functions: options?.functions, + messages: (messages ?? []).map((p) => ({ + role: p["role"], + content: p["content"], + name: p["name"], + function_call: !p.functionCall + ? undefined + : { + name: p.functionCall?.["name"], + arguments: p.functionCall?.["arguments"], + }, + context: !p.context + ? undefined + : { + messages: !p.context?.messages + ? undefined + : (p.context?.messages as any), + }, + })), + functions: (options?.functions ?? []).map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), function_call: options?.functionCall, max_tokens: options?.maxTokens, temperature: options?.temperature, @@ -414,7 +459,10 @@ export function _getChatCompletionsWithAzureExtensionsSend( frequency_penalty: options?.frequencyPenalty, stream: options?.stream, model: options?.model, - dataSources: options?.dataSources, + dataSources: (options?.dataSources ?? []).map((p) => ({ + type: p["type"], + parameters: p["parameters"], + })), }, }); } diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index 8e9abf6052..116035cadb 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -30,7 +30,9 @@ "integration-test:alone:rlc": "cross-env TS_NODE_PROJECT=tsconfig.test.json mocha -r ts-node/register --experimental-specifier-resolution=node --timeout 4000 ./test/integration/*.spec.ts", "integration-test:alone:modular": "cross-env TS_NODE_PROJECT=tsconfig.test.json mocha -r ts-node/register --experimental-specifier-resolution=node --timeout 4000 ./test/modularIntegration/*.spec.ts", "stop-test-server": "npx cadl-ranch server stop", - "unit-test": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --timeout 4000 './test/unit/**/*.spec.ts' './test/modularUnit/**/*.spec.ts'" + "unit-test": "npm run unit-test:rlc && npm run unit-test:modular", + "unit-test:rlc": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --timeout 4000 './test/unit/**/*.spec.ts'", + "unit-test:modular": "cross-env TS_NODE_PROJECT=tsconfig.json mocha -r ts-node/register --experimental-specifier-resolution=node --experimental-modules=true --no-timeout './test/modularUnit/**/*.spec.ts'" }, "author": "Jose Heredia ", "license": "MIT", diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index b601160f81..3c86c7193b 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -27,7 +27,6 @@ import { isStringType, getPropertyType, isNumericType, - getFormat, getMinItems, getMaxItems, listServices, @@ -37,7 +36,8 @@ import { getProjectedName, isNullType, getEncode, - isTemplateDeclarationOrInstance + isTemplateDeclarationOrInstance, + getFormat } from "@typespec/compiler"; import { getAuthentication, @@ -155,7 +155,8 @@ function isSimpleType( getMaxValue, getMinLength, getMaxLength, - getPattern + getPattern, + getEncode ]; for (const func of funcs) { if (func(program, type)) { @@ -277,8 +278,7 @@ function getType( options: { disableEffectiveModel?: boolean } = {} ): any { // don't cache simple type(string, int, etc) since decorators may change the result - const enableCache = - !isSimpleType(context.program, type) && !isEmptyModel(type); + const enableCache = !isSimpleType(context.program, type); const effectiveModel = !options.disableEffectiveModel && (type.kind === "Model" || type.kind === "Union") @@ -298,6 +298,10 @@ function getType( newValue = emitType(context, type); } + if (type.kind === "ModelProperty" || type.kind === "Scalar") { + newValue = applyEncoding(context.program, type, newValue); + } + if (enableCache) { typesMap.set(effectiveModel, newValue); if (type.kind === "Union") { @@ -335,6 +339,7 @@ type ParamBase = { addedOn: string | undefined; clientName: string; inOverload: boolean; + format?: string; }; function emitParamBase( program: Program, @@ -344,12 +349,15 @@ function emitParamBase( let name: string; let description: string = ""; let addedOn: string | undefined; + let format: string | undefined; if (parameter.kind === "ModelProperty") { + const newParameter = applyEncoding(program, parameter, parameter); optional = parameter.optional; name = parameter.name; description = getDocStr(program, parameter); addedOn = getAddedOnVersion(program, parameter); + format = newParameter.format; } else { optional = false; name = "body"; @@ -360,7 +368,8 @@ function emitParamBase( description, addedOn, clientName: applyCasing(name, { casing: CASING }), - inOverload: false + inOverload: false, + format }; } @@ -428,7 +437,6 @@ function emitBodyParameter( const type = getType(context, getBodyType(context.program, httpOperation), { disableEffectiveModel: true }); - if (type.type === "model" && type.name === "") { type.name = capitalize(httpOperation.operation.name) + "Request"; } @@ -466,10 +474,10 @@ function emitParameter( const paramMap: any = { restApiName: parameter.name, location: parameter.type, - type: type, + type: base.format ? { ...type, format: base.format } : type, implementation: implementation, skipUrlEncoding: parameter.type === "endpointPath", - format: (parameter as any).format + format: (parameter as any).format ?? base.format }; if (paramMap.type.type === "constant") { @@ -828,6 +836,7 @@ function emitProperty( context: SdkContext, property: ModelProperty ): Record { + const newProperty = applyEncoding(context.program, property, property); let clientDefaultValue = undefined; const propertyDefaultKind = property.default?.kind; if ( @@ -851,16 +860,18 @@ function emitProperty( if (property.model) { getType(context, property.model); } + const type = getType(context, property.type); return { clientName: applyCasing(clientName, { casing: CASING }), restApiName: jsonName, - type: getType(context, property.type), + type: newProperty.format ? { ...type, format: newProperty.format } : type, optional: property.optional, description: getDocStr(context.program, property), addedOn: getAddedOnVersion(context.program, property), readonly: isReadOnly(context.program, property) || isKey(context.program, property), - clientDefaultValue: clientDefaultValue + clientDefaultValue: clientDefaultValue, + format: newProperty.format }; } @@ -1024,9 +1035,10 @@ function emitStdScalar( program: Program, scalar: Scalar & { name: IntrinsicScalarName } ): Record { + const newScalar = applyEncoding(program, scalar, scalar); switch (scalar.name) { case "bytes": - return { type: "byte-array", format: getEncode(program, scalar) }; + return { type: "byte-array", format: newScalar.format }; case "int8": case "int16": case "int32": @@ -1048,13 +1060,15 @@ function emitStdScalar( case "boolean": return { type: "boolean" }; case "plainDate": - return { type: "date" }; + return { type: "datetime", format: newScalar.format ?? "date" }; case "utcDateTime": - return { type: "datetime", format: "date-time" }; + return { type: "datetime", format: newScalar.format }; case "plainTime": - return { type: "time" }; + return { type: "datetime", format: newScalar.format ?? "time" }; + case "offsetDateTime": + return { type: "datetime", format: newScalar.format ?? "rfc7231" }; case "duration": - return { type: "duration" }; + return { type: "duration", format: newScalar.format }; case "numeric": return {}; // Waiting on design for more precise type https://github.com/microsoft/cadl/issues/1260 default: @@ -1062,12 +1076,51 @@ function emitStdScalar( } } +function applyEncoding( + program: Program, + typespecType: Scalar | ModelProperty, + target: any = {} +) { + const encodeData = getEncode(program, typespecType); + const formatData = getFormat(program, typespecType); + formatData; + if (encodeData) { + const newTarget = { ...target }; + const newType = emitScalar(program, encodeData.type); + // newTarget["type"] = newType["type"]; + // If the target already has a format it takes priority. (e.g. int32) + newTarget["format"] = mergeFormatAndEncoding( + newTarget.format, + encodeData.encoding, + newType["format"] + ); + return newTarget; + } + return target; +} + +function mergeFormatAndEncoding( + format: string | undefined, + encoding: string, + encodeAsFormat: string | undefined +): string { + switch (format) { + case undefined: + return encodeAsFormat ?? encoding; + case "date-time": + return encoding; + case "duration": + default: + return encodeAsFormat ?? encoding; + } +} + function applyIntrinsicDecorators( program: Program, type: Scalar | ModelProperty, result: any ): Record { - const newResult = { ...result }; + let newResult = { ...result }; const docStr = getDoc(program, type); const isString = isStringType(program, getPropertyType(type)); const isNumeric = isNumericType(program, getPropertyType(type)); @@ -1076,10 +1129,7 @@ function applyIntrinsicDecorators( newResult.description = docStr; } - const formatStr = getFormat(program, type); - if (isString && !result.format && formatStr) { - newResult.format = formatStr; - } + newResult = applyEncoding(program, type, newResult); const pattern = getPattern(program, type); if (isString && !result.pattern && pattern) { @@ -1120,7 +1170,8 @@ function applyIntrinsicDecorators( function emitScalar(program: Program, scalar: Scalar): Record { let result: Record = {}; - if (program.checker.isStdType(scalar)) { + const isStd = program.checker.isStdType(scalar); + if (isStd) { result = emitStdScalar(program, scalar); } else if (scalar.baseScalar) { result = emitScalar(program, scalar.baseScalar); @@ -1575,6 +1626,8 @@ export function emitCodeModel( project }; + typesMap.clear(); + simpleTypesMap.clear(); const allModels = getAllModels(dpgContext); for (const model of allModels) { getType(dpgContext, model); diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index a03ac3bcd9..58b9af7a61 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -23,6 +23,7 @@ export function buildOperationFiles( client: Client, needUnexpectedHelper: boolean = true ) { + const operationFiles = []; for (const operationGroup of client.operationGroups) { const importSet: Map> = new Map>(); const fileName = operationGroup.className @@ -114,7 +115,9 @@ export function buildOperationFiles( operationGroupFile.fixMissingImports(); // have to fixUnusedIdentifiers after everything get generated. operationGroupFile.fixUnusedIdentifiers(); + operationFiles.push(operationGroupFile); } + return operationFiles; } export function importModels( @@ -171,7 +174,7 @@ export function buildOperationOptions( return { docs: getDocsFromDescription(p.description), hasQuestionToken: true, - ...buildType(p.clientName, p.type) + ...buildType(p.clientName, p.type, p.format) }; }) }); diff --git a/packages/typespec-ts/src/modular/emitModels.ts b/packages/typespec-ts/src/modular/emitModels.ts index edf8b2795a..ad43acba3c 100644 --- a/packages/typespec-ts/src/modular/emitModels.ts +++ b/packages/typespec-ts/src/modular/emitModels.ts @@ -40,7 +40,7 @@ export function buildModels( for (const model of models) { const properties = model.properties ?? []; - const typeMetadata = getType(model); + const typeMetadata = getType(model, model.format); let typeName = typeMetadata.name; if (typeMetadata.modifier === "Array") { typeName = `${typeName}[]`; @@ -77,7 +77,7 @@ export function buildModels( docs: getDocsFromDescription(model.description), extends: [] as string[], properties: properties.map((p) => { - const propertyMetadata = getType(p.type); + const propertyMetadata = getType(p.type, p.format); let propertyTypeName = propertyMetadata.name; if (isAzureCoreErrorSdkType(p.type)) { propertyTypeName = isAzureCoreErrorSdkType(p.type) @@ -98,7 +98,7 @@ export function buildModels( }; model.type === "model" ? model.parents?.forEach((p) => - modelInterface.extends.push(getType(p).name) + modelInterface.extends.push(getType(p, p.format).name) ) : undefined; modelsFile.addInterface(modelInterface); diff --git a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts index 1770bbafa6..c4fac46752 100644 --- a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts @@ -24,7 +24,7 @@ export function getClientParameters( .map>((p) => { return { name: p.clientName, - type: getType(p.type).name + type: getType(p.type, p.format).name }; }), optionsParam diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index e67b3d548e..e3f5cca0a3 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -101,7 +101,11 @@ export function getDeserializePrivateFunction( const response = operation.responses[0]!; let returnType; if (response?.type?.type) { - returnType = buildType(response.type.name, response.type); + returnType = buildType( + response.type.name, + response.type, + response.type.format + ); } else { returnType = { name: "", type: "void" }; } @@ -148,7 +152,8 @@ export function getDeserializePrivateFunction( response.type, "result.body", importSet, - response.type.nullable !== undefined ? !response.type.nullable : false + response.type.nullable !== undefined ? !response.type.nullable : false, + response.type.format )}` ); } else if (response?.type?.properties) { @@ -185,20 +190,21 @@ function getOperationSignatureParameters( (operation.bodyParameter?.type.properties ?? []) .filter((p) => !p.optional) .filter((p) => !p.readonly) - .map((p) => buildType(p.clientName, p.type)) + .map((p) => buildType(p.clientName, p.type, p.format)) .forEach((p) => parameters.set(p.name, p)); } else if (operation.bodyParameter?.type.type === "list") { const bodyArray = operation.bodyParameter; parameters.set( bodyArray.clientName, - buildType(bodyArray.clientName, bodyArray.type) + buildType(bodyArray.clientName, bodyArray.type, bodyArray.type.format) ); } else if (operation.bodyParameter?.type.type === "byte-array") { parameters.set( operation.bodyParameter.clientName, buildType( operation.bodyParameter.clientName, - operation.bodyParameter.type + operation.bodyParameter.type, + operation.bodyParameter.type.format ) ); } @@ -211,7 +217,7 @@ function getOperationSignatureParameters( p.clientDefaultValue === undefined && !p.optional ) - .map((p) => buildType(p.clientName, p.type)) + .map((p) => buildType(p.clientName, p.type, p.format)) .forEach((p) => { parameters.set(p.name, p); }); @@ -245,7 +251,7 @@ export function getOperationFunction( // TODO: Support operation overloads const response = operation.responses[0]!; const returnType = response?.type?.type - ? buildType(response.type.name, response.type) + ? buildType(response.type.name, response.type, response.type.format) : { name: "", type: "void" }; const { name, fixme = [] } = getOperationName(operation); @@ -298,7 +304,6 @@ function getRequestParameters( if (!operation.parameters) { return ""; } - const operationParameters = operation.parameters.filter( (p) => p.implementation !== "Client" && !isContentType(p) ); @@ -412,7 +417,7 @@ function getParameterMap( } if (hasCollectionFormatInfo((param as any).location, (param as any).format)) { - return getCollectionFormat(param as Parameter); + return getCollectionFormat(param as Parameter, importSet); } // if the parameter or property is optional, we don't need to handle the default value @@ -427,7 +432,10 @@ function getParameterMap( throw new Error(`Parameter ${param.clientName} is not supported`); } -function getCollectionFormat(param: Parameter) { +function getCollectionFormat( + param: Parameter, + importSet: Map> +) { const collectionInfo = getCollectionFormatHelper( param.location, param.format ?? "" @@ -438,9 +446,23 @@ function getCollectionFormat(param: Parameter) { const isMulti = (param.format ?? "").toLowerCase() === "multi"; const additionalParam = isMulti ? `, "${param.restApiName}"` : ""; if (!param.optional) { - return `"${param.restApiName}": ${collectionInfo}(${param.clientName}${additionalParam})`; - } - return `"${param.restApiName}": options?.${param.clientName} !== undefined ? ${collectionInfo}(options?.${param.clientName}${additionalParam}): undefined`; + return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( + param.type, + param.clientName, + importSet, + true, + param.format + )}${additionalParam})`; + } + return `"${param.restApiName}": options?.${ + param.clientName + } !== undefined ? ${collectionInfo}(${serializeRequestValue( + param.type, + "options?." + param.clientName, + importSet, + false, + param.format + )}${additionalParam}): undefined`; } function isContentType(param: Parameter): boolean { @@ -483,7 +505,17 @@ function getRequired(param: RequiredType, importSet: Map>) { importSet ).join(",")}`; } - return `"${param.restApiName}": ${param.clientName}`; + return `"${param.restApiName}": ${serializeRequestValue( + param.type, + param.clientName, + importSet, + true, + param.format === undefined && + (param as Parameter).location === "header" && + param.type.type === "datetime" + ? "headerDefault" + : param.format + )}`; } type ConstantType = (Parameter | Property) & { @@ -525,7 +557,17 @@ function getOptional(param: OptionalType, importSet: Map>) { importSet ).join(", ")}}`; } - return `"${param.restApiName}": options?.${param.clientName}`; + return `"${param.restApiName}": ${serializeRequestValue( + param.type, + `options?.${param.clientName}`, + importSet, + false, + param.format === undefined && + (param as Parameter).location === "header" && + param.type.type === "datetime" + ? "headerDefault" + : param.format + )}`; } /** @@ -598,7 +640,7 @@ function getRequestModelMapping( if (property.readonly) { continue; } - const propertyFullName = `${propertyPath}.${property.restApiName}`; + const propertyFullName = `${propertyPath}.${property.clientName}`; if (property.type.type === "model") { let definition; if (property.type.isCoreErrorType) { @@ -608,6 +650,17 @@ function getRequestModelMapping( )} ${ !property.optional ? "" : `!${propertyFullName} ? undefined :` } ${propertyFullName}`; + } else if ( + (property.restApiName === "message" || + property.restApiName === "messages") && + (property.type.name === "ChatMessage" || + property.type.elementType?.name === "ChatMessage") + ) { + definition = `"${property.restApiName}": ${ + !property.optional + ? `${propertyFullName} as any` + : `!${propertyFullName} ? undefined : ${propertyFullName} as any` + }`; } else { definition = `"${property.restApiName}": ${getNullableCheck( propertyFullName, @@ -616,24 +669,38 @@ function getRequestModelMapping( !property.optional ? "" : `!${propertyFullName} ? undefined :` } {${getRequestModelMapping( property.type, - `${propertyPath}.${property.restApiName}${ + `${propertyPath}.${property.clientName}${ property.optional ? "?" : "" }`, importSet )}}`; } + props.push(definition); + } else if ( + (property.restApiName === "message" || + property.restApiName === "messages") && + (property.type.name === "ChatMessage" || + property.type.elementType?.name === "ChatMessage") + ) { + const definition = `"${property.restApiName}": ${ + !property.optional + ? `${propertyFullName} as any` + : `!${propertyFullName} ? undefined : ${propertyFullName} as any` + }`; props.push(definition); } else { const dot = propertyPath.endsWith("?") ? "." : ""; - const restValue = `${ + const clientValue = `${ propertyPath ? `${propertyPath}${dot}` : `${dot}` }["${property.clientName}"]`; props.push( `"${property.restApiName}": ${serializeRequestValue( property.type, - restValue, - importSet + clientValue, + importSet, + !property.optional, + property.format )}` ); } @@ -697,7 +764,8 @@ export function getResponseMapping( propertyPath ? `${propertyPath}${dot}` : `${dot}` }["${property.restApiName}"]`; if ( - property.restApiName === "messages" && + (property.restApiName === "message" || + property.restApiName === "messages") && (property.type.name === "ChatMessage" || property.type.elementType?.name === "ChatMessage") ) { @@ -714,7 +782,8 @@ export function getResponseMapping( property.type, restValue, importSet, - property.optional !== undefined ? !property.optional : false + property.optional !== undefined ? !property.optional : false, + property.format )}` ); } @@ -733,7 +802,8 @@ function deserializeResponseValue( type: Type, restValue: string, importSet: Map>, - required: boolean + required: boolean, + format?: string ): string { const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { @@ -750,14 +820,13 @@ function deserializeResponseValue( "p", importSet )}}))`; - } else if ( - type.elementType?.properties?.some((p) => needsDeserialize(p.type)) - ) { + } else if (needsDeserialize(type.elementType)) { return `(${restValue} ?? []).map(p => ${deserializeResponseValue( type.elementType!, "p", importSet, - required + required, + type.elementType?.format )})`; } else { return restValue; @@ -772,7 +841,7 @@ function deserializeResponseValue( coreUtilSet.add("stringToUint8Array"); } return `typeof ${restValue} === 'string' - ? stringToUint8Array(${restValue}, "${type.format ?? "base64"}") + ? stringToUint8Array(${restValue}, "${format ?? "base64"}") : ${restValue}`; default: return restValue; @@ -786,30 +855,45 @@ function deserializeResponseValue( */ function serializeRequestValue( type: Type, - restValue: string, - importSet: Map> + clientValue: string, + importSet: Map>, + required: boolean, + format?: string ): string { const coreUtilSet = importSet.get("@azure/core-util"); switch (type.type) { case "datetime": - return `${restValue} !== undefined ? new Date(${restValue}): undefined`; + switch (type.format ?? format) { + case "date": + return `${clientValue}${required ? "" : "?"}.toDateString()`; + case "time": + return `${clientValue}${required ? "" : "?"}.toTimeString()`; + case "rfc7231": + case "headerDefault": + return `${clientValue}${required ? "" : "?"}.toUTCString()`; + case "unixTimestamp": + return `${clientValue}${required ? "" : "?"}.getTime()`; + case "rfc3339": + default: + return `${clientValue}${required ? "" : "?"}.toISOString()`; + } case "list": if (type.elementType?.type === "model") { - return `(${restValue} ?? []).map(p => ({${getRequestModelMapping( + return `(${clientValue} ?? []).map(p => ({${getRequestModelMapping( type.elementType, "p", importSet )}}))`; - } else if ( - type.elementType?.properties?.some((p) => needsDeserialize(p.type)) - ) { - return `(${restValue} ?? []).map(p => ${serializeRequestValue( + } else if (needsDeserialize(type.elementType)) { + return `(${clientValue} ?? []).map(p => ${serializeRequestValue( type.elementType!, "p", - importSet + importSet, + required, + type.elementType?.format )})`; } else { - return restValue; + return clientValue; } case "byte-array": if (!coreUtilSet) { @@ -820,16 +904,23 @@ function serializeRequestValue( } else { coreUtilSet.add("uint8ArrayToString"); } - return `${restValue} !== undefined ? uint8ArrayToString(${restValue}, "${ - type.format ?? "base64" - }"): undefined`; + return required + ? `uint8ArrayToString(${clientValue}, "${format ?? "base64"}")` + : `${clientValue} !== undefined ? uint8ArrayToString(${clientValue}, "${ + format ?? "base64" + }"): undefined`; default: - return restValue; + return clientValue; } } function needsDeserialize(type?: Type) { - return type?.type === "datetime" || type?.type === "model"; + return ( + type?.type === "datetime" || + type?.type === "model" || + type?.type === "list" || + type?.type === "byte-array" + ); } export function hasLROOperation(codeModel: ModularCodeModel) { diff --git a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts index 78bc5f60b3..2f9ad75345 100644 --- a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts @@ -15,7 +15,7 @@ function getNullableType(name: string, type: Type): string { return name; } -export function getType(type: Type): TypeMetadata { +export function getType(type: Type, format?: string): TypeMetadata { switch (type.type) { case "Key": return { @@ -58,7 +58,7 @@ export function getType(type: Type): TypeMetadata { throw new Error("Unable to process Array with no elementType"); } return { - name: getNullableType(getType(type.elementType).name, type), + name: getNullableType(getType(type.elementType, type.elementType.format).name, type), modifier: "Array", originModule: type.elementType?.type === "model" ? "models.js" : undefined @@ -73,14 +73,20 @@ export function getType(type: Type): TypeMetadata { }; case "string": case "duration": - return { name: getNullableType("string", type) }; + switch (format) { + case "seconds": + return { name: getNullableType("number", type) }; + case "ISO8601": + default: + return { name: getNullableType("string", type) }; + } case "combined": { if (!type.types) { throw new Error("Unable to process combined without combinedTypes"); } const name = type.types .map((t) => { - const sdkType = getTypeName(getType(t)); + const sdkType = getTypeName(getType(t, t.format)); return `${sdkType}`; }) .join(" | "); @@ -91,7 +97,7 @@ export function getType(type: Type): TypeMetadata { throw new Error("Unable to process dict without elemetType info"); } return { - name: `Record` + name: `Record` }; case "any": return { @@ -118,13 +124,14 @@ function getTypeName(typeMetadata: TypeMetadata) { */ export function buildType( clientName: string | undefined, - type: Type | undefined + type: Type | undefined, + format: string | undefined ) { if (!type) { throw new Error("Type should be defined"); } - const typeMetadata = getType(type); + const typeMetadata = getType(type, format); let typeName = typeMetadata.name; if (typeMetadata.modifier === "Array") { typeName = `${typeName}[]`; diff --git a/packages/typespec-ts/src/modular/modularCodeModel.ts b/packages/typespec-ts/src/modular/modularCodeModel.ts index b0d65b20e4..3ce025dfed 100644 --- a/packages/typespec-ts/src/modular/modularCodeModel.ts +++ b/packages/typespec-ts/src/modular/modularCodeModel.ts @@ -27,6 +27,7 @@ export interface Property { optional?: boolean; description: string; readonly?: boolean; + format?: string; } export interface BodyParameter { diff --git a/packages/typespec-ts/src/utils/modelUtils.ts b/packages/typespec-ts/src/utils/modelUtils.ts index 7c623002c4..deb02f8d77 100644 --- a/packages/typespec-ts/src/utils/modelUtils.ts +++ b/packages/typespec-ts/src/utils/modelUtils.ts @@ -900,10 +900,12 @@ function getSchemaForStdScalar( * if absent use typespec type (or default way of serializing that type) * if present respect type provided in @encode */ + let format = undefined; if (relevantProperty) { const encodeData = getEncode(program, relevantProperty); if (encodeData && isEncodeTypeEffective(type, encodeData)) { type = encodeData.type; + format = encodeData.encoding; } } const name = type.name; @@ -984,7 +986,7 @@ function getSchemaForStdScalar( case "plainDate": return { type: "string", - format: "date", + format, description, typeName: "Date | string", outputTypeName: "string" @@ -992,7 +994,7 @@ function getSchemaForStdScalar( case "utcDateTime": return { type: "string", - format: "date-time", + format, description, typeName: "Date | string", outputTypeName: "string" @@ -1014,7 +1016,7 @@ function getSchemaForStdScalar( outputTypeName: "string" }; case "duration": - return { type: "string", format: "duration", description }; + return { type: "string", format, description }; } } diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 22b19008bc..5bc608fb11 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -223,5 +223,17 @@ export const modularTsps: TypeSpecRanchConfig[] = [ { outputPath: "azure/core", inputPath: "azure/core/basic" + }, + { + outputPath: "encode/bytes", + inputPath: "encode/bytes" + }, + { + outputPath: "encode/duration", + inputPath: "encode/duration" + }, + { + outputPath: "encode/datetime", + inputPath: "encode/datetime" } ]; diff --git a/packages/typespec-ts/test/integration/generated/encode/bytes/src/index.ts b/packages/typespec-ts/test/integration/generated/encode/bytes/src/index.ts index 5548632499..a03f7a3538 100644 --- a/packages/typespec-ts/test/integration/generated/encode/bytes/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/encode/bytes/src/index.ts @@ -9,5 +9,6 @@ export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; export * from "./outputModels"; +export * from "./serializeHelper"; export default BytesClient; diff --git a/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts b/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts index 9cac785ece..9785cae7dd 100644 --- a/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/encode/datetime/src/index.ts @@ -9,5 +9,6 @@ export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; export * from "./outputModels"; +export * from "./serializeHelper"; export default DatetimeClient; diff --git a/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts b/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts index dcd6d09c74..0fc0d6db38 100644 --- a/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/encode/duration/src/index.ts @@ -9,5 +9,6 @@ export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; export * from "./outputModels"; +export * from "./serializeHelper"; export default DurationClient; diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts new file mode 100644 index 0000000000..dd1c2679a6 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -0,0 +1,159 @@ +import { assert } from "chai"; +import { BytesClient } from "./generated/encode/bytes/src/index"; +import { stringToUint8Array } from "@azure/core-util"; +describe("EncodeBytesClient Rest Client", () => { + let client: BytesClient; + + beforeEach(() => { + client = new BytesClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get bytes`, async () => { + try { + const result = await client.query.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64 encoding`, async () => { + try { + const result = await client.query.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url encoding`, async () => { + try { + const result = await client.query.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url-array`, async () => { + try { + const result = await client.query.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should post bytes`, async () => { + try { + const result = await client.property.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA==", "base64")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64 encoding`, async () => { + try { + const result = await client.property.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA==", "base64")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64url encoding`, async () => { + try { + const result = await client.property.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.deepEqual(result.value, stringToUint8Array("dGVzdA", "base64url")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should post bytes base64url array`, async () => { + try { + const result = await client.property.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.deepEqual(result.value, [ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get bytes`, async () => { + try { + const result = await client.header.default( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64 encoding`, async () => { + try { + const result = await client.header.base64( + stringToUint8Array("dGVzdA==", "base64") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url encoding`, async () => { + try { + const result = await client.header.base64url( + stringToUint8Array("dGVzdA", "base64url") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get bytes base64url-array`, async () => { + try { + const result = await client.header.base64urlArray([ + stringToUint8Array("dGVzdA", "base64url"), + stringToUint8Array("dGVzdA", "base64url") + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts new file mode 100644 index 0000000000..6a02e0a085 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeDatetime.spec.ts @@ -0,0 +1,182 @@ +import { assert } from "chai"; +import { DatetimeClient } from "./generated/encode/datetime/src/index"; +describe("EncodeDatetimeClient Rest Client", () => { + let client: DatetimeClient; + + beforeEach(() => { + client = new DatetimeClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.query.default( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.query.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.query.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.query.unixTimestamp(new Date(1686566864)); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.query.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.property.default( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.deepEqual(result.value, new Date("2022-08-26T18:38:00.000Z")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.property.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.deepEqual(result.value, new Date("2022-08-26T18:38:00.000Z")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.property.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.deepEqual(result.value, new Date("Fri, 26 Aug 2022 14:38:00 GMT")); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.property.unixTimestamp(new Date(1686566864)); + assert.deepEqual(result.value, new Date(1686566864)); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.property.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.deepEqual(result.value, [new Date(1686566864), new Date(1686734256)]); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get default datetime`, async () => { + try { + const result = await client.header.default( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc3339`, async () => { + try { + const result = await client.header.rfc3339( + new Date("2022-08-26T18:38:00.000Z") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get rfc7231`, async () => { + try { + const result = await client.header.rfc7231( + new Date("Fri, 26 Aug 2022 14:38:00 GMT") + ); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp`, async () => { + try { + const result = await client.header.unixTimestamp(new Date(1686566864)); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get unix timestamp-array`, async () => { + try { + const result = await client.header.unixTimestampArray([ + new Date(1686566864), + new Date(1686734256) + ]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts new file mode 100644 index 0000000000..fc1e0bed00 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/encodeDuration.spec.ts @@ -0,0 +1,157 @@ +import { assert } from "chai"; +import { DurationClient } from "./generated/encode/duration/src/index"; +describe("EncodeDurationClient Rest Client", () => { + let client: DurationClient; + + beforeEach(() => { + client = new DurationClient({ + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + } + }); + }); + + describe("query", () => { + it(`should get default duration`, async () => { + try { + const result = await client.query.default("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.query.iso8601("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.query.floatSeconds(35.621); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.query.int32Seconds(36); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.query.int32SecondsArray([36, 47]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("property", () => { + it(`should get default duration`, async () => { + try { + const result = await client.property.default("P40D"); + assert.deepEqual(result.value, "P40D"); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.property.iso8601("P40D"); + assert.deepEqual(result.value, "P40D"); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.property.floatSeconds(35.621); + assert.deepEqual(result.value, 35.621); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.property.int32Seconds(36); + assert.deepEqual(result.value, 36); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.property.floatSecondsArray([ + 35.621, 46.781 + ]); + assert.deepEqual(result.value, [35.621, 46.781]); + } catch (err) { + assert.fail(err as string); + } + }); + }); + + describe("header", () => { + it(`should get default duration`, async () => { + try { + const result = await client.header.default("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get iso8601 duration`, async () => { + try { + const result = await client.header.iso8601("P40D"); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get float seconds`, async () => { + try { + const result = await client.header.floatSeconds(35.621); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds`, async () => { + try { + const result = await client.header.int32Seconds(36); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + + it(`should get int32 seconds array`, async () => { + try { + const result = await client.header.iso8601Array(["P40D", "P50D"]); + assert.isUndefined(result); + } catch (err) { + assert.fail(err as string); + } + }); + }); +}); 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..6feb3389e3 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 @@ -56,7 +56,13 @@ export function _createOrUpdateSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { name: name, orders: options?.orders }, + body: { + name: name, + orders: (options?.orders ?? []).map((p) => ({ + userId: p["userId"], + detail: p["detail"], + })), + }, }); } @@ -107,7 +113,13 @@ export function _createOrReplaceSend( .path("/azure/core/basic/users/{id}", id) .put({ ...operationOptionsToRequestParameters(options), - body: { name: name, orders: options?.orders }, + body: { + name: name, + orders: (options?.orders ?? []).map((p) => ({ + userId: p["userId"], + detail: p["detail"], + })), + }, }); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts new file mode 100644 index 0000000000..dd3ad1c0dd --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/BytesClient.ts @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./models/options.js"; +import { + createBytes, + BytesClientOptions, + BytesContext, + headerDefault, + headerBase64, + headerBase64url, + headerBase64urlArray, + propertyDefault, + propertyBase64, + propertyBase64url, + propertyBase64urlArray, + queryDefault, + queryBase64, + queryBase64url, + queryBase64urlArray, +} from "./api/index.js"; + +export { BytesClientOptions } from "./api/BytesContext.js"; + +export class BytesClient { + private _client: BytesContext; + + /** Test for encode decorator on bytes. */ + constructor(options: BytesClientOptions = {}) { + this._client = createBytes(options); + } + + query = { + default: ( + value: Uint8Array, + options?: QueryDefaultOptions + ): Promise => { + return queryDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: QueryBase64Options + ): Promise => { + return queryBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: QueryBase64urlOptions + ): Promise => { + return queryBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: QueryBase64urlArrayOptions + ): Promise => { + return queryBase64urlArray(this._client, value, options); + }, + }; + property = { + default: ( + value: Uint8Array, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: PropertyBase64Options + ): Promise => { + return propertyBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: PropertyBase64urlOptions + ): Promise => { + return propertyBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: PropertyBase64urlArrayOptions + ): Promise => { + return propertyBase64urlArray(this._client, value, options); + }, + }; + header = { + default: ( + value: Uint8Array, + options?: HeaderDefaultOptions + ): Promise => { + return headerDefault(this._client, value, options); + }, + base64: ( + value: Uint8Array, + options?: HeaderBase64Options + ): Promise => { + return headerBase64(this._client, value, options); + }, + base64url: ( + value: Uint8Array, + options?: HeaderBase64urlOptions + ): Promise => { + return headerBase64url(this._client, value, options); + }, + base64urlArray: ( + value: Uint8Array[], + options?: HeaderBase64urlArrayOptions + ): Promise => { + return headerBase64urlArray(this._client, value, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts new file mode 100644 index 0000000000..d05b414bfe --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/BytesContext.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { BytesContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface BytesClientOptions extends ClientOptions {} + +export { BytesContext } from "../rest/index.js"; + +/** Test for encode decorator on bytes. */ +export function createBytes(options: BytesClientOptions = {}): BytesContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts new file mode 100644 index 0000000000..f354cd22ac --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/header.ts @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + buildCsvCollection, + BytesContext as Client, + HeaderBase64204Response, + HeaderBase64url204Response, + HeaderBase64urlArray204Response, + HeaderDefault204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + value: Uint8Array, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + value: Uint8Array, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, value, options); + return _headerDefaultDeserialize(result); +} + +export function _headerBase64Send( + context: Client, + value: Uint8Array, + options: HeaderBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _headerBase64Deserialize( + result: HeaderBase64204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64( + context: Client, + value: Uint8Array, + options: HeaderBase64Options = { requestOptions: {} } +): Promise { + const result = await _headerBase64Send(context, value, options); + return _headerBase64Deserialize(result); +} + +export function _headerBase64urlSend( + context: Client, + value: Uint8Array, + options: HeaderBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64url") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: uint8ArrayToString(value, "base64url") }, + }); +} + +export async function _headerBase64urlDeserialize( + result: HeaderBase64url204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64url( + context: Client, + value: Uint8Array, + options: HeaderBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _headerBase64urlSend(context, value, options); + return _headerBase64urlDeserialize(result); +} + +export function _headerBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: HeaderBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/header/base64url-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + value: buildCsvCollection( + (value ?? []).map((p) => uint8ArrayToString(p, "base64url")) + ), + }, + }); +} + +export async function _headerBase64urlArrayDeserialize( + result: HeaderBase64urlArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerBase64urlArray( + context: Client, + value: Uint8Array[], + options: HeaderBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerBase64urlArraySend(context, value, options); + return _headerBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts new file mode 100644 index 0000000000..5f7df54269 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createBytes, + BytesClientOptions, + BytesContext, +} from "./BytesContext.js"; +export { + headerDefault, + headerBase64, + headerBase64url, + headerBase64urlArray, +} from "./header.js"; +export { + propertyDefault, + propertyBase64, + propertyBase64url, + propertyBase64urlArray, +} from "./property.js"; +export { + queryDefault, + queryBase64, + queryBase64url, + queryBase64urlArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts new file mode 100644 index 0000000000..0f345df264 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/property.ts @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "../models/models.js"; +import { + BytesContext as Client, + PropertyBase64200Response, + PropertyBase64url200Response, + PropertyBase64urlArray200Response, + PropertyDefault200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; +import { + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: Uint8Array, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64") + : result.body["value"], + }; +} + +export async function propertyDefault( + context: Client, + value: Uint8Array, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyBase64Send( + context: Client, + value: Uint8Array, + options: PropertyBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _propertyBase64Deserialize( + result: PropertyBase64200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64") + : result.body["value"], + }; +} + +export async function propertyBase64( + context: Client, + value: Uint8Array, + options: PropertyBase64Options = { requestOptions: {} } +): Promise { + const result = await _propertyBase64Send(context, value, options); + return _propertyBase64Deserialize(result); +} + +export function _propertyBase64urlSend( + context: Client, + value: Uint8Array, + options: PropertyBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64url") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: uint8ArrayToString(value, "base64url") }, + }); +} + +export async function _propertyBase64urlDeserialize( + result: PropertyBase64url200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: + typeof result.body["value"] === "string" + ? stringToUint8Array(result.body["value"], "base64url") + : result.body["value"], + }; +} + +export async function propertyBase64url( + context: Client, + value: Uint8Array, + options: PropertyBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _propertyBase64urlSend(context, value, options); + return _propertyBase64urlDeserialize(result); +} + +export function _propertyBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: PropertyBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/property/base64url-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + value: (value ?? []).map((p) => uint8ArrayToString(p, "base64url")), + }, + }); +} + +export async function _propertyBase64urlArrayDeserialize( + result: PropertyBase64urlArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => + typeof p === "string" ? stringToUint8Array(p, "base64url") : p + ), + }; +} + +export async function propertyBase64urlArray( + context: Client, + value: Uint8Array[], + options: PropertyBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyBase64urlArraySend(context, value, options); + return _propertyBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts new file mode 100644 index 0000000000..fe03bfd668 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/api/query.ts @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + BytesContext as Client, + QueryBase64204Response, + QueryBase64url204Response, + QueryBase64urlArray204Response, + QueryDefault204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + value: Uint8Array, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + value: Uint8Array, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, value, options); + return _queryDefaultDeserialize(result); +} + +export function _queryBase64Send( + context: Client, + value: Uint8Array, + options: QueryBase64Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: uint8ArrayToString(value, "base64") }, + }); +} + +export async function _queryBase64Deserialize( + result: QueryBase64204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64( + context: Client, + value: Uint8Array, + options: QueryBase64Options = { requestOptions: {} } +): Promise { + const result = await _queryBase64Send(context, value, options); + return _queryBase64Deserialize(result); +} + +export function _queryBase64urlSend( + context: Client, + value: Uint8Array, + options: QueryBase64urlOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64url") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: uint8ArrayToString(value, "base64url") }, + }); +} + +export async function _queryBase64urlDeserialize( + result: QueryBase64url204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64url( + context: Client, + value: Uint8Array, + options: QueryBase64urlOptions = { requestOptions: {} } +): Promise { + const result = await _queryBase64urlSend(context, value, options); + return _queryBase64urlDeserialize(result); +} + +export function _queryBase64urlArraySend( + context: Client, + value: Uint8Array[], + options: QueryBase64urlArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/bytes/query/base64url-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + value: (value ?? []).map((p) => uint8ArrayToString(p, "base64url")), + }, + }); +} + +export async function _queryBase64urlArrayDeserialize( + result: QueryBase64urlArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryBase64urlArray( + context: Client, + value: Uint8Array[], + options: QueryBase64urlArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryBase64urlArraySend(context, value, options); + return _queryBase64urlArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts new file mode 100644 index 0000000000..e2daf3d2e1 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { BytesClient, BytesClientOptions } from "./BytesClient.js"; +export { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/logger.ts new file mode 100644 index 0000000000..370150902d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/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("encode-bytes"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts new file mode 100644 index 0000000000..7dac823549 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/index.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryBase64Options, + QueryBase64urlOptions, + QueryBase64urlArrayOptions, + PropertyDefaultOptions, + PropertyBase64Options, + PropertyBase64urlOptions, + PropertyBase64urlArrayOptions, + HeaderDefaultOptions, + HeaderBase64Options, + HeaderBase64urlOptions, + HeaderBase64urlArrayOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts new file mode 100644 index 0000000000..a5c4bdd415 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesProperty { + value: Uint8Array; +} + +export interface Base64BytesProperty { + value: Uint8Array; +} + +export interface Base64urlBytesProperty { + value: Uint8Array; +} + +export interface Base64urlArrayBytesProperty { + value: Uint8Array[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts new file mode 100644 index 0000000000..e57487c598 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/models/options.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryBase64Options extends OperationOptions {} + +export interface QueryBase64urlOptions extends OperationOptions {} + +export interface QueryBase64urlArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyBase64Options extends OperationOptions {} + +export interface PropertyBase64urlOptions extends OperationOptions {} + +export interface PropertyBase64urlArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderBase64Options extends OperationOptions {} + +export interface HeaderBase64urlOptions extends OperationOptions {} + +export interface HeaderBase64urlArrayOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.ts new file mode 100644 index 0000000000..f8b0556248 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/bytesClient.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 { BytesContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `BytesContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): BytesContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-bytes-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 BytesContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..8bad05bb6e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/clientDefinitions.ts @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryBase64Parameters, + QueryBase64urlParameters, + QueryBase64urlArrayParameters, + PropertyDefaultParameters, + PropertyBase64Parameters, + PropertyBase64urlParameters, + PropertyBase64urlArrayParameters, + HeaderDefaultParameters, + HeaderBase64Parameters, + HeaderBase64urlParameters, + HeaderBase64urlArrayParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryBase64204Response, + QueryBase64url204Response, + QueryBase64urlArray204Response, + PropertyDefault200Response, + PropertyBase64200Response, + PropertyBase64url200Response, + PropertyBase64urlArray200Response, + HeaderDefault204Response, + HeaderBase64204Response, + HeaderBase64url204Response, + HeaderBase64urlArray204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryBase64 { + get(options: QueryBase64Parameters): StreamableMethod; +} + +export interface QueryBase64url { + get( + options: QueryBase64urlParameters + ): StreamableMethod; +} + +export interface QueryBase64urlArray { + get( + options: QueryBase64urlArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyBase64 { + post( + options: PropertyBase64Parameters + ): StreamableMethod; +} + +export interface PropertyBase64url { + post( + options: PropertyBase64urlParameters + ): StreamableMethod; +} + +export interface PropertyBase64urlArray { + post( + options: PropertyBase64urlArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderBase64 { + get( + options: HeaderBase64Parameters + ): StreamableMethod; +} + +export interface HeaderBase64url { + get( + options: HeaderBase64urlParameters + ): StreamableMethod; +} + +export interface HeaderBase64urlArray { + get( + options: HeaderBase64urlArrayParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/bytes/query/default' has methods for the following verbs: get */ + (path: "/encode/bytes/query/default"): QueryDefault; + /** Resource for '/encode/bytes/query/base64' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64"): QueryBase64; + /** Resource for '/encode/bytes/query/base64url' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64url"): QueryBase64url; + /** Resource for '/encode/bytes/query/base64url-array' has methods for the following verbs: get */ + (path: "/encode/bytes/query/base64url-array"): QueryBase64urlArray; + /** Resource for '/encode/bytes/property/default' has methods for the following verbs: post */ + (path: "/encode/bytes/property/default"): PropertyDefault; + /** Resource for '/encode/bytes/property/base64' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64"): PropertyBase64; + /** Resource for '/encode/bytes/property/base64url' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64url"): PropertyBase64url; + /** Resource for '/encode/bytes/property/base64url-array' has methods for the following verbs: post */ + (path: "/encode/bytes/property/base64url-array"): PropertyBase64urlArray; + /** Resource for '/encode/bytes/header/default' has methods for the following verbs: get */ + (path: "/encode/bytes/header/default"): HeaderDefault; + /** Resource for '/encode/bytes/header/base64' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64"): HeaderBase64; + /** Resource for '/encode/bytes/header/base64url' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64url"): HeaderBase64url; + /** Resource for '/encode/bytes/header/base64url-array' has methods for the following verbs: get */ + (path: "/encode/bytes/header/base64url-array"): HeaderBase64urlArray; +} + +export type BytesContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts new file mode 100644 index 0000000000..65eda613f6 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import BytesClient from "./bytesClient.js"; + +export * from "./bytesClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; +export * from "./serializeHelper.js"; + +export default BytesClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts new file mode 100644 index 0000000000..e318f7928d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/models.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesProperty { + value: string; +} + +export interface Base64BytesProperty { + value: string; +} + +export interface Base64urlBytesProperty { + value: string; +} + +export interface Base64urlArrayBytesProperty { + value: string[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts new file mode 100644 index 0000000000..66195f40c4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/outputModels.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultBytesPropertyOutput { + value: string; +} + +export interface Base64BytesPropertyOutput { + value: string; +} + +export interface Base64urlBytesPropertyOutput { + value: string; +} + +export interface Base64urlArrayBytesPropertyOutput { + value: string[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts new file mode 100644 index 0000000000..629e71eff7 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/parameters.ts @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultBytesProperty, + Base64BytesProperty, + Base64urlBytesProperty, + Base64urlArrayBytesProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + value: string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryBase64QueryParamProperties { + value: string; +} + +export interface QueryBase64QueryParam { + queryParameters: QueryBase64QueryParamProperties; +} + +export type QueryBase64Parameters = QueryBase64QueryParam & RequestParameters; + +export interface QueryBase64urlQueryParamProperties { + value: string; +} + +export interface QueryBase64urlQueryParam { + queryParameters: QueryBase64urlQueryParamProperties; +} + +export type QueryBase64urlParameters = QueryBase64urlQueryParam & + RequestParameters; + +export interface QueryBase64urlArrayQueryParamProperties { + value: string[]; +} + +export interface QueryBase64urlArrayQueryParam { + queryParameters: QueryBase64urlArrayQueryParamProperties; +} + +export type QueryBase64urlArrayParameters = QueryBase64urlArrayQueryParam & + RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultBytesProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyBase64BodyParam { + body: Base64BytesProperty; +} + +export type PropertyBase64Parameters = PropertyBase64BodyParam & + RequestParameters; + +export interface PropertyBase64urlBodyParam { + body: Base64urlBytesProperty; +} + +export type PropertyBase64urlParameters = PropertyBase64urlBodyParam & + RequestParameters; + +export interface PropertyBase64urlArrayBodyParam { + body: Base64urlArrayBytesProperty; +} + +export type PropertyBase64urlArrayParameters = PropertyBase64urlArrayBodyParam & + RequestParameters; + +export interface HeaderDefaultHeaders { + value: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderBase64Headers { + value: string; +} + +export interface HeaderBase64HeaderParam { + headers: RawHttpHeadersInput & HeaderBase64Headers; +} + +export type HeaderBase64Parameters = HeaderBase64HeaderParam & + RequestParameters; + +export interface HeaderBase64urlHeaders { + value: string; +} + +export interface HeaderBase64urlHeaderParam { + headers: RawHttpHeadersInput & HeaderBase64urlHeaders; +} + +export type HeaderBase64urlParameters = HeaderBase64urlHeaderParam & + RequestParameters; + +export interface HeaderBase64urlArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + value: string; +} + +export interface HeaderBase64urlArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderBase64urlArrayHeaders; +} + +export type HeaderBase64urlArrayParameters = HeaderBase64urlArrayHeaderParam & + RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts new file mode 100644 index 0000000000..302790a12f --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/responses.ts @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultBytesPropertyOutput, + Base64BytesPropertyOutput, + Base64urlBytesPropertyOutput, + Base64urlArrayBytesPropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64url204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryBase64urlArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultBytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64200Response extends HttpResponse { + status: "200"; + body: Base64BytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64url200Response extends HttpResponse { + status: "200"; + body: Base64urlBytesPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyBase64urlArray200Response extends HttpResponse { + status: "200"; + body: Base64urlArrayBytesPropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64url204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderBase64urlArray204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/tspconfig.yaml new file mode 100644 index 0000000000..f43d04c270 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/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 + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-bytes" diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts new file mode 100644 index 0000000000..ff1c463643 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/DatetimeClient.ts @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./models/options.js"; +import { + createDatetime, + DatetimeClientOptions, + DatetimeContext, + headerDefault, + headerRfc3339, + headerRfc7231, + headerUnixTimestamp, + headerUnixTimestampArray, + propertyDefault, + propertyRfc3339, + propertyRfc7231, + propertyUnixTimestamp, + propertyUnixTimestampArray, + queryDefault, + queryRfc3339, + queryRfc7231, + queryUnixTimestamp, + queryUnixTimestampArray, +} from "./api/index.js"; + +export { DatetimeClientOptions } from "./api/DatetimeContext.js"; + +export class DatetimeClient { + private _client: DatetimeContext; + + /** Test for encode decorator on datetime. */ + constructor(options: DatetimeClientOptions = {}) { + this._client = createDatetime(options); + } + + query = { + default: (value: Date, options?: QueryDefaultOptions): Promise => { + return queryDefault(this._client, value, options); + }, + rfc3339: (value: Date, options?: QueryRfc3339Options): Promise => { + return queryRfc3339(this._client, value, options); + }, + rfc7231: (value: Date, options?: QueryRfc7231Options): Promise => { + return queryRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: QueryUnixTimestampOptions + ): Promise => { + return queryUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: QueryUnixTimestampArrayOptions + ): Promise => { + return queryUnixTimestampArray(this._client, value, options); + }, + }; + property = { + default: ( + value: Date, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + rfc3339: ( + value: Date, + options?: PropertyRfc3339Options + ): Promise => { + return propertyRfc3339(this._client, value, options); + }, + rfc7231: ( + value: Date, + options?: PropertyRfc7231Options + ): Promise => { + return propertyRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: PropertyUnixTimestampOptions + ): Promise => { + return propertyUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: PropertyUnixTimestampArrayOptions + ): Promise => { + return propertyUnixTimestampArray(this._client, value, options); + }, + }; + header = { + default: (value: Date, options?: HeaderDefaultOptions): Promise => { + return headerDefault(this._client, value, options); + }, + rfc3339: (value: Date, options?: HeaderRfc3339Options): Promise => { + return headerRfc3339(this._client, value, options); + }, + rfc7231: (value: Date, options?: HeaderRfc7231Options): Promise => { + return headerRfc7231(this._client, value, options); + }, + unixTimestamp: ( + value: Date, + options?: HeaderUnixTimestampOptions + ): Promise => { + return headerUnixTimestamp(this._client, value, options); + }, + unixTimestampArray: ( + value: Date[], + options?: HeaderUnixTimestampArrayOptions + ): Promise => { + return headerUnixTimestampArray(this._client, value, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts new file mode 100644 index 0000000000..6efab496bf --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/DatetimeContext.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { DatetimeContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface DatetimeClientOptions extends ClientOptions {} + +export { DatetimeContext } from "../rest/index.js"; + +/** Test for encode decorator on datetime. */ +export function createDatetime( + options: DatetimeClientOptions = {} +): DatetimeContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts new file mode 100644 index 0000000000..5b291b3b69 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/header.ts @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + buildCsvCollection, + DatetimeContext as Client, + HeaderDefault204Response, + HeaderRfc3339204Response, + HeaderRfc7231204Response, + HeaderUnixTimestamp204Response, + HeaderUnixTimestampArray204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + value: Date, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value.toUTCString() }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + value: Date, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, value, options); + return _headerDefaultDeserialize(result); +} + +export function _headerRfc3339Send( + context: Client, + value: Date, + options: HeaderRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/rfc3339") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value.toISOString() }, + }); +} + +export async function _headerRfc3339Deserialize( + result: HeaderRfc3339204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerRfc3339( + context: Client, + value: Date, + options: HeaderRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _headerRfc3339Send(context, value, options); + return _headerRfc3339Deserialize(result); +} + +export function _headerRfc7231Send( + context: Client, + value: Date, + options: HeaderRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/rfc7231") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value.toUTCString() }, + }); +} + +export async function _headerRfc7231Deserialize( + result: HeaderRfc7231204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerRfc7231( + context: Client, + value: Date, + options: HeaderRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _headerRfc7231Send(context, value, options); + return _headerRfc7231Deserialize(result); +} + +export function _headerUnixTimestampSend( + context: Client, + value: Date, + options: HeaderUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/unix-timestamp") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { value: value.getTime() }, + }); +} + +export async function _headerUnixTimestampDeserialize( + result: HeaderUnixTimestamp204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerUnixTimestamp( + context: Client, + value: Date, + options: HeaderUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _headerUnixTimestampSend(context, value, options); + return _headerUnixTimestampDeserialize(result); +} + +export function _headerUnixTimestampArraySend( + context: Client, + value: Date[], + options: HeaderUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/header/unix-timestamp-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + value: buildCsvCollection((value ?? []).map((p) => p.getTime())), + }, + }); +} + +export async function _headerUnixTimestampArrayDeserialize( + result: HeaderUnixTimestampArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerUnixTimestampArray( + context: Client, + value: Date[], + options: HeaderUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerUnixTimestampArraySend(context, value, options); + return _headerUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts new file mode 100644 index 0000000000..ca55c56612 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/index.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createDatetime, + DatetimeClientOptions, + DatetimeContext, +} from "./DatetimeContext.js"; +export { + headerDefault, + headerRfc3339, + headerRfc7231, + headerUnixTimestamp, + headerUnixTimestampArray, +} from "./header.js"; +export { + propertyDefault, + propertyRfc3339, + propertyRfc7231, + propertyUnixTimestamp, + propertyUnixTimestampArray, +} from "./property.js"; +export { + queryDefault, + queryRfc3339, + queryRfc7231, + queryUnixTimestamp, + queryUnixTimestampArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts new file mode 100644 index 0000000000..9f0173a0e4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/property.ts @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "../models/models.js"; +import { + DatetimeContext as Client, + PropertyDefault200Response, + PropertyRfc3339200Response, + PropertyRfc7231200Response, + PropertyUnixTimestamp200Response, + PropertyUnixTimestampArray200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: Date, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value.toISOString() }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyDefault( + context: Client, + value: Date, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyRfc3339Send( + context: Client, + value: Date, + options: PropertyRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/rfc3339") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value.toISOString() }, + }); +} + +export async function _propertyRfc3339Deserialize( + result: PropertyRfc3339200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyRfc3339( + context: Client, + value: Date, + options: PropertyRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _propertyRfc3339Send(context, value, options); + return _propertyRfc3339Deserialize(result); +} + +export function _propertyRfc7231Send( + context: Client, + value: Date, + options: PropertyRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/rfc7231") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value.toUTCString() }, + }); +} + +export async function _propertyRfc7231Deserialize( + result: PropertyRfc7231200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyRfc7231( + context: Client, + value: Date, + options: PropertyRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _propertyRfc7231Send(context, value, options); + return _propertyRfc7231Deserialize(result); +} + +export function _propertyUnixTimestampSend( + context: Client, + value: Date, + options: PropertyUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/unix-timestamp") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value.getTime() }, + }); +} + +export async function _propertyUnixTimestampDeserialize( + result: PropertyUnixTimestamp200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: new Date(result.body["value"]), + }; +} + +export async function propertyUnixTimestamp( + context: Client, + value: Date, + options: PropertyUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _propertyUnixTimestampSend(context, value, options); + return _propertyUnixTimestampDeserialize(result); +} + +export function _propertyUnixTimestampArraySend( + context: Client, + value: Date[], + options: PropertyUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/property/unix-timestamp-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: (value ?? []).map((p) => p.getTime()) }, + }); +} + +export async function _propertyUnixTimestampArrayDeserialize( + result: PropertyUnixTimestampArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => new Date(p)), + }; +} + +export async function propertyUnixTimestampArray( + context: Client, + value: Date[], + options: PropertyUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyUnixTimestampArraySend(context, value, options); + return _propertyUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts new file mode 100644 index 0000000000..ffce73a4fe --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/api/query.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DatetimeContext as Client, + QueryDefault204Response, + QueryRfc3339204Response, + QueryRfc7231204Response, + QueryUnixTimestamp204Response, + QueryUnixTimestampArray204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + value: Date, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value.toISOString() }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + value: Date, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, value, options); + return _queryDefaultDeserialize(result); +} + +export function _queryRfc3339Send( + context: Client, + value: Date, + options: QueryRfc3339Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/rfc3339") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value.toISOString() }, + }); +} + +export async function _queryRfc3339Deserialize( + result: QueryRfc3339204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryRfc3339( + context: Client, + value: Date, + options: QueryRfc3339Options = { requestOptions: {} } +): Promise { + const result = await _queryRfc3339Send(context, value, options); + return _queryRfc3339Deserialize(result); +} + +export function _queryRfc7231Send( + context: Client, + value: Date, + options: QueryRfc7231Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/rfc7231") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value.toUTCString() }, + }); +} + +export async function _queryRfc7231Deserialize( + result: QueryRfc7231204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryRfc7231( + context: Client, + value: Date, + options: QueryRfc7231Options = { requestOptions: {} } +): Promise { + const result = await _queryRfc7231Send(context, value, options); + return _queryRfc7231Deserialize(result); +} + +export function _queryUnixTimestampSend( + context: Client, + value: Date, + options: QueryUnixTimestampOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/unix-timestamp") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: value.getTime() }, + }); +} + +export async function _queryUnixTimestampDeserialize( + result: QueryUnixTimestamp204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryUnixTimestamp( + context: Client, + value: Date, + options: QueryUnixTimestampOptions = { requestOptions: {} } +): Promise { + const result = await _queryUnixTimestampSend(context, value, options); + return _queryUnixTimestampDeserialize(result); +} + +export function _queryUnixTimestampArraySend( + context: Client, + value: Date[], + options: QueryUnixTimestampArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/datetime/query/unix-timestamp-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { value: (value ?? []).map((p) => p.getTime()) }, + }); +} + +export async function _queryUnixTimestampArrayDeserialize( + result: QueryUnixTimestampArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryUnixTimestampArray( + context: Client, + value: Date[], + options: QueryUnixTimestampArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryUnixTimestampArraySend(context, value, options); + return _queryUnixTimestampArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts new file mode 100644 index 0000000000..db7b5809d5 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { DatetimeClient, DatetimeClientOptions } from "./DatetimeClient.js"; +export { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/logger.ts new file mode 100644 index 0000000000..f3e4c0f4f4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/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("encode-datatime"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts new file mode 100644 index 0000000000..a28faa2ffb --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryRfc3339Options, + QueryRfc7231Options, + QueryUnixTimestampOptions, + QueryUnixTimestampArrayOptions, + PropertyDefaultOptions, + PropertyRfc3339Options, + PropertyRfc7231Options, + PropertyUnixTimestampOptions, + PropertyUnixTimestampArrayOptions, + HeaderDefaultOptions, + HeaderRfc3339Options, + HeaderRfc7231Options, + HeaderUnixTimestampOptions, + HeaderUnixTimestampArrayOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts new file mode 100644 index 0000000000..11e83eab15 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimeProperty { + value: Date; +} + +export interface Rfc3339DatetimeProperty { + value: Date; +} + +export interface Rfc7231DatetimeProperty { + value: Date; +} + +export interface UnixTimestampDatetimeProperty { + value: Date; +} + +export interface UnixTimestampArrayDatetimeProperty { + value: Date[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts new file mode 100644 index 0000000000..264e8163e3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/models/options.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryRfc3339Options extends OperationOptions {} + +export interface QueryRfc7231Options extends OperationOptions {} + +export interface QueryUnixTimestampOptions extends OperationOptions {} + +export interface QueryUnixTimestampArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyRfc3339Options extends OperationOptions {} + +export interface PropertyRfc7231Options extends OperationOptions {} + +export interface PropertyUnixTimestampOptions extends OperationOptions {} + +export interface PropertyUnixTimestampArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderRfc3339Options extends OperationOptions {} + +export interface HeaderRfc7231Options extends OperationOptions {} + +export interface HeaderUnixTimestampOptions extends OperationOptions {} + +export interface HeaderUnixTimestampArrayOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..0cbfb4245b --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/clientDefinitions.ts @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryRfc3339Parameters, + QueryRfc7231Parameters, + QueryUnixTimestampParameters, + QueryUnixTimestampArrayParameters, + PropertyDefaultParameters, + PropertyRfc3339Parameters, + PropertyRfc7231Parameters, + PropertyUnixTimestampParameters, + PropertyUnixTimestampArrayParameters, + HeaderDefaultParameters, + HeaderRfc3339Parameters, + HeaderRfc7231Parameters, + HeaderUnixTimestampParameters, + HeaderUnixTimestampArrayParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryRfc3339204Response, + QueryRfc7231204Response, + QueryUnixTimestamp204Response, + QueryUnixTimestampArray204Response, + PropertyDefault200Response, + PropertyRfc3339200Response, + PropertyRfc7231200Response, + PropertyUnixTimestamp200Response, + PropertyUnixTimestampArray200Response, + HeaderDefault204Response, + HeaderRfc3339204Response, + HeaderRfc7231204Response, + HeaderUnixTimestamp204Response, + HeaderUnixTimestampArray204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryRfc3339 { + get( + options: QueryRfc3339Parameters + ): StreamableMethod; +} + +export interface QueryRfc7231 { + get( + options: QueryRfc7231Parameters + ): StreamableMethod; +} + +export interface QueryUnixTimestamp { + get( + options: QueryUnixTimestampParameters + ): StreamableMethod; +} + +export interface QueryUnixTimestampArray { + get( + options: QueryUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyRfc3339 { + post( + options: PropertyRfc3339Parameters + ): StreamableMethod; +} + +export interface PropertyRfc7231 { + post( + options: PropertyRfc7231Parameters + ): StreamableMethod; +} + +export interface PropertyUnixTimestamp { + post( + options: PropertyUnixTimestampParameters + ): StreamableMethod; +} + +export interface PropertyUnixTimestampArray { + post( + options: PropertyUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderRfc3339 { + get( + options: HeaderRfc3339Parameters + ): StreamableMethod; +} + +export interface HeaderRfc7231 { + get( + options: HeaderRfc7231Parameters + ): StreamableMethod; +} + +export interface HeaderUnixTimestamp { + get( + options: HeaderUnixTimestampParameters + ): StreamableMethod; +} + +export interface HeaderUnixTimestampArray { + get( + options: HeaderUnixTimestampArrayParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/datetime/query/default' has methods for the following verbs: get */ + (path: "/encode/datetime/query/default"): QueryDefault; + /** Resource for '/encode/datetime/query/rfc3339' has methods for the following verbs: get */ + (path: "/encode/datetime/query/rfc3339"): QueryRfc3339; + /** Resource for '/encode/datetime/query/rfc7231' has methods for the following verbs: get */ + (path: "/encode/datetime/query/rfc7231"): QueryRfc7231; + /** Resource for '/encode/datetime/query/unix-timestamp' has methods for the following verbs: get */ + (path: "/encode/datetime/query/unix-timestamp"): QueryUnixTimestamp; + /** Resource for '/encode/datetime/query/unix-timestamp-array' has methods for the following verbs: get */ + ( + path: "/encode/datetime/query/unix-timestamp-array" + ): QueryUnixTimestampArray; + /** Resource for '/encode/datetime/property/default' has methods for the following verbs: post */ + (path: "/encode/datetime/property/default"): PropertyDefault; + /** Resource for '/encode/datetime/property/rfc3339' has methods for the following verbs: post */ + (path: "/encode/datetime/property/rfc3339"): PropertyRfc3339; + /** Resource for '/encode/datetime/property/rfc7231' has methods for the following verbs: post */ + (path: "/encode/datetime/property/rfc7231"): PropertyRfc7231; + /** Resource for '/encode/datetime/property/unix-timestamp' has methods for the following verbs: post */ + (path: "/encode/datetime/property/unix-timestamp"): PropertyUnixTimestamp; + /** Resource for '/encode/datetime/property/unix-timestamp-array' has methods for the following verbs: post */ + ( + path: "/encode/datetime/property/unix-timestamp-array" + ): PropertyUnixTimestampArray; + /** Resource for '/encode/datetime/header/default' has methods for the following verbs: get */ + (path: "/encode/datetime/header/default"): HeaderDefault; + /** Resource for '/encode/datetime/header/rfc3339' has methods for the following verbs: get */ + (path: "/encode/datetime/header/rfc3339"): HeaderRfc3339; + /** Resource for '/encode/datetime/header/rfc7231' has methods for the following verbs: get */ + (path: "/encode/datetime/header/rfc7231"): HeaderRfc7231; + /** Resource for '/encode/datetime/header/unix-timestamp' has methods for the following verbs: get */ + (path: "/encode/datetime/header/unix-timestamp"): HeaderUnixTimestamp; + /** Resource for '/encode/datetime/header/unix-timestamp-array' has methods for the following verbs: get */ + ( + path: "/encode/datetime/header/unix-timestamp-array" + ): HeaderUnixTimestampArray; +} + +export type DatetimeContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.ts new file mode 100644 index 0000000000..eadbf6b783 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/datetimeClient.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 { DatetimeContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `DatetimeContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): DatetimeContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-datatime-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 DatetimeContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts new file mode 100644 index 0000000000..f795d62955 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import DatetimeClient from "./datetimeClient.js"; + +export * from "./datetimeClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; +export * from "./serializeHelper.js"; + +export default DatetimeClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts new file mode 100644 index 0000000000..ae51efd66e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimeProperty { + value: Date | string; +} + +export interface Rfc3339DatetimeProperty { + value: Date | string; +} + +export interface Rfc7231DatetimeProperty { + value: Date | string; +} + +export interface UnixTimestampDatetimeProperty { + value: number; +} + +export interface UnixTimestampArrayDatetimeProperty { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts new file mode 100644 index 0000000000..51c6afbd5e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/outputModels.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDatetimePropertyOutput { + value: string; +} + +export interface Rfc3339DatetimePropertyOutput { + value: string; +} + +export interface Rfc7231DatetimePropertyOutput { + value: string; +} + +export interface UnixTimestampDatetimePropertyOutput { + value: number; +} + +export interface UnixTimestampArrayDatetimePropertyOutput { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts new file mode 100644 index 0000000000..ba029da0b3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/parameters.ts @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultDatetimeProperty, + Rfc3339DatetimeProperty, + Rfc7231DatetimeProperty, + UnixTimestampDatetimeProperty, + UnixTimestampArrayDatetimeProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + value: Date | string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryRfc3339QueryParamProperties { + value: Date | string; +} + +export interface QueryRfc3339QueryParam { + queryParameters: QueryRfc3339QueryParamProperties; +} + +export type QueryRfc3339Parameters = QueryRfc3339QueryParam & RequestParameters; + +export interface QueryRfc7231QueryParamProperties { + value: Date | string; +} + +export interface QueryRfc7231QueryParam { + queryParameters: QueryRfc7231QueryParamProperties; +} + +export type QueryRfc7231Parameters = QueryRfc7231QueryParam & RequestParameters; + +export interface QueryUnixTimestampQueryParamProperties { + value: number; +} + +export interface QueryUnixTimestampQueryParam { + queryParameters: QueryUnixTimestampQueryParamProperties; +} + +export type QueryUnixTimestampParameters = QueryUnixTimestampQueryParam & + RequestParameters; + +export interface QueryUnixTimestampArrayQueryParamProperties { + value: number[]; +} + +export interface QueryUnixTimestampArrayQueryParam { + queryParameters: QueryUnixTimestampArrayQueryParamProperties; +} + +export type QueryUnixTimestampArrayParameters = + QueryUnixTimestampArrayQueryParam & RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultDatetimeProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyRfc3339BodyParam { + body: Rfc3339DatetimeProperty; +} + +export type PropertyRfc3339Parameters = PropertyRfc3339BodyParam & + RequestParameters; + +export interface PropertyRfc7231BodyParam { + body: Rfc7231DatetimeProperty; +} + +export type PropertyRfc7231Parameters = PropertyRfc7231BodyParam & + RequestParameters; + +export interface PropertyUnixTimestampBodyParam { + body: UnixTimestampDatetimeProperty; +} + +export type PropertyUnixTimestampParameters = PropertyUnixTimestampBodyParam & + RequestParameters; + +export interface PropertyUnixTimestampArrayBodyParam { + body: UnixTimestampArrayDatetimeProperty; +} + +export type PropertyUnixTimestampArrayParameters = + PropertyUnixTimestampArrayBodyParam & RequestParameters; + +export interface HeaderDefaultHeaders { + value: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderRfc3339Headers { + value: string; +} + +export interface HeaderRfc3339HeaderParam { + headers: RawHttpHeadersInput & HeaderRfc3339Headers; +} + +export type HeaderRfc3339Parameters = HeaderRfc3339HeaderParam & + RequestParameters; + +export interface HeaderRfc7231Headers { + value: string; +} + +export interface HeaderRfc7231HeaderParam { + headers: RawHttpHeadersInput & HeaderRfc7231Headers; +} + +export type HeaderRfc7231Parameters = HeaderRfc7231HeaderParam & + RequestParameters; + +export interface HeaderUnixTimestampHeaders { + value: number; +} + +export interface HeaderUnixTimestampHeaderParam { + headers: RawHttpHeadersInput & HeaderUnixTimestampHeaders; +} + +export type HeaderUnixTimestampParameters = HeaderUnixTimestampHeaderParam & + RequestParameters; + +export interface HeaderUnixTimestampArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + value: string; +} + +export interface HeaderUnixTimestampArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderUnixTimestampArrayHeaders; +} + +export type HeaderUnixTimestampArrayParameters = + HeaderUnixTimestampArrayHeaderParam & RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts new file mode 100644 index 0000000000..0b0101e9ba --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/responses.ts @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultDatetimePropertyOutput, + Rfc3339DatetimePropertyOutput, + Rfc7231DatetimePropertyOutput, + UnixTimestampDatetimePropertyOutput, + UnixTimestampArrayDatetimePropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryRfc3339204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryRfc7231204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryUnixTimestamp204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryUnixTimestampArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultDatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyRfc3339200Response extends HttpResponse { + status: "200"; + body: Rfc3339DatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyRfc7231200Response extends HttpResponse { + status: "200"; + body: Rfc7231DatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyUnixTimestamp200Response extends HttpResponse { + status: "200"; + body: UnixTimestampDatetimePropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyUnixTimestampArray200Response extends HttpResponse { + status: "200"; + body: UnixTimestampArrayDatetimePropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderRfc3339204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderRfc7231204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderUnixTimestamp204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderUnixTimestampArray204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/tspconfig.yaml new file mode 100644 index 0000000000..03aecac2c6 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/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 + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-datatime" diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts new file mode 100644 index 0000000000..c5d57d72a9 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/DurationClient.ts @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models/models.js"; +import { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./models/options.js"; +import { + createDuration, + DurationClientOptions, + DurationContext, + headerDefault, + headerIso8601, + headerIso8601Array, + headerInt32Seconds, + headerFloatSeconds, + propertyDefault, + propertyIso8601, + propertyInt32Seconds, + propertyFloatSeconds, + propertyFloatSecondsArray, + queryDefault, + queryIso8601, + queryInt32Seconds, + queryFloatSeconds, + queryInt32SecondsArray, +} from "./api/index.js"; + +export { DurationClientOptions } from "./api/DurationContext.js"; + +export class DurationClient { + private _client: DurationContext; + + /** Test for encode decorator on duration. */ + constructor(options: DurationClientOptions = {}) { + this._client = createDuration(options); + } + + query = { + default: (input: string, options?: QueryDefaultOptions): Promise => { + return queryDefault(this._client, input, options); + }, + iso8601: (input: string, options?: QueryIso8601Options): Promise => { + return queryIso8601(this._client, input, options); + }, + int32Seconds: ( + input: number, + options?: QueryInt32SecondsOptions + ): Promise => { + return queryInt32Seconds(this._client, input, options); + }, + floatSeconds: ( + input: number, + options?: QueryFloatSecondsOptions + ): Promise => { + return queryFloatSeconds(this._client, input, options); + }, + int32SecondsArray: ( + input: number[], + options?: QueryInt32SecondsArrayOptions + ): Promise => { + return queryInt32SecondsArray(this._client, input, options); + }, + }; + property = { + default: ( + value: string, + options?: PropertyDefaultOptions + ): Promise => { + return propertyDefault(this._client, value, options); + }, + iso8601: ( + value: string, + options?: PropertyIso8601Options + ): Promise => { + return propertyIso8601(this._client, value, options); + }, + int32Seconds: ( + value: number, + options?: PropertyInt32SecondsOptions + ): Promise => { + return propertyInt32Seconds(this._client, value, options); + }, + floatSeconds: ( + value: number, + options?: PropertyFloatSecondsOptions + ): Promise => { + return propertyFloatSeconds(this._client, value, options); + }, + floatSecondsArray: ( + value: number[], + options?: PropertyFloatSecondsArrayOptions + ): Promise => { + return propertyFloatSecondsArray(this._client, value, options); + }, + }; + header = { + default: ( + duration: string, + options?: HeaderDefaultOptions + ): Promise => { + return headerDefault(this._client, duration, options); + }, + iso8601: ( + duration: string, + options?: HeaderIso8601Options + ): Promise => { + return headerIso8601(this._client, duration, options); + }, + iso8601Array: ( + duration: string[], + options?: HeaderIso8601ArrayOptions + ): Promise => { + return headerIso8601Array(this._client, duration, options); + }, + int32Seconds: ( + duration: number, + options?: HeaderInt32SecondsOptions + ): Promise => { + return headerInt32Seconds(this._client, duration, options); + }, + floatSeconds: ( + duration: number, + options?: HeaderFloatSecondsOptions + ): Promise => { + return headerFloatSeconds(this._client, duration, options); + }, + }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts new file mode 100644 index 0000000000..0016bd1b25 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/DurationContext.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { DurationContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface DurationClientOptions extends ClientOptions {} + +export { DurationContext } from "../rest/index.js"; + +/** Test for encode decorator on duration. */ +export function createDuration( + options: DurationClientOptions = {} +): DurationContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts new file mode 100644 index 0000000000..eb1de520e9 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/header.ts @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + buildCsvCollection, + DurationContext as Client, + HeaderDefault204Response, + HeaderFloatSeconds204Response, + HeaderInt32Seconds204Response, + HeaderIso8601204Response, + HeaderIso8601Array204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "../models/options.js"; + +export function _headerDefaultSend( + context: Client, + duration: string, + options: HeaderDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/default") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerDefaultDeserialize( + result: HeaderDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerDefault( + context: Client, + duration: string, + options: HeaderDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _headerDefaultSend(context, duration, options); + return _headerDefaultDeserialize(result); +} + +export function _headerIso8601Send( + context: Client, + duration: string, + options: HeaderIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/iso8601") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerIso8601Deserialize( + result: HeaderIso8601204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerIso8601( + context: Client, + duration: string, + options: HeaderIso8601Options = { requestOptions: {} } +): Promise { + const result = await _headerIso8601Send(context, duration, options); + return _headerIso8601Deserialize(result); +} + +export function _headerIso8601ArraySend( + context: Client, + duration: string[], + options: HeaderIso8601ArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/iso8601-array") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: buildCsvCollection(duration) }, + }); +} + +export async function _headerIso8601ArrayDeserialize( + result: HeaderIso8601Array204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerIso8601Array( + context: Client, + duration: string[], + options: HeaderIso8601ArrayOptions = { requestOptions: {} } +): Promise { + const result = await _headerIso8601ArraySend(context, duration, options); + return _headerIso8601ArrayDeserialize(result); +} + +export function _headerInt32SecondsSend( + context: Client, + duration: number, + options: HeaderInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/int32-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerInt32SecondsDeserialize( + result: HeaderInt32Seconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerInt32Seconds( + context: Client, + duration: number, + options: HeaderInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _headerInt32SecondsSend(context, duration, options); + return _headerInt32SecondsDeserialize(result); +} + +export function _headerFloatSecondsSend( + context: Client, + duration: number, + options: HeaderFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/header/float-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { duration: duration }, + }); +} + +export async function _headerFloatSecondsDeserialize( + result: HeaderFloatSeconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function headerFloatSeconds( + context: Client, + duration: number, + options: HeaderFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _headerFloatSecondsSend(context, duration, options); + return _headerFloatSecondsDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts new file mode 100644 index 0000000000..716eddc539 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/index.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createDuration, + DurationClientOptions, + DurationContext, +} from "./DurationContext.js"; +export { + headerDefault, + headerIso8601, + headerIso8601Array, + headerInt32Seconds, + headerFloatSeconds, +} from "./header.js"; +export { + propertyDefault, + propertyIso8601, + propertyInt32Seconds, + propertyFloatSeconds, + propertyFloatSecondsArray, +} from "./property.js"; +export { + queryDefault, + queryIso8601, + queryInt32Seconds, + queryFloatSeconds, + queryInt32SecondsArray, +} from "./query.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts new file mode 100644 index 0000000000..1f1f125607 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/property.ts @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "../models/models.js"; +import { + DurationContext as Client, + PropertyDefault200Response, + PropertyFloatSeconds200Response, + PropertyFloatSecondsArray200Response, + PropertyInt32Seconds200Response, + PropertyIso8601200Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, +} from "../models/options.js"; + +export function _propertyDefaultSend( + context: Client, + value: string, + options: PropertyDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/default") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyDefaultDeserialize( + result: PropertyDefault200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyDefault( + context: Client, + value: string, + options: PropertyDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _propertyDefaultSend(context, value, options); + return _propertyDefaultDeserialize(result); +} + +export function _propertyIso8601Send( + context: Client, + value: string, + options: PropertyIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/iso8601") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyIso8601Deserialize( + result: PropertyIso8601200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyIso8601( + context: Client, + value: string, + options: PropertyIso8601Options = { requestOptions: {} } +): Promise { + const result = await _propertyIso8601Send(context, value, options); + return _propertyIso8601Deserialize(result); +} + +export function _propertyInt32SecondsSend( + context: Client, + value: number, + options: PropertyInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/int32-seconds") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyInt32SecondsDeserialize( + result: PropertyInt32Seconds200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyInt32Seconds( + context: Client, + value: number, + options: PropertyInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _propertyInt32SecondsSend(context, value, options); + return _propertyInt32SecondsDeserialize(result); +} + +export function _propertyFloatSecondsSend( + context: Client, + value: number, + options: PropertyFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/float-seconds") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyFloatSecondsDeserialize( + result: PropertyFloatSeconds200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyFloatSeconds( + context: Client, + value: number, + options: PropertyFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _propertyFloatSecondsSend(context, value, options); + return _propertyFloatSecondsDeserialize(result); +} + +export function _propertyFloatSecondsArraySend( + context: Client, + value: number[], + options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/property/float-seconds-array") + .post({ + ...operationOptionsToRequestParameters(options), + body: { value: value }, + }); +} + +export async function _propertyFloatSecondsArrayDeserialize( + result: PropertyFloatSecondsArray200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: result.body["value"], + }; +} + +export async function propertyFloatSecondsArray( + context: Client, + value: number[], + options: PropertyFloatSecondsArrayOptions = { requestOptions: {} } +): Promise { + const result = await _propertyFloatSecondsArraySend(context, value, options); + return _propertyFloatSecondsArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts new file mode 100644 index 0000000000..9ba5615fbd --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/api/query.ts @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + DurationContext as Client, + QueryDefault204Response, + QueryFloatSeconds204Response, + QueryInt32Seconds204Response, + QueryInt32SecondsArray204Response, + QueryIso8601204Response, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, +} from "../models/options.js"; + +export function _queryDefaultSend( + context: Client, + input: string, + options: QueryDefaultOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/default") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryDefaultDeserialize( + result: QueryDefault204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryDefault( + context: Client, + input: string, + options: QueryDefaultOptions = { requestOptions: {} } +): Promise { + const result = await _queryDefaultSend(context, input, options); + return _queryDefaultDeserialize(result); +} + +export function _queryIso8601Send( + context: Client, + input: string, + options: QueryIso8601Options = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/iso8601") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryIso8601Deserialize( + result: QueryIso8601204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryIso8601( + context: Client, + input: string, + options: QueryIso8601Options = { requestOptions: {} } +): Promise { + const result = await _queryIso8601Send(context, input, options); + return _queryIso8601Deserialize(result); +} + +export function _queryInt32SecondsSend( + context: Client, + input: number, + options: QueryInt32SecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/int32-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryInt32SecondsDeserialize( + result: QueryInt32Seconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryInt32Seconds( + context: Client, + input: number, + options: QueryInt32SecondsOptions = { requestOptions: {} } +): Promise { + const result = await _queryInt32SecondsSend(context, input, options); + return _queryInt32SecondsDeserialize(result); +} + +export function _queryFloatSecondsSend( + context: Client, + input: number, + options: QueryFloatSecondsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/float-seconds") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryFloatSecondsDeserialize( + result: QueryFloatSeconds204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryFloatSeconds( + context: Client, + input: number, + options: QueryFloatSecondsOptions = { requestOptions: {} } +): Promise { + const result = await _queryFloatSecondsSend(context, input, options); + return _queryFloatSecondsDeserialize(result); +} + +export function _queryInt32SecondsArraySend( + context: Client, + input: number[], + options: QueryInt32SecondsArrayOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/encode/duration/query/int32-seconds-array") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { input: input }, + }); +} + +export async function _queryInt32SecondsArrayDeserialize( + result: QueryInt32SecondsArray204Response +): Promise { + if (result.status !== "204") { + throw result.body; + } + + return; +} + +export async function queryInt32SecondsArray( + context: Client, + input: number[], + options: QueryInt32SecondsArrayOptions = { requestOptions: {} } +): Promise { + const result = await _queryInt32SecondsArraySend(context, input, options); + return _queryInt32SecondsArrayDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts new file mode 100644 index 0000000000..58be9b1f92 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { DurationClient, DurationClientOptions } from "./DurationClient.js"; +export { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/logger.ts new file mode 100644 index 0000000000..aa142f6020 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/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("encode-duration"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts new file mode 100644 index 0000000000..f0b43ea881 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models.js"; +export { + QueryDefaultOptions, + QueryIso8601Options, + QueryInt32SecondsOptions, + QueryFloatSecondsOptions, + QueryInt32SecondsArrayOptions, + PropertyDefaultOptions, + PropertyIso8601Options, + PropertyInt32SecondsOptions, + PropertyFloatSecondsOptions, + PropertyFloatSecondsArrayOptions, + HeaderDefaultOptions, + HeaderIso8601Options, + HeaderIso8601ArrayOptions, + HeaderInt32SecondsOptions, + HeaderFloatSecondsOptions, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts new file mode 100644 index 0000000000..476962243e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationProperty { + value: string; +} + +export interface ISO8601DurationProperty { + value: string; +} + +export interface Int32SecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationArrayProperty { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts new file mode 100644 index 0000000000..5dff518131 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/models/options.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface QueryDefaultOptions extends OperationOptions {} + +export interface QueryIso8601Options extends OperationOptions {} + +export interface QueryInt32SecondsOptions extends OperationOptions {} + +export interface QueryFloatSecondsOptions extends OperationOptions {} + +export interface QueryInt32SecondsArrayOptions extends OperationOptions {} + +export interface PropertyDefaultOptions extends OperationOptions {} + +export interface PropertyIso8601Options extends OperationOptions {} + +export interface PropertyInt32SecondsOptions extends OperationOptions {} + +export interface PropertyFloatSecondsOptions extends OperationOptions {} + +export interface PropertyFloatSecondsArrayOptions extends OperationOptions {} + +export interface HeaderDefaultOptions extends OperationOptions {} + +export interface HeaderIso8601Options extends OperationOptions {} + +export interface HeaderIso8601ArrayOptions extends OperationOptions {} + +export interface HeaderInt32SecondsOptions extends OperationOptions {} + +export interface HeaderFloatSecondsOptions extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..c75cf2c79f --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/clientDefinitions.ts @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + QueryDefaultParameters, + QueryIso8601Parameters, + QueryInt32SecondsParameters, + QueryFloatSecondsParameters, + QueryInt32SecondsArrayParameters, + PropertyDefaultParameters, + PropertyIso8601Parameters, + PropertyInt32SecondsParameters, + PropertyFloatSecondsParameters, + PropertyFloatSecondsArrayParameters, + HeaderDefaultParameters, + HeaderIso8601Parameters, + HeaderIso8601ArrayParameters, + HeaderInt32SecondsParameters, + HeaderFloatSecondsParameters, +} from "./parameters.js"; +import { + QueryDefault204Response, + QueryIso8601204Response, + QueryInt32Seconds204Response, + QueryFloatSeconds204Response, + QueryInt32SecondsArray204Response, + PropertyDefault200Response, + PropertyIso8601200Response, + PropertyInt32Seconds200Response, + PropertyFloatSeconds200Response, + PropertyFloatSecondsArray200Response, + HeaderDefault204Response, + HeaderIso8601204Response, + HeaderIso8601Array204Response, + HeaderInt32Seconds204Response, + HeaderFloatSeconds204Response, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface QueryDefault { + get( + options: QueryDefaultParameters + ): StreamableMethod; +} + +export interface QueryIso8601 { + get( + options: QueryIso8601Parameters + ): StreamableMethod; +} + +export interface QueryInt32Seconds { + get( + options: QueryInt32SecondsParameters + ): StreamableMethod; +} + +export interface QueryFloatSeconds { + get( + options: QueryFloatSecondsParameters + ): StreamableMethod; +} + +export interface QueryInt32SecondsArray { + get( + options: QueryInt32SecondsArrayParameters + ): StreamableMethod; +} + +export interface PropertyDefault { + post( + options: PropertyDefaultParameters + ): StreamableMethod; +} + +export interface PropertyIso8601 { + post( + options: PropertyIso8601Parameters + ): StreamableMethod; +} + +export interface PropertyInt32Seconds { + post( + options: PropertyInt32SecondsParameters + ): StreamableMethod; +} + +export interface PropertyFloatSeconds { + post( + options: PropertyFloatSecondsParameters + ): StreamableMethod; +} + +export interface PropertyFloatSecondsArray { + post( + options: PropertyFloatSecondsArrayParameters + ): StreamableMethod; +} + +export interface HeaderDefault { + get( + options: HeaderDefaultParameters + ): StreamableMethod; +} + +export interface HeaderIso8601 { + get( + options: HeaderIso8601Parameters + ): StreamableMethod; +} + +export interface HeaderIso8601Array { + get( + options: HeaderIso8601ArrayParameters + ): StreamableMethod; +} + +export interface HeaderInt32Seconds { + get( + options: HeaderInt32SecondsParameters + ): StreamableMethod; +} + +export interface HeaderFloatSeconds { + get( + options: HeaderFloatSecondsParameters + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/encode/duration/query/default' has methods for the following verbs: get */ + (path: "/encode/duration/query/default"): QueryDefault; + /** Resource for '/encode/duration/query/iso8601' has methods for the following verbs: get */ + (path: "/encode/duration/query/iso8601"): QueryIso8601; + /** Resource for '/encode/duration/query/int32-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/query/int32-seconds"): QueryInt32Seconds; + /** Resource for '/encode/duration/query/float-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/query/float-seconds"): QueryFloatSeconds; + /** Resource for '/encode/duration/query/int32-seconds-array' has methods for the following verbs: get */ + (path: "/encode/duration/query/int32-seconds-array"): QueryInt32SecondsArray; + /** Resource for '/encode/duration/property/default' has methods for the following verbs: post */ + (path: "/encode/duration/property/default"): PropertyDefault; + /** Resource for '/encode/duration/property/iso8601' has methods for the following verbs: post */ + (path: "/encode/duration/property/iso8601"): PropertyIso8601; + /** Resource for '/encode/duration/property/int32-seconds' has methods for the following verbs: post */ + (path: "/encode/duration/property/int32-seconds"): PropertyInt32Seconds; + /** Resource for '/encode/duration/property/float-seconds' has methods for the following verbs: post */ + (path: "/encode/duration/property/float-seconds"): PropertyFloatSeconds; + /** Resource for '/encode/duration/property/float-seconds-array' has methods for the following verbs: post */ + ( + path: "/encode/duration/property/float-seconds-array" + ): PropertyFloatSecondsArray; + /** Resource for '/encode/duration/header/default' has methods for the following verbs: get */ + (path: "/encode/duration/header/default"): HeaderDefault; + /** Resource for '/encode/duration/header/iso8601' has methods for the following verbs: get */ + (path: "/encode/duration/header/iso8601"): HeaderIso8601; + /** Resource for '/encode/duration/header/iso8601-array' has methods for the following verbs: get */ + (path: "/encode/duration/header/iso8601-array"): HeaderIso8601Array; + /** Resource for '/encode/duration/header/int32-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/header/int32-seconds"): HeaderInt32Seconds; + /** Resource for '/encode/duration/header/float-seconds' has methods for the following verbs: get */ + (path: "/encode/duration/header/float-seconds"): HeaderFloatSeconds; +} + +export type DurationContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.ts new file mode 100644 index 0000000000..d10bbfbf29 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/durationClient.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 { DurationContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `DurationContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): DurationContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-encode-duration-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 DurationContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts new file mode 100644 index 0000000000..2b00de3f97 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import DurationClient from "./durationClient.js"; + +export * from "./durationClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./models.js"; +export * from "./outputModels.js"; +export * from "./serializeHelper.js"; + +export default DurationClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts new file mode 100644 index 0000000000..476962243e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/models.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationProperty { + value: string; +} + +export interface ISO8601DurationProperty { + value: string; +} + +export interface Int32SecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationProperty { + value: number; +} + +export interface FloatSecondsDurationArrayProperty { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts new file mode 100644 index 0000000000..a31b5b57db --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/outputModels.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface DefaultDurationPropertyOutput { + value: string; +} + +export interface ISO8601DurationPropertyOutput { + value: string; +} + +export interface Int32SecondsDurationPropertyOutput { + value: number; +} + +export interface FloatSecondsDurationPropertyOutput { + value: number; +} + +export interface FloatSecondsDurationArrayPropertyOutput { + value: number[]; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts new file mode 100644 index 0000000000..15fe2c7595 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/parameters.ts @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + DefaultDurationProperty, + ISO8601DurationProperty, + Int32SecondsDurationProperty, + FloatSecondsDurationProperty, + FloatSecondsDurationArrayProperty, +} from "./models.js"; + +export interface QueryDefaultQueryParamProperties { + input: string; +} + +export interface QueryDefaultQueryParam { + queryParameters: QueryDefaultQueryParamProperties; +} + +export type QueryDefaultParameters = QueryDefaultQueryParam & RequestParameters; + +export interface QueryIso8601QueryParamProperties { + input: string; +} + +export interface QueryIso8601QueryParam { + queryParameters: QueryIso8601QueryParamProperties; +} + +export type QueryIso8601Parameters = QueryIso8601QueryParam & RequestParameters; + +export interface QueryInt32SecondsQueryParamProperties { + input: number; +} + +export interface QueryInt32SecondsQueryParam { + queryParameters: QueryInt32SecondsQueryParamProperties; +} + +export type QueryInt32SecondsParameters = QueryInt32SecondsQueryParam & + RequestParameters; + +export interface QueryFloatSecondsQueryParamProperties { + input: number; +} + +export interface QueryFloatSecondsQueryParam { + queryParameters: QueryFloatSecondsQueryParamProperties; +} + +export type QueryFloatSecondsParameters = QueryFloatSecondsQueryParam & + RequestParameters; + +export interface QueryInt32SecondsArrayQueryParamProperties { + input: number[]; +} + +export interface QueryInt32SecondsArrayQueryParam { + queryParameters: QueryInt32SecondsArrayQueryParamProperties; +} + +export type QueryInt32SecondsArrayParameters = + QueryInt32SecondsArrayQueryParam & RequestParameters; + +export interface PropertyDefaultBodyParam { + body: DefaultDurationProperty; +} + +export type PropertyDefaultParameters = PropertyDefaultBodyParam & + RequestParameters; + +export interface PropertyIso8601BodyParam { + body: ISO8601DurationProperty; +} + +export type PropertyIso8601Parameters = PropertyIso8601BodyParam & + RequestParameters; + +export interface PropertyInt32SecondsBodyParam { + body: Int32SecondsDurationProperty; +} + +export type PropertyInt32SecondsParameters = PropertyInt32SecondsBodyParam & + RequestParameters; + +export interface PropertyFloatSecondsBodyParam { + body: FloatSecondsDurationProperty; +} + +export type PropertyFloatSecondsParameters = PropertyFloatSecondsBodyParam & + RequestParameters; + +export interface PropertyFloatSecondsArrayBodyParam { + body: FloatSecondsDurationArrayProperty; +} + +export type PropertyFloatSecondsArrayParameters = + PropertyFloatSecondsArrayBodyParam & RequestParameters; + +export interface HeaderDefaultHeaders { + duration: string; +} + +export interface HeaderDefaultHeaderParam { + headers: RawHttpHeadersInput & HeaderDefaultHeaders; +} + +export type HeaderDefaultParameters = HeaderDefaultHeaderParam & + RequestParameters; + +export interface HeaderIso8601Headers { + duration: string; +} + +export interface HeaderIso8601HeaderParam { + headers: RawHttpHeadersInput & HeaderIso8601Headers; +} + +export type HeaderIso8601Parameters = HeaderIso8601HeaderParam & + RequestParameters; + +export interface HeaderIso8601ArrayHeaders { + /** This parameter needs to be formatted as csv collection, we provide buildCsvCollection from serializeHelper.ts to help */ + duration: string; +} + +export interface HeaderIso8601ArrayHeaderParam { + headers: RawHttpHeadersInput & HeaderIso8601ArrayHeaders; +} + +export type HeaderIso8601ArrayParameters = HeaderIso8601ArrayHeaderParam & + RequestParameters; + +export interface HeaderInt32SecondsHeaders { + duration: number; +} + +export interface HeaderInt32SecondsHeaderParam { + headers: RawHttpHeadersInput & HeaderInt32SecondsHeaders; +} + +export type HeaderInt32SecondsParameters = HeaderInt32SecondsHeaderParam & + RequestParameters; + +export interface HeaderFloatSecondsHeaders { + duration: number; +} + +export interface HeaderFloatSecondsHeaderParam { + headers: RawHttpHeadersInput & HeaderFloatSecondsHeaders; +} + +export type HeaderFloatSecondsParameters = HeaderFloatSecondsHeaderParam & + RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts new file mode 100644 index 0000000000..bcddc3be93 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/responses.ts @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + DefaultDurationPropertyOutput, + ISO8601DurationPropertyOutput, + Int32SecondsDurationPropertyOutput, + FloatSecondsDurationPropertyOutput, + FloatSecondsDurationArrayPropertyOutput, +} from "./outputModels.js"; + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryIso8601204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryInt32Seconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryFloatSeconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface QueryInt32SecondsArray204Response extends HttpResponse { + status: "204"; +} + +/** The request has succeeded. */ +export interface PropertyDefault200Response extends HttpResponse { + status: "200"; + body: DefaultDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyIso8601200Response extends HttpResponse { + status: "200"; + body: ISO8601DurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyInt32Seconds200Response extends HttpResponse { + status: "200"; + body: Int32SecondsDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyFloatSeconds200Response extends HttpResponse { + status: "200"; + body: FloatSecondsDurationPropertyOutput; +} + +/** The request has succeeded. */ +export interface PropertyFloatSecondsArray200Response extends HttpResponse { + status: "200"; + body: FloatSecondsDurationArrayPropertyOutput; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderDefault204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderIso8601204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderIso8601Array204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderInt32Seconds204Response extends HttpResponse { + status: "204"; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface HeaderFloatSeconds204Response extends HttpResponse { + status: "204"; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts new file mode 100644 index 0000000000..aeb95223cc --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/rest/serializeHelper.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function buildCsvCollection(items: string[] | number[]) { + return items.join(","); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/tspconfig.yaml new file mode 100644 index 0000000000..36b5a41544 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/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 + enableOperationGroup: true + isModularLibrary: true + packageDetails: + name: "@msinternal/encode-duration" diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index 87fd90aa1d..da395db889 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -1,5 +1,5 @@ import { assert } from "chai"; -import { emitModularModelsFromTypeSpec } from "../util/emitUtil.js"; +import { emitModularModelsFromTypeSpec, emitModularOperationsFromTypeSpec } from "../util/emitUtil.js"; import { assertEqualContent } from "../util/testUtil.js"; describe("modular model type", () => { @@ -13,6 +13,760 @@ describe("modular model type", () => { }); }); +describe("modular encode test for property type datetime", () => { + it("should handle property type plainDate, plainTime, utcDateTime, offsetDatetime with default encoding", async () => { + const tspContent = ` + model Foo { + prop1: plainDate; + prop2: plainTime; + prop3: utcDateTime; + prop4: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + prop3: Date; + prop4: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + prop3: Date, + prop4: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toDateString(), + prop2: prop2.toTimeString(), + prop3: prop3.toISOString(), + prop4: prop4.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + prop3: new Date(result.body["prop3"]), + prop4: new Date(result.body["prop4"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + prop3: Date, + prop4: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, prop3, prop4, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle header parameter type utcDateTime with default encoding", async () => { + const tspContent = ` + op read(@header prop: utcDateTime): OkResponse; + ` + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + prop: prop.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return; + } + + export async function read( + context: Client, + prop: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type utcDateTime, offsetDateTime with rfc3339 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.rfc3339) + prop1: utcDateTime; + @encode(DateTimeKnownEncoding.rfc3339) + prop2: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toISOString(), + prop2: prop2.toISOString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type utcDateTime, offsetDateTime with rfc7231 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.rfc7231) + prop1: utcDateTime; + @encode(DateTimeKnownEncoding.rfc7231) + prop2: offsetDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + prop2: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.toUTCString(), + prop2: prop2.toUTCString(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + prop2: new Date(result.body["prop2"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + prop2: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type utcDateTime with unixTimestamp encoding", async () => { + const tspContent = ` + model Foo { + @encode(DateTimeKnownEncoding.unixTimestamp, int64) + prop1: utcDateTime; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Date; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: Date, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1.getTime(), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: new Date(result.body["prop1"]), + }; + } + + export async function read( + context: Client, + prop1: Date, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); +}); + +describe("modular encode test for property type duration", () => { + it("should handle property type duration with default encoding", async () => { + const tspContent = ` + model Foo { + prop1: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: string; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type duration with ISO8601 encoding", async () => { + const tspContent = ` + model Foo { + @encode(DurationKnownEncoding.ISO8601) + prop1: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: string; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: string, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type duration with seconds encoding", async () => { + const tspContent = ` + model Foo { + @encode(DurationKnownEncoding.seconds, float32) + prop1: duration; + @encode(DurationKnownEncoding.seconds, int64) + prop2: duration; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: number; + prop2: number; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + + export function _readSend( + context: Client, + prop1: number, + prop2: number, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: prop1, + prop2: prop2, + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: result.body["prop1"], + prop2: result.body["prop2"], + }; + } + + export async function read( + context: Client, + prop1: number, + prop2: number, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, prop2, options); + return _readDeserialize(result); + }`, + true + ); + }); +}); + +describe("modular encode test for property type bytes", () => { + it("should handle property type bytes with default encoding", async () => { + const tspContent = ` + model Foo { + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type bytes with base64 encoding", async () => { + const tspContent = ` + model Foo { + @encode(BytesKnownEncoding.base64) + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); + + it("should handle property type bytes with base64url encoding", async () => { + const tspContent = ` + model Foo { + @encode(BytesKnownEncoding.base64url) + prop1: bytes; + } + op read(@body body: Foo): { @body body: Foo }; + ` + const modelFile = await emitModularModelsFromTypeSpec(tspContent); + assert.ok(modelFile); + assertEqualContent( + modelFile?.getFullText()!, + ` + export interface Foo { + prop1: Uint8Array; + }` + ); + const operationFiles = await emitModularOperationsFromTypeSpec(tspContent); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + assertEqualContent( + operationFiles?.[0]?.getFullText()!,` + import { TestingContext as Client } from "../rest/index.js"; + import { + StreamableMethod, + operationOptionsToRequestParameters, + } from "@azure-rest/core-client"; + import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; + + export function _readSend( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): StreamableMethod { + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + body: { + prop1: uint8ArrayToString(prop1, "base64url"), + }, + }); + } + + export async function _readDeserialize(result: Read200Response): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + prop1: + typeof result.body["prop1"] === "string" + ? stringToUint8Array(result.body["prop1"], "base64url") + : result.body["prop1"], + }; + } + + export async function read( + context: Client, + prop1: Uint8Array, + options: ReadOptions = { requestOptions: {} } + ): Promise { + const result = await _readSend(context, prop1, options); + return _readDeserialize(result); + }`, + true + ); + }); +}); + describe("inheritance & polymorphism", () => { it("should handle inheritance model", async () => { const modelFile = await emitModularModelsFromTypeSpec(` diff --git a/packages/typespec-ts/test/util/emitUtil.ts b/packages/typespec-ts/test/util/emitUtil.ts index 76d833d1d7..432ceede3e 100644 --- a/packages/typespec-ts/test/util/emitUtil.ts +++ b/packages/typespec-ts/test/util/emitUtil.ts @@ -25,6 +25,7 @@ import { expectDiagnosticEmpty } from "@typespec/compiler/testing"; import { transformHelperFunctionDetails } from "../../src/transform/transformHelperFunctionDetails.js"; import { emitCodeModel } from "../../src/modular/buildCodeModel.js"; import { buildModels } from "../../src/modular/emitModels.js"; +import { buildOperationFiles } from "../../src/modular/buildOperations.js"; import { Project } from "ts-morph"; export async function emitPageHelperFromTypeSpec( @@ -246,3 +247,39 @@ export async function emitModularModelsFromTypeSpec(tspContent: string) { expectDiagnosticEmpty(dpgContext.program.diagnostics); return undefined; } + +export async function emitModularOperationsFromTypeSpec(tspContent: string) { + const context = await rlcEmitterFor(tspContent); + const dpgContext = createDpgContextTestHelper(context.program); + const serviceNameToRlcModelsMap: Map = new Map< + string, + RLCModel + >(); + const project = new Project(); + const clients = getRLCClients(dpgContext); + if (clients && clients[0]) { + dpgContext.rlcOptions!.isModularLibrary = true; + const rlcModels = await transformRLCModel(clients[0], dpgContext); + serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); + const modularCodeModel = emitCodeModel( + dpgContext, + serviceNameToRlcModelsMap, + "", + project, + { + casing: "camel" + } + ); + if ( + modularCodeModel && + modularCodeModel.clients && + modularCodeModel.clients.length > 0 && + modularCodeModel.clients[0] + ) { + return buildOperationFiles(dpgContext, modularCodeModel, modularCodeModel.clients[0], false); + } + } + expectDiagnosticEmpty(dpgContext.program.diagnostics); + return undefined; + +} \ No newline at end of file diff --git a/packages/typespec-ts/test/util/testUtil.ts b/packages/typespec-ts/test/util/testUtil.ts index a5d4bc12f9..0a060d59a3 100644 --- a/packages/typespec-ts/test/util/testUtil.ts +++ b/packages/typespec-ts/test/util/testUtil.ts @@ -71,7 +71,12 @@ export function createDpgContextTestHelper(program: Program): SdkContext { const defaultOptions = { generateProtocolMethods: true, generateConvenienceMethods: true, - emitters: [] + emitters: [ + { + main: "@azure-tools/typespec-ts", + metadata: { name: "@azure-tools/typespec-ts" } + } + ] }; const resolvedOptions = { ...defaultOptions }; program.emitters = resolvedOptions.emitters as any; @@ -84,9 +89,19 @@ export function createDpgContextTestHelper(program: Program): SdkContext { } as SdkContext; } -export function assertEqualContent(actual: string, expected: string) { +export function assertEqualContent( + actual: string, + expected: string, + ignoreWeirdLine: boolean = false +) { assert.strictEqual( - format(actual, prettierTypeScriptOptions), - format(expected, prettierTypeScriptOptions) + format( + ignoreWeirdLine ? actual.replace(/\n/g, "") : actual, + prettierTypeScriptOptions + ), + format( + ignoreWeirdLine ? expected.replace(/\n/g, "") : expected, + prettierTypeScriptOptions + ) ); }