diff --git a/.gitignore b/.gitignore index 99a6f8f..e6a8533 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/__tests__ /models /models/errors /types diff --git a/.npmignore b/.npmignore index 3ef05d1..06cd8ab 100644 --- a/.npmignore +++ b/.npmignore @@ -7,3 +7,4 @@ /cjs /.tshy /.tshy-* +/__tests__ diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index bd57271..46a4b25 100644 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -3,10 +3,10 @@ id: ede0e8e6-5a63-4cc3-bd29-551cf1036a60 management: docChecksum: 7c524b4be7afdadc4b2f448072865ac4 docVersion: 1.0.0 - speakeasyVersion: 1.378.0 - generationVersion: 2.404.3 - releaseVersion: 0.0.3 - configChecksum: 5750dbc3b9d5c61d1e57227fd04a92c3 + speakeasyVersion: 1.413.0 + generationVersion: 2.436.3 + releaseVersion: 0.1.0 + configChecksum: 47c6d1652615889a4433876e11abcf6b repoURL: https://github.com/ryan-timothy-albert/simple-ts-sdk.git installationURL: https://github.com/ryan-timothy-albert/simple-ts-sdk published: true @@ -14,9 +14,10 @@ features: typescript: additionalDependencies: 0.1.0 constsAndDefaults: 0.1.11 - core: 3.14.1 + core: 3.18.2 defaultEnabledRetries: 0.1.0 devContainers: 2.90.0 + enumUnions: 0.1.0 envVarSecurityUsage: 0.1.1 globalSecurity: 2.82.11 globalSecurityCallbacks: 0.1.0 @@ -25,41 +26,78 @@ features: responseFormat: 0.2.3 retries: 2.83.0 sdkHooks: 0.1.0 + uploadStreams: 0.1.0 generatedFiles: - - src/funcs/petUpdatePet.ts + - .devcontainer/README.md + - .devcontainer/devcontainer.json + - .devcontainer/setup.sh + - .eslintrc.cjs + - .gitattributes + - .npmignore + - CONTRIBUTING.md + - FUNCTIONS.md + - RUNTIMES.md + - USAGE.md + - docs/lib/utils/retryconfig.md + - docs/models/components/apiresponse.md + - docs/models/components/category.md + - docs/models/components/order.md + - docs/models/components/orderstatus.md + - docs/models/components/pet.md + - docs/models/components/security.md + - docs/models/components/status.md + - docs/models/components/tag.md + - docs/models/components/user.md + - docs/models/errors/apierrorinvalidinput.md + - docs/models/errors/apierrornotfound.md + - docs/models/errors/apierrorunauthorized.md + - docs/models/operations/deleteorderrequest.md + - docs/models/operations/deletepetrequest.md + - docs/models/operations/deleteuserrequest.md + - docs/models/operations/findpetsbystatusrequest.md + - docs/models/operations/findpetsbytagsrequest.md + - docs/models/operations/getorderbyidrequest.md + - docs/models/operations/getpetbyidrequest.md + - docs/models/operations/getuserbynamerequest.md + - docs/models/operations/loginuserrequest.md + - docs/models/operations/loginuserresponse.md + - docs/models/operations/status.md + - docs/models/operations/updateuserrequest.md + - docs/models/operations/uploadfilerequest.md + - docs/sdks/pet/README.md + - docs/sdks/petstore/README.md + - docs/sdks/store/README.md + - docs/sdks/user/README.md + - jsr.json + - package.json + - src/core.ts - src/funcs/petAddPet.ts + - src/funcs/petDeletePet.ts - src/funcs/petFindPetsByStatus.ts - src/funcs/petFindPetsByTags.ts - src/funcs/petGetPetById.ts - - src/funcs/petDeletePet.ts + - src/funcs/petUpdatePet.ts - src/funcs/petUploadFile.ts + - src/funcs/storeDeleteOrder.ts - src/funcs/storeGetInventory.ts - - src/funcs/storePlaceOrder.ts - src/funcs/storeGetOrderById.ts - - src/funcs/storeDeleteOrder.ts + - src/funcs/storePlaceOrder.ts - src/funcs/userCreateUser.ts - src/funcs/userCreateUsersWithListInput.ts + - src/funcs/userDeleteUser.ts + - src/funcs/userGetUserByName.ts - src/funcs/userLoginUser.ts - src/funcs/userLogoutUser.ts - - src/funcs/userGetUserByName.ts - src/funcs/userUpdateUser.ts - - src/funcs/userDeleteUser.ts - - src/sdk/pet.ts - - src/sdk/store.ts - - src/sdk/user.ts - - src/sdk/sdk.ts - - .eslintrc.cjs - - .npmignore - - FUNCTIONS.md - - RUNTIMES.md - - jsr.json - - package.json - - src/core.ts + - src/hooks/hooks.ts + - src/hooks/index.ts + - src/hooks/types.ts - src/index.ts - src/lib/base64.ts - src/lib/config.ts - src/lib/dlv.ts - src/lib/encodings.ts + - src/lib/files.ts - src/lib/http.ts - src/lib/is-plain-object.ts - src/lib/logger.ts @@ -70,10 +108,38 @@ generatedFiles: - src/lib/sdks.ts - src/lib/security.ts - src/lib/url.ts - - src/sdk/index.ts + - src/models/components/apiresponse.ts + - src/models/components/category.ts + - src/models/components/index.ts + - src/models/components/order.ts + - src/models/components/pet.ts + - src/models/components/security.ts + - src/models/components/tag.ts + - src/models/components/user.ts + - src/models/errors/apierrorinvalidinput.ts + - src/models/errors/apierrornotfound.ts + - src/models/errors/apierrorunauthorized.ts - src/models/errors/httpclienterrors.ts + - src/models/errors/index.ts - src/models/errors/sdkerror.ts - src/models/errors/sdkvalidationerror.ts + - src/models/operations/deleteorder.ts + - src/models/operations/deletepet.ts + - src/models/operations/deleteuser.ts + - src/models/operations/findpetsbystatus.ts + - src/models/operations/findpetsbytags.ts + - src/models/operations/getorderbyid.ts + - src/models/operations/getpetbyid.ts + - src/models/operations/getuserbyname.ts + - src/models/operations/index.ts + - src/models/operations/loginuser.ts + - src/models/operations/updateuser.ts + - src/models/operations/uploadfile.ts + - src/sdk/index.ts + - src/sdk/pet.ts + - src/sdk/sdk.ts + - src/sdk/store.ts + - src/sdk/user.ts - src/types/blobs.ts - src/types/constdatetime.ts - src/types/enums.ts @@ -81,67 +147,192 @@ generatedFiles: - src/types/index.ts - src/types/operations.ts - src/types/rfcdate.ts + - src/types/streams.ts - tsconfig.json - - src/models/components/pet.ts - - src/models/components/tag.ts - - src/models/components/category.ts - - src/models/components/apiresponse.ts - - src/models/components/order.ts - - src/models/components/user.ts - - src/models/components/security.ts - - src/models/errors/apierrorinvalidinput.ts - - src/models/errors/apierrorunauthorized.ts - - src/models/errors/apierrornotfound.ts - - src/models/operations/findpetsbystatus.ts - - src/models/operations/findpetsbytags.ts - - src/models/operations/getpetbyid.ts - - src/models/operations/deletepet.ts - - src/models/operations/uploadfile.ts - - src/models/operations/getorderbyid.ts - - src/models/operations/deleteorder.ts - - src/models/operations/loginuser.ts - - src/models/operations/getuserbyname.ts - - src/models/operations/updateuser.ts - - src/models/operations/deleteuser.ts - - src/models/errors/index.ts - - src/models/components/index.ts - - src/models/operations/index.ts - - docs/models/components/status.md - - docs/models/components/pet.md - - docs/models/components/tag.md - - docs/models/components/category.md - - docs/models/components/apiresponse.md - - docs/models/components/orderstatus.md - - docs/models/components/order.md - - docs/models/components/user.md - - docs/models/components/security.md - - docs/models/errors/apierrorinvalidinput.md - - docs/models/errors/apierrorunauthorized.md - - docs/models/errors/apierrornotfound.md - - docs/models/operations/status.md - - docs/models/operations/findpetsbystatusrequest.md - - docs/models/operations/findpetsbytagsrequest.md - - docs/models/operations/getpetbyidrequest.md - - docs/models/operations/deletepetrequest.md - - docs/models/operations/uploadfilerequest.md - - docs/models/operations/getorderbyidrequest.md - - docs/models/operations/deleteorderrequest.md - - docs/models/operations/loginuserrequest.md - - docs/models/operations/loginuserresponse.md - - docs/models/operations/getuserbynamerequest.md - - docs/models/operations/updateuserrequest.md - - docs/models/operations/deleteuserrequest.md - - docs/sdks/petstore/README.md - - docs/lib/utils/retryconfig.md - - docs/sdks/pet/README.md - - docs/sdks/store/README.md - - docs/sdks/user/README.md - - USAGE.md - - .gitattributes - - .devcontainer/README.md - - .devcontainer/devcontainer.json - - .devcontainer/setup.sh - - src/hooks/hooks.ts - - src/hooks/types.ts - - src/hooks/index.ts - - CONTRIBUTING.md +examples: + updatePet: + speakeasy-default-update-pet: + requestBody: + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": ["", ""]} + responses: + "200": + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": [""]} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + addPet: + speakeasy-default-add-pet: + requestBody: + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": [""]} + responses: + "200": + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": [""]} + findPetsByStatus: + speakeasy-default-find-pets-by-status: + responses: + "200": + application/json: [{"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": []}, {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": [""]}, {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": []}] + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + findPetsByTags: + speakeasy-default-find-pets-by-tags: + responses: + "200": + application/json: [{"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": ["", "", ""]}] + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + getPetById: + speakeasy-default-get-pet-by-id: + parameters: + path: + petId: 504151 + responses: + "200": + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": []} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + deletePet: + speakeasy-default-delete-pet: + parameters: + path: + petId: 441876 + header: {} + responses: + "200": + application/json: {"id": 10, "name": "doggie", "category": {"id": 1, "name": "Dogs"}, "photoUrls": [""]} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + uploadFile: + speakeasy-default-upload-file: + parameters: + path: + petId: 565380 + query: {} + getInventory: + speakeasy-default-get-inventory: + responses: + "200": + application/json: {"key": 373538} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + placeOrder: + speakeasy-default-place-order: + requestBody: + application/json: {"id": 10, "petId": 198772, "quantity": 7, "status": "approved"} + responses: + "200": + application/json: {"id": 10, "petId": 198772, "quantity": 7, "status": "approved"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + getOrderById: + speakeasy-default-get-order-by-id: + parameters: + path: + orderId: 614993 + responses: + "200": + application/json: {"id": 10, "petId": 198772, "quantity": 7, "status": "approved"} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + deleteOrder: + speakeasy-default-delete-order: + parameters: + path: + orderId: 127902 + responses: + "200": + application/json: {"id": 10, "petId": 198772, "quantity": 7, "status": "approved"} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + createUser: + speakeasy-default-create-user: + requestBody: + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + responses: + "200": + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + createUsersWithListInput: + speakeasy-default-create-users-with-list-input: + requestBody: + application/json: [] + responses: + "200": + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + loginUser: + speakeasy-default-login-user: + responses: + "200": + application/json: "" + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + logoutUser: {} + getUserByName: + speakeasy-default-get-user-by-name: + parameters: + path: + username: "Zachery_Lubowitz15" + responses: + "200": + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} + updateUser: + speakeasy-default-update-user: + parameters: + path: + username: "Dandre_Hand41" + requestBody: + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + deleteUser: + speakeasy-default-delete-user: + parameters: + path: + username: "Demetris_Schmitt" + responses: + "200": + application/json: {"id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "john@email.com", "password": "12345", "phone": "12345", "userStatus": 1} + "400": + application/json: {"status": 400, "error": "Bad request"} + "401": + application/json: {"status": 401, "error": "Unauthorized"} + "404": + application/json: {"status": 404, "error": "Not Found", "code": "object_not_found"} diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml index 278b7d1..715480a 100644 --- a/.speakeasy/gen.yaml +++ b/.speakeasy/gen.yaml @@ -15,7 +15,7 @@ generation: auth: oAuth2ClientCredentialsEnabled: true typescript: - version: 0.0.3 + version: 0.1.0 additionalDependencies: dependencies: {} devDependencies: {} @@ -25,6 +25,7 @@ typescript: clientServerStatusCodesAsErrors: true enumFormat: union flattenGlobalSecurity: true + flatteningOrder: body-first imports: option: openapi paths: diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock index df1eb70..7025148 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -1,8 +1,8 @@ -speakeasyVersion: 1.378.0 +speakeasyVersion: 1.413.0 sources: petstore-oas: sourceNamespace: petstore-oas - sourceRevisionDigest: sha256:41b6cd70c803b5bc5ae7a224b761e6e1b7d8b6658446ec21859f86651d65413c + sourceRevisionDigest: sha256:ba44db0463d91312cf3dba36076ce3fca306f84f8b0f07c96eabd2ed048bd136 sourceBlobDigest: sha256:849ab95113a7a54b7944402c86e88af54754f8ef15f449005e30ca17bac3f5a0 tags: - latest @@ -11,9 +11,8 @@ targets: petstore: source: petstore-oas sourceNamespace: petstore-oas - sourceRevisionDigest: sha256:41b6cd70c803b5bc5ae7a224b761e6e1b7d8b6658446ec21859f86651d65413c + sourceRevisionDigest: sha256:ba44db0463d91312cf3dba36076ce3fca306f84f8b0f07c96eabd2ed048bd136 sourceBlobDigest: sha256:849ab95113a7a54b7944402c86e88af54754f8ef15f449005e30ca17bac3f5a0 - outLocation: /github/workspace/repo workflow: workflowVersion: 1.0.0 speakeasyVersion: latest diff --git a/FUNCTIONS.md b/FUNCTIONS.md index 1c17f4e..5a5e8bc 100644 --- a/FUNCTIONS.md +++ b/FUNCTIONS.md @@ -39,6 +39,7 @@ async function run() { }, photoUrls: [ "", + "", ], }); @@ -62,7 +63,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); diff --git a/README.md b/README.md index a5cb0e9..b9f40c7 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,41 @@ It has been generated successfully based on your OpenAPI spec. However, it is no - [ ] 🎁 Publish your SDK to package managers by [configuring automatic publishing](https://www.speakeasy.com/docs/advanced-setup/publish-sdks) - [ ] ✨ When ready to productionize, delete this section from the README + +## Summary + +Petstore - OpenAPI 3.1: This is a sample Pet Store Server based on the OpenAPI 3.1 specification. + +Some useful links: +- [OpenAPI Reference](https://www.speakeasyapi.dev/openapi) +- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + +For more information about the API: [Find out more about Swagger](http://swagger.io) + + + +## Table of Contents + +* [SDK Installation](#sdk-installation) +* [Requirements](#requirements) +* [SDK Example Usage](#sdk-example-usage) +* [Available Resources and Operations](#available-resources-and-operations) +* [Standalone functions](#standalone-functions) +* [File uploads](#file-uploads) +* [Retries](#retries) +* [Error Handling](#error-handling) +* [Server Selection](#server-selection) +* [Custom HTTP Client](#custom-http-client) +* [Authentication](#authentication) +* [Debugging](#debugging) + + ## SDK Installation +The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers. + ### NPM ```bash @@ -62,22 +94,25 @@ For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md). import { Petstore } from "petstore"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -88,6 +123,9 @@ run(); ## Available Resources and Operations +
+Available methods + ### [pet](docs/sdks/pet/README.md) * [updatePet](docs/sdks/pet/README.md#updatepet) - Update an existing pet @@ -98,6 +136,7 @@ run(); * [deletePet](docs/sdks/pet/README.md#deletepet) - Deletes a pet * [uploadFile](docs/sdks/pet/README.md#uploadfile) - uploads an image + ### [store](docs/sdks/store/README.md) * [getInventory](docs/sdks/store/README.md#getinventory) - Returns pet inventories by status @@ -114,6 +153,8 @@ run(); * [getUserByName](docs/sdks/user/README.md#getuserbyname) - Get user by user name * [updateUser](docs/sdks/user/README.md#updateuser) - Update user * [deleteUser](docs/sdks/user/README.md#deleteuser) - Delete user + +
@@ -131,25 +172,24 @@ To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md). Available standalone functions -- [petAddPet](docs/sdks/pet/README.md#addpet) -- [petDeletePet](docs/sdks/pet/README.md#deletepet) -- [petFindPetsByStatus](docs/sdks/pet/README.md#findpetsbystatus) -- [petFindPetsByTags](docs/sdks/pet/README.md#findpetsbytags) -- [petGetPetById](docs/sdks/pet/README.md#getpetbyid) -- [petUpdatePet](docs/sdks/pet/README.md#updatepet) -- [petUploadFile](docs/sdks/pet/README.md#uploadfile) -- [storeDeleteOrder](docs/sdks/store/README.md#deleteorder) -- [storeGetInventory](docs/sdks/store/README.md#getinventory) -- [storeGetOrderById](docs/sdks/store/README.md#getorderbyid) -- [storePlaceOrder](docs/sdks/store/README.md#placeorder) -- [userCreateUser](docs/sdks/user/README.md#createuser) -- [userCreateUsersWithListInput](docs/sdks/user/README.md#createuserswithlistinput) -- [userDeleteUser](docs/sdks/user/README.md#deleteuser) -- [userGetUserByName](docs/sdks/user/README.md#getuserbyname) -- [userLoginUser](docs/sdks/user/README.md#loginuser) -- [userLogoutUser](docs/sdks/user/README.md#logoutuser) -- [userUpdateUser](docs/sdks/user/README.md#updateuser) - +- [`petAddPet`](docs/sdks/pet/README.md#addpet) - Add a new pet to the store +- [`petDeletePet`](docs/sdks/pet/README.md#deletepet) - Deletes a pet +- [`petFindPetsByStatus`](docs/sdks/pet/README.md#findpetsbystatus) - Finds Pets by status +- [`petFindPetsByTags`](docs/sdks/pet/README.md#findpetsbytags) - Finds Pets by tags +- [`petGetPetById`](docs/sdks/pet/README.md#getpetbyid) - Find pet by ID +- [`petUpdatePet`](docs/sdks/pet/README.md#updatepet) - Update an existing pet +- [`petUploadFile`](docs/sdks/pet/README.md#uploadfile) - uploads an image +- [`storeDeleteOrder`](docs/sdks/store/README.md#deleteorder) - Delete purchase order by ID +- [`storeGetInventory`](docs/sdks/store/README.md#getinventory) - Returns pet inventories by status +- [`storeGetOrderById`](docs/sdks/store/README.md#getorderbyid) - Find purchase order by ID +- [`storePlaceOrder`](docs/sdks/store/README.md#placeorder) - Place an order for a pet +- [`userCreateUser`](docs/sdks/user/README.md#createuser) - Create user +- [`userCreateUsersWithListInput`](docs/sdks/user/README.md#createuserswithlistinput) - Creates list of users with given input array +- [`userDeleteUser`](docs/sdks/user/README.md#deleteuser) - Delete user +- [`userGetUserByName`](docs/sdks/user/README.md#getuserbyname) - Get user by user name +- [`userLoginUser`](docs/sdks/user/README.md#loginuser) - Logs user into the system +- [`userLogoutUser`](docs/sdks/user/README.md#logoutuser) - Logs out current logged in user session +- [`userUpdateUser`](docs/sdks/user/README.md#updateuser) - Update user @@ -172,16 +212,16 @@ Certain SDK methods accept files as part of a multi-part request. It is possible import { Petstore } from "petstore"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - const result = await petstore.pet.uploadFile({ - petId: 565380, - }); + const result = await petstore.pet.uploadFile({ + petId: 565380, + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -199,36 +239,36 @@ To change the default retry strategy for a single API call, simply provide a ret import { Petstore } from "petstore"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet( - { - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }, - { - retries: { - strategy: "backoff", - backoff: { - initialInterval: 1, - maxInterval: 50, - exponent: 1.1, - maxElapsedTime: 100, - }, - retryConnectionErrors: false, - }, - } - ); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }, { + retries: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -240,32 +280,35 @@ If you'd like to override the default retry strategy for all operations that sup import { Petstore } from "petstore"; const petstore = new Petstore({ - retryConfig: { - strategy: "backoff", - backoff: { - initialInterval: 1, - maxInterval: 50, - exponent: 1.1, - maxElapsedTime: 100, - }, - retryConnectionErrors: false, + retryConfig: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, }, - apiKey: "", + retryConnectionErrors: false, + }, + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -276,72 +319,94 @@ run(); ## Error Handling -All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type. +All SDK methods return a response object or throw an error. By default, an API error will throw a `errors.SDKError`. -| Error Object | Status Code | Content Type | +If a HTTP request fails, an operation my also throw an error from the `models/errors/httpclienterrors.ts` module: + +| HTTP Client Error | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | +| RequestAbortedError | HTTP request was aborted by the client | +| RequestTimeoutError | HTTP request timed out due to an AbortSignal signal | +| ConnectionError | HTTP client was unable to make a request to a server | +| InvalidRequestError | Any input used to create a request is invalid | +| UnexpectedClientError | Unrecognised or unexpected error | + +In addition, when custom error responses are specified for an operation, the SDK may throw their associated Error type. You can refer to respective *Errors* tables in SDK docs for more details on possible error types for each operation. For example, the `updatePet` method may throw the following errors: + +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - -Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. - +| errors.SDKError | 4XX, 5XX | \*/\* | ```typescript import { Petstore } from "petstore"; -import { SDKValidationError } from "petstore/models/errors"; +import { + ApiErrorInvalidInput, + ApiErrorNotFound, + ApiErrorUnauthorized, + SDKValidationError, +} from "petstore/models/errors"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - let result; - try { - result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); - } catch (err) { - switch (true) { - case err instanceof SDKValidationError: { - // Validation errors can be pretty-printed - console.error(err.pretty()); - // Raw value may also be inspected - console.error(err.rawValue); - return; - } - case err instanceof errors.ApiErrorInvalidInput: { - console.error(err); // handle exception - return; - } - case err instanceof errors.ApiErrorUnauthorized: { - console.error(err); // handle exception - return; - } - case err instanceof errors.ApiErrorNotFound: { - console.error(err); // handle exception - return; - } - default: { - throw err; - } - } - } + let result; + try { + result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); // Handle the result console.log(result); + } catch (err) { + switch (true) { + case (err instanceof SDKValidationError): { + // Validation errors can be pretty-printed + console.error(err.pretty()); + // Raw value may also be inspected + console.error(err.rawValue); + return; + } + case (err instanceof ApiErrorInvalidInput): { + // Handle err.data$: ApiErrorInvalidInputData + console.error(err); + return; + } + case (err instanceof ApiErrorUnauthorized): { + // Handle err.data$: ApiErrorUnauthorizedData + console.error(err); + return; + } + case (err instanceof ApiErrorNotFound): { + // Handle err.data$: ApiErrorNotFoundData + console.error(err); + return; + } + default: { + throw err; + } + } + } } run(); ``` + +Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. @@ -359,23 +424,26 @@ You can override the default server globally by passing a server index to the `s import { Petstore } from "petstore"; const petstore = new Petstore({ - serverIdx: 0, - apiKey: "", + serverIdx: 0, + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -395,23 +463,26 @@ The default server can also be overridden globally by passing a URL to the `serv import { Petstore } from "petstore"; const petstore = new Petstore({ - serverURL: "https://{environment}.petstore.io", - apiKey: "", + serverURL: "https://{environment}.petstore.io", + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -484,22 +555,25 @@ To authenticate with the API the `apiKey` parameter must be set when initializin import { Petstore } from "petstore"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); diff --git a/RELEASES.md b/RELEASES.md index 5b44e1e..a5ffbd9 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -18,4 +18,14 @@ Based on: ### Generated - [typescript v0.0.3] . ### Releases -- [NPM v0.0.3] https://www.npmjs.com/package/petstore/v/0.0.3 - . \ No newline at end of file +- [NPM v0.0.3] https://www.npmjs.com/package/petstore/v/0.0.3 - . + +## 2024-10-09 04:15:28 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.413.0 (2.436.3) https://github.com/speakeasy-api/speakeasy +### Generated +- [typescript v0.1.0] . +### Releases +- [NPM v0.1.0] https://www.npmjs.com/package/petstore/v/0.1.0 - . \ No newline at end of file diff --git a/USAGE.md b/USAGE.md index 1d1f726..e407e2d 100644 --- a/USAGE.md +++ b/USAGE.md @@ -3,22 +3,25 @@ import { Petstore } from "petstore"; const petstore = new Petstore({ - apiKey: "", + apiKey: "", }); async function run() { - const result = await petstore.pet.updatePet({ - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], - }); + const result = await petstore.pet.updatePet({ + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + "", + ], + }); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); diff --git a/docs/models/components/category.md b/docs/models/components/category.md index 27a36c9..f285cda 100644 --- a/docs/models/components/category.md +++ b/docs/models/components/category.md @@ -6,8 +6,8 @@ import { Category } from "petstore/models/components"; let value: Category = { - id: 1, - name: "Dogs", + id: 1, + name: "Dogs", }; ``` diff --git a/docs/models/components/order.md b/docs/models/components/order.md index ab2ac1c..ba8c821 100644 --- a/docs/models/components/order.md +++ b/docs/models/components/order.md @@ -6,10 +6,10 @@ import { Order } from "petstore/models/components"; let value: Order = { - id: 10, - petId: 198772, - quantity: 7, - status: "approved", + id: 10, + petId: 198772, + quantity: 7, + status: "approved", }; ``` diff --git a/docs/models/components/pet.md b/docs/models/components/pet.md index 4cb45d1..f736433 100644 --- a/docs/models/components/pet.md +++ b/docs/models/components/pet.md @@ -6,13 +6,15 @@ import { Pet } from "petstore/models/components"; let value: Pet = { - id: 10, - name: "doggie", - category: { - id: 1, - name: "Dogs", - }, - photoUrls: [""], + id: 10, + name: "doggie", + category: { + id: 1, + name: "Dogs", + }, + photoUrls: [ + "", + ], }; ``` diff --git a/docs/models/components/security.md b/docs/models/components/security.md index d95fff6..05c59e2 100644 --- a/docs/models/components/security.md +++ b/docs/models/components/security.md @@ -6,7 +6,7 @@ import { Security } from "petstore/models/components"; let value: Security = { - apiKey: "", + apiKey: "", }; ``` diff --git a/docs/models/components/user.md b/docs/models/components/user.md index dbda452..1457ec5 100644 --- a/docs/models/components/user.md +++ b/docs/models/components/user.md @@ -6,14 +6,14 @@ import { User } from "petstore/models/components"; let value: User = { - id: 10, - username: "theUser", - firstName: "John", - lastName: "James", - email: "john@email.com", - password: "12345", - phone: "12345", - userStatus: 1, + id: 10, + username: "theUser", + firstName: "John", + lastName: "James", + email: "john@email.com", + password: "12345", + phone: "12345", + userStatus: 1, }; ``` diff --git a/docs/models/operations/deleteorderrequest.md b/docs/models/operations/deleteorderrequest.md index f25f2a1..68f8296 100644 --- a/docs/models/operations/deleteorderrequest.md +++ b/docs/models/operations/deleteorderrequest.md @@ -6,7 +6,7 @@ import { DeleteOrderRequest } from "petstore/models/operations"; let value: DeleteOrderRequest = { - orderId: 544883, + orderId: 645894, }; ``` diff --git a/docs/models/operations/deletepetrequest.md b/docs/models/operations/deletepetrequest.md index a1c4ced..3754c5d 100644 --- a/docs/models/operations/deletepetrequest.md +++ b/docs/models/operations/deletepetrequest.md @@ -6,7 +6,7 @@ import { DeletePetRequest } from "petstore/models/operations"; let value: DeletePetRequest = { - petId: 844266, + petId: 544883, }; ``` diff --git a/docs/models/operations/deleteuserrequest.md b/docs/models/operations/deleteuserrequest.md index 0540940..f327e9b 100644 --- a/docs/models/operations/deleteuserrequest.md +++ b/docs/models/operations/deleteuserrequest.md @@ -6,7 +6,7 @@ import { DeleteUserRequest } from "petstore/models/operations"; let value: DeleteUserRequest = { - username: "Anahi38", + username: "Orlando46", }; ``` diff --git a/docs/models/operations/getorderbyidrequest.md b/docs/models/operations/getorderbyidrequest.md index e76836e..adffe3f 100644 --- a/docs/models/operations/getorderbyidrequest.md +++ b/docs/models/operations/getorderbyidrequest.md @@ -6,7 +6,7 @@ import { GetOrderByIdRequest } from "petstore/models/operations"; let value: GetOrderByIdRequest = { - orderId: 857946, + orderId: 423655, }; ``` diff --git a/docs/models/operations/getpetbyidrequest.md b/docs/models/operations/getpetbyidrequest.md index 95f605f..34559ef 100644 --- a/docs/models/operations/getpetbyidrequest.md +++ b/docs/models/operations/getpetbyidrequest.md @@ -6,7 +6,7 @@ import { GetPetByIdRequest } from "petstore/models/operations"; let value: GetPetByIdRequest = { - petId: 715190, + petId: 602763, }; ``` diff --git a/docs/models/operations/getuserbynamerequest.md b/docs/models/operations/getuserbynamerequest.md index 49a82ad..ef97868 100644 --- a/docs/models/operations/getuserbynamerequest.md +++ b/docs/models/operations/getuserbynamerequest.md @@ -6,7 +6,7 @@ import { GetUserByNameRequest } from "petstore/models/operations"; let value: GetUserByNameRequest = { - username: "Roselyn_Kassulke", + username: "Hunter.Windler", }; ``` diff --git a/docs/models/operations/loginuserresponse.md b/docs/models/operations/loginuserresponse.md index f97547b..ac33ce9 100644 --- a/docs/models/operations/loginuserresponse.md +++ b/docs/models/operations/loginuserresponse.md @@ -6,10 +6,12 @@ import { LoginUserResponse } from "petstore/models/operations"; let value: LoginUserResponse = { - headers: { - key: [""], - }, - result: "", + headers: { + "key": [ + "", + ], + }, + result: "", }; ``` diff --git a/docs/models/operations/status.md b/docs/models/operations/status.md index 8d60449..7fa1147 100644 --- a/docs/models/operations/status.md +++ b/docs/models/operations/status.md @@ -7,7 +7,7 @@ Status values that need to be considered for filter ```typescript import { Status } from "petstore/models/operations"; -let value: Status = "pending"; +let value: Status = "sold"; ``` ## Values diff --git a/docs/models/operations/updateuserrequest.md b/docs/models/operations/updateuserrequest.md index 930975a..b6b96f6 100644 --- a/docs/models/operations/updateuserrequest.md +++ b/docs/models/operations/updateuserrequest.md @@ -6,17 +6,17 @@ import { UpdateUserRequest } from "petstore/models/operations"; let value: UpdateUserRequest = { - username: "Gerda89", - user: { - id: 10, - username: "theUser", - firstName: "John", - lastName: "James", - email: "john@email.com", - password: "12345", - phone: "12345", - userStatus: 1, - }, + username: "Kenyon2", + user: { + id: 10, + username: "theUser", + firstName: "John", + lastName: "James", + email: "john@email.com", + password: "12345", + phone: "12345", + userStatus: 1, + }, }; ``` diff --git a/docs/models/operations/uploadfilerequest.md b/docs/models/operations/uploadfilerequest.md index 94ba40d..79f746c 100644 --- a/docs/models/operations/uploadfilerequest.md +++ b/docs/models/operations/uploadfilerequest.md @@ -5,15 +5,13 @@ ```typescript import { UploadFileRequest } from "petstore/models/operations"; -let value: UploadFileRequest = { - petId: 602763, -}; +// No examples available for this model ``` ## Fields -| Field | Type | Required | Description | -| -------------------- | -------------------- | -------------------- | -------------------- | -| `petId` | *number* | :heavy_check_mark: | ID of pet to update | -| `additionalMetadata` | *string* | :heavy_minus_sign: | Additional Metadata | -| `requestBody` | *Uint8Array* | :heavy_minus_sign: | N/A | \ No newline at end of file +| Field | Type | Required | Description | +| ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- | +| `petId` | *number* | :heavy_check_mark: | ID of pet to update | +| `additionalMetadata` | *string* | :heavy_minus_sign: | Additional Metadata | +| `requestBody` | *ReadableStream* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/sdks/pet/README.md b/docs/sdks/pet/README.md index c848753..c135c2d 100644 --- a/docs/sdks/pet/README.md +++ b/docs/sdks/pet/README.md @@ -41,11 +41,12 @@ async function run() { }, photoUrls: [ "", + "", ], }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -75,6 +76,7 @@ async function run() { }, photoUrls: [ "", + "", ], }); @@ -85,7 +87,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -106,13 +108,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## addPet @@ -141,7 +142,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -181,7 +182,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -202,10 +203,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## findPetsByStatus @@ -224,7 +224,7 @@ async function run() { const result = await petstore.pet.findPetsByStatus({}); // Handle the result - console.log(result) + console.log(result); } run(); @@ -254,7 +254,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -275,13 +275,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## findPetsByTags @@ -300,7 +299,7 @@ async function run() { const result = await petstore.pet.findPetsByTags({}); // Handle the result - console.log(result) + console.log(result); } run(); @@ -330,7 +329,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -351,13 +350,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## getPetById @@ -378,7 +376,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -400,7 +398,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await petGetPetById(petstore, { - petId: 30806, + petId: 504151, }); if (!res.ok) { @@ -410,7 +408,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -431,13 +429,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## deletePet @@ -458,7 +455,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -480,7 +477,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await petDeletePet(petstore, { - petId: 449384, + petId: 441876, }); if (!res.ok) { @@ -490,7 +487,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -511,13 +508,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## uploadFile @@ -538,7 +534,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -560,7 +556,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await petUploadFile(petstore, { - petId: 586600, + petId: 565380, }); if (!res.ok) { @@ -570,7 +566,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -591,6 +587,6 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/store/README.md b/docs/sdks/store/README.md index dcfb674..42f2864 100644 --- a/docs/sdks/store/README.md +++ b/docs/sdks/store/README.md @@ -32,7 +32,7 @@ async function run() { const result = await petstore.store.getInventory(); // Handle the result - console.log(result) + console.log(result); } run(); @@ -62,7 +62,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -82,12 +82,11 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## placeOrder @@ -111,7 +110,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -146,7 +145,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -167,12 +166,11 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## getOrderById @@ -193,7 +191,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -215,7 +213,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await storeGetOrderById(petstore, { - orderId: 248986, + orderId: 614993, }); if (!res.ok) { @@ -225,7 +223,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -246,13 +244,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## deleteOrder @@ -273,7 +270,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -295,7 +292,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await storeDeleteOrder(petstore, { - orderId: 327709, + orderId: 127902, }); if (!res.ok) { @@ -305,7 +302,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -326,9 +323,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/user/README.md b/docs/sdks/user/README.md index 338aefc..a6752c4 100644 --- a/docs/sdks/user/README.md +++ b/docs/sdks/user/README.md @@ -41,7 +41,7 @@ async function run() { }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -80,7 +80,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -101,10 +101,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## createUsersWithListInput @@ -134,7 +133,7 @@ async function run() { ]); // Handle the result - console.log(result) + console.log(result); } run(); @@ -175,7 +174,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -196,10 +195,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## loginUser @@ -218,7 +216,7 @@ async function run() { const result = await petstore.user.loginUser({}); // Handle the result - console.log(result) + console.log(result); } run(); @@ -248,7 +246,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -269,13 +267,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## logoutUser @@ -293,7 +290,7 @@ const petstore = new Petstore({ async function run() { await petstore.user.logoutUser(); - + } run(); @@ -342,10 +339,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## getUserByName @@ -362,11 +358,11 @@ const petstore = new Petstore({ async function run() { const result = await petstore.user.getUserByName({ - username: "Zachery_Schneider", + username: "Zachery_Lubowitz15", }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -388,7 +384,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await userGetUserByName(petstore, { - username: "Carmel75", + username: "Zachery_Lubowitz15", }); if (!res.ok) { @@ -398,7 +394,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -419,13 +415,12 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## updateUser @@ -442,7 +437,7 @@ const petstore = new Petstore({ async function run() { await petstore.user.updateUser({ - username: "Dandre.Jast32", + username: "Dandre_Hand41", user: { id: 10, username: "theUser", @@ -455,7 +450,7 @@ async function run() { }, }); - + } run(); @@ -477,7 +472,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await userUpdateUser(petstore, { - username: "Cora.Gislason", + username: "Dandre_Hand41", user: { id: 10, username: "theUser", @@ -517,10 +512,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | - +| errors.SDKError | 4XX, 5XX | \*/\* | ## deleteUser @@ -537,11 +531,11 @@ const petstore = new Petstore({ async function run() { const result = await petstore.user.deleteUser({ - username: "Demetris_Torphy", + username: "Demetris_Schmitt", }); // Handle the result - console.log(result) + console.log(result); } run(); @@ -563,7 +557,7 @@ const petstore = new PetstoreCore({ async function run() { const res = await userDeleteUser(petstore, { - username: "Christina.Marks72", + username: "Demetris_Schmitt", }); if (!res.ok) { @@ -573,7 +567,7 @@ async function run() { const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -594,9 +588,9 @@ run(); ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------------------- | --------------------------- | --------------------------- | | errors.ApiErrorInvalidInput | 400 | application/json | | errors.ApiErrorUnauthorized | 401 | application/json | | errors.ApiErrorNotFound | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/jsr.json b/jsr.json index 864d665..30995f4 100644 --- a/jsr.json +++ b/jsr.json @@ -2,7 +2,7 @@ { "name": "petstore", - "version": "0.0.3", + "version": "0.1.0", "exports": { ".": "./src/index.ts", "./models/errors": "./src/models/errors/index.ts", diff --git a/package-lock.json b/package-lock.json index ffa6c99..025366b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "petstore", - "version": "0.0.3", + "version": "0.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "petstore", - "version": "0.0.3", + "version": "0.1.0", "devDependencies": { "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", diff --git a/package.json b/package.json index 8968fe7..1e6e829 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "petstore", - "version": "0.0.3", + "version": "0.1.0", "author": "Speakeasy", "main": "./index.js", "sideEffects": false, @@ -11,7 +11,7 @@ "scripts": { "lint": "eslint --max-warnings=0 src", "build": "tsc", - "prepare": "npm run build" + "prepublishOnly": "npm run build" }, "peerDependencies": { "zod": ">= 3" diff --git a/src/funcs/petAddPet.ts b/src/funcs/petAddPet.ts index 5df05c8..c7e018e 100644 --- a/src/funcs/petAddPet.ts +++ b/src/funcs/petAddPet.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -28,94 +28,89 @@ import { Result } from "../types/fp.js"; * Add a new pet to the store */ export async function petAddPet( - client$: PetstoreCore, - request: components.Pet, - options?: RequestOptions + client: PetstoreCore, + request: components.Pet, + options?: RequestOptions, ): Promise< - Result< - components.Pet, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Pet, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => components.Pet$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload, { explode: true }); - const parsed$ = schemas$.safeParse( - input$, - (value$) => components.Pet$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = encodeJSON$("body", payload$, { explode: true }); + const path = pathToFunc("/pet")(); - const path$ = pathToFunc("/pet")(); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "addPet", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "addPet", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "POST", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["405", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["405", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const [result] = await M.match< + components.Pet, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Pet$inboundSchema), + M.fail([405, "4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Pet, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Pet$inboundSchema), - m$.fail([405, "4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/petDeletePet.ts b/src/funcs/petDeletePet.ts index 9c476f4..ea1ed35 100644 --- a/src/funcs/petDeletePet.ts +++ b/src/funcs/petDeletePet.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -27,114 +27,112 @@ import { Result } from "../types/fp.js"; * Deletes a pet */ export async function petDeletePet( - client$: PetstoreCore, - request: operations.DeletePetRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.DeletePetRequest, + options?: RequestOptions, ): Promise< - Result< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.DeletePetRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.DeletePetRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + petId: encodeSimple("petId", payload.petId, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - petId: encodeSimple$("petId", payload$.petId, { explode: false, charEncoding: "percent" }), - }; + const path = pathToFunc("/pet/{petId}")(pathParams); - const path$ = pathToFunc("/pet/{petId}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + "api_key": encodeSimple("api_key", payload.api_key, { + explode: false, + charEncoding: "none", + }), + }); - const headers$ = new Headers({ - Accept: "application/json", - api_key: encodeSimple$("api_key", payload$.api_key, { - explode: false, - charEncoding: "none", - }), - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "deletePet", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "deletePet", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "DELETE", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Pet$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Pet$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/petFindPetsByStatus.ts b/src/funcs/petFindPetsByStatus.ts index 7dae6a8..147bd53 100644 --- a/src/funcs/petFindPetsByStatus.ts +++ b/src/funcs/petFindPetsByStatus.ts @@ -2,27 +2,27 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import { encodeFormQuery as encodeFormQuery$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import * as operations from "../models/operations/index.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Finds Pets by status @@ -31,111 +31,106 @@ import * as z from "zod"; * Multiple status values can be provided with comma separated strings */ export async function petFindPetsByStatus( - client$: PetstoreCore, - request: operations.FindPetsByStatusRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.FindPetsByStatusRequest, + options?: RequestOptions, ): Promise< - Result< - Array, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + Array, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = typeof request === "undefined" ? {} : request; - - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.FindPetsByStatusRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const parsed = safeParse( + request, + (value) => operations.FindPetsByStatusRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const path$ = pathToFunc("/pet/findByStatus")(); + const path = pathToFunc("/pet/findByStatus")(); - const query$ = encodeFormQuery$({ - status: payload$.status, - }); + const query = encodeFormQuery({ + "status": payload.status, + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const headers = new Headers({ + Accept: "application/json", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "findPetsByStatus", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "findPetsByStatus", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - query: query$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const [result$] = await m$.match< - Array, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, z.array(components.Pet$inboundSchema)), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + Array, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, z.array(components.Pet$inboundSchema)), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/petFindPetsByTags.ts b/src/funcs/petFindPetsByTags.ts index ea89abc..058a68f 100644 --- a/src/funcs/petFindPetsByTags.ts +++ b/src/funcs/petFindPetsByTags.ts @@ -2,27 +2,27 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import { encodeFormQuery as encodeFormQuery$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import * as operations from "../models/operations/index.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Finds Pets by tags @@ -31,111 +31,106 @@ import * as z from "zod"; * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ export async function petFindPetsByTags( - client$: PetstoreCore, - request: operations.FindPetsByTagsRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.FindPetsByTagsRequest, + options?: RequestOptions, ): Promise< - Result< - Array, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + Array, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = typeof request === "undefined" ? {} : request; - - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.FindPetsByTagsRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const parsed = safeParse( + request, + (value) => operations.FindPetsByTagsRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const path$ = pathToFunc("/pet/findByTags")(); + const path = pathToFunc("/pet/findByTags")(); - const query$ = encodeFormQuery$({ - tags: payload$.tags, - }); + const query = encodeFormQuery({ + "tags": payload.tags, + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const headers = new Headers({ + Accept: "application/json", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "findPetsByTags", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "findPetsByTags", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - query: query$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const [result$] = await m$.match< - Array, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, z.array(components.Pet$inboundSchema)), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + Array, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, z.array(components.Pet$inboundSchema)), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/petGetPetById.ts b/src/funcs/petGetPetById.ts index f2b21ef..b395b7d 100644 --- a/src/funcs/petGetPetById.ts +++ b/src/funcs/petGetPetById.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -30,110 +30,108 @@ import { Result } from "../types/fp.js"; * Returns a single pet */ export async function petGetPetById( - client$: PetstoreCore, - request: operations.GetPetByIdRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.GetPetByIdRequest, + options?: RequestOptions, ): Promise< - Result< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.GetPetByIdRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.GetPetByIdRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + petId: encodeSimple("petId", payload.petId, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - petId: encodeSimple$("petId", payload$.petId, { explode: false, charEncoding: "percent" }), - }; + const path = pathToFunc("/pet/{petId}")(pathParams); - const path$ = pathToFunc("/pet/{petId}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "getPetById", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "getPetById", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Pet$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Pet$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/petUpdatePet.ts b/src/funcs/petUpdatePet.ts index 60a3fdd..66ca2b3 100644 --- a/src/funcs/petUpdatePet.ts +++ b/src/funcs/petUpdatePet.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -29,107 +29,102 @@ import { Result } from "../types/fp.js"; * Update an existing pet by Id */ export async function petUpdatePet( - client$: PetstoreCore, - request: components.Pet, - options?: RequestOptions + client: PetstoreCore, + request: components.Pet, + options?: RequestOptions, ): Promise< - Result< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => components.Pet$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload, { explode: true }); - const parsed$ = schemas$.safeParse( - input$, - (value$) => components.Pet$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = encodeJSON$("body", payload$, { explode: true }); + const path = pathToFunc("/pet")(); - const path$ = pathToFunc("/pet")(); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "updatePet", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "updatePet", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "PUT", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Pet, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Pet$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Pet, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Pet$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/petUploadFile.ts b/src/funcs/petUploadFile.ts index 2e94767..f2eb4f9 100644 --- a/src/funcs/petUploadFile.ts +++ b/src/funcs/petUploadFile.ts @@ -3,22 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { - encodeFormQuery as encodeFormQuery$, - encodeSimple as encodeSimple$, -} from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -29,103 +26,101 @@ import { Result } from "../types/fp.js"; * uploads an image */ export async function petUploadFile( - client$: PetstoreCore, - request: operations.UploadFileRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.UploadFileRequest, + options?: RequestOptions, ): Promise< - Result< - components.ApiResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.ApiResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; - - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.UploadFileRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = payload$.RequestBody; + const parsed = safeParse( + request, + (value) => operations.UploadFileRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload.RequestBody; - const pathParams$ = { - petId: encodeSimple$("petId", payload$.petId, { explode: false, charEncoding: "percent" }), - }; + const pathParams = { + petId: encodeSimple("petId", payload.petId, { + explode: false, + charEncoding: "percent", + }), + }; - const path$ = pathToFunc("/pet/{petId}/uploadImage")(pathParams$); + const path = pathToFunc("/pet/{petId}/uploadImage")(pathParams); - const query$ = encodeFormQuery$({ - additionalMetadata: payload$.additionalMetadata, - }); + const query = encodeFormQuery({ + "additionalMetadata": payload.additionalMetadata, + }); - const headers$ = new Headers({ - "Content-Type": "application/octet-stream", - Accept: "application/json", - }); + const headers = new Headers({ + "Content-Type": "application/octet-stream", + Accept: "application/json", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "uploadFile", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "uploadFile", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "POST", - path: path$, - headers: headers$, - query: query$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const [result$] = await m$.match< - components.ApiResponse, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.ApiResponse$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + components.ApiResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.ApiResponse$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/storeDeleteOrder.ts b/src/funcs/storeDeleteOrder.ts index 0ac0d1f..c3e07cd 100644 --- a/src/funcs/storeDeleteOrder.ts +++ b/src/funcs/storeDeleteOrder.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -30,113 +30,108 @@ import { Result } from "../types/fp.js"; * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors */ export async function storeDeleteOrder( - client$: PetstoreCore, - request: operations.DeleteOrderRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.DeleteOrderRequest, + options?: RequestOptions, ): Promise< - Result< - components.Order, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Order, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.DeleteOrderRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.DeleteOrderRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + orderId: encodeSimple("orderId", payload.orderId, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - orderId: encodeSimple$("orderId", payload$.orderId, { - explode: false, - charEncoding: "percent", - }), - }; + const path = pathToFunc("/store/order/{orderId}")(pathParams); - const path$ = pathToFunc("/store/order/{orderId}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "deleteOrder", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "deleteOrder", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "DELETE", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Order, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Order$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Order, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Order$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/storeGetInventory.ts b/src/funcs/storeGetInventory.ts index baa1ed8..9861326 100644 --- a/src/funcs/storeGetInventory.ts +++ b/src/funcs/storeGetInventory.ts @@ -2,23 +2,23 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import * as m$ from "../lib/matchers.js"; +import * as M from "../lib/matchers.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Returns pet inventories by status @@ -27,88 +27,85 @@ import * as z from "zod"; * Returns a map of status codes to quantities */ export async function storeGetInventory( - client$: PetstoreCore, - options?: RequestOptions + client: PetstoreCore, + options?: RequestOptions, ): Promise< - Result< - { [k: string]: number }, - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + { [k: string]: number }, + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const path$ = pathToFunc("/store/inventory")(); + const path = pathToFunc("/store/inventory")(); - const headers$ = new Headers({ - Accept: "application/json", - }); + const headers = new Headers({ + Accept: "application/json", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "getInventory", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "getInventory", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const [result$] = await m$.match< - { [k: string]: number }, - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, z.record(z.number().int())), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + { [k: string]: number }, + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, z.record(z.number().int())), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/storeGetOrderById.ts b/src/funcs/storeGetOrderById.ts index 79f291b..c92fe26 100644 --- a/src/funcs/storeGetOrderById.ts +++ b/src/funcs/storeGetOrderById.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -30,113 +30,108 @@ import { Result } from "../types/fp.js"; * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. */ export async function storeGetOrderById( - client$: PetstoreCore, - request: operations.GetOrderByIdRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.GetOrderByIdRequest, + options?: RequestOptions, ): Promise< - Result< - components.Order, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Order, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.GetOrderByIdRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.GetOrderByIdRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + orderId: encodeSimple("orderId", payload.orderId, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - orderId: encodeSimple$("orderId", payload$.orderId, { - explode: false, - charEncoding: "percent", - }), - }; + const path = pathToFunc("/store/order/{orderId}")(pathParams); - const path$ = pathToFunc("/store/order/{orderId}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "getOrderById", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "getOrderById", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Order, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Order$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Order, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Order$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/storePlaceOrder.ts b/src/funcs/storePlaceOrder.ts index ca56bda..ca684fd 100644 --- a/src/funcs/storePlaceOrder.ts +++ b/src/funcs/storePlaceOrder.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -29,104 +29,101 @@ import { Result } from "../types/fp.js"; * Place a new order in the store */ export async function storePlaceOrder( - client$: PetstoreCore, - request?: components.Order | undefined, - options?: RequestOptions + client: PetstoreCore, + request?: components.Order | undefined, + options?: RequestOptions, ): Promise< - Result< - components.Order, - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.Order, + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => components.Order$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); - const parsed$ = schemas$.safeParse( - input$, - (value$) => components.Order$outboundSchema.optional().parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); + const path = pathToFunc("/store/order")(); - const path$ = pathToFunc("/store/order")(); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "placeOrder", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "placeOrder", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "POST", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["401", "404", "405", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["401", "404", "405", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.Order, + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.Order$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail([405, "4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.Order, - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.Order$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail([405, "4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/userCreateUser.ts b/src/funcs/userCreateUser.ts index 3b57f91..5b718cd 100644 --- a/src/funcs/userCreateUser.ts +++ b/src/funcs/userCreateUser.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; @@ -28,94 +28,91 @@ import { Result } from "../types/fp.js"; * This can only be done by the logged in user. */ export async function userCreateUser( - client$: PetstoreCore, - request?: components.User | undefined, - options?: RequestOptions + client: PetstoreCore, + request?: components.User | undefined, + options?: RequestOptions, ): Promise< - Result< - components.User, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.User, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => components.User$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); - const parsed$ = schemas$.safeParse( - input$, - (value$) => components.User$outboundSchema.optional().parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); + const path = pathToFunc("/user")(); - const path$ = pathToFunc("/user")(); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "createUser", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "createUser", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "POST", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const [result] = await M.match< + components.User, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.User$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.User, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.User$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/userCreateUsersWithListInput.ts b/src/funcs/userCreateUsersWithListInput.ts index c8ecabb..e8f1a47 100644 --- a/src/funcs/userCreateUsersWithListInput.ts +++ b/src/funcs/userCreateUsersWithListInput.ts @@ -2,25 +2,25 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Creates list of users with given input array @@ -29,94 +29,91 @@ import * as z from "zod"; * Creates list of users with given input array */ export async function userCreateUsersWithListInput( - client$: PetstoreCore, - request?: Array | undefined, - options?: RequestOptions + client: PetstoreCore, + request?: Array | undefined, + options?: RequestOptions, ): Promise< - Result< - components.User, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.User, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; - - const parsed$ = schemas$.safeParse( - input$, - (value$) => z.array(components.User$outboundSchema).optional().parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); + const parsed = safeParse( + request, + (value) => z.array(components.User$outboundSchema).optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); - const path$ = pathToFunc("/user/createWithList")(); + const path = pathToFunc("/user/createWithList")(); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "application/json", - }); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "createUsersWithListInput", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "createUsersWithListInput", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "POST", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const [result$] = await m$.match< - components.User, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.User$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + components.User, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.User$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/userDeleteUser.ts b/src/funcs/userDeleteUser.ts index ce79e27..da21f73 100644 --- a/src/funcs/userDeleteUser.ts +++ b/src/funcs/userDeleteUser.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -30,113 +30,108 @@ import { Result } from "../types/fp.js"; * This can only be done by the logged in user. */ export async function userDeleteUser( - client$: PetstoreCore, - request: operations.DeleteUserRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.DeleteUserRequest, + options?: RequestOptions, ): Promise< - Result< - components.User, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.User, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.DeleteUserRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.DeleteUserRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + username: encodeSimple("username", payload.username, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - username: encodeSimple$("username", payload$.username, { - explode: false, - charEncoding: "percent", - }), - }; + const path = pathToFunc("/user/{username}")(pathParams); - const path$ = pathToFunc("/user/{username}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "deleteUser", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "deleteUser", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "DELETE", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.User, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.User$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.User, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.User$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/userGetUserByName.ts b/src/funcs/userGetUserByName.ts index 43b6b4f..5eabbd2 100644 --- a/src/funcs/userGetUserByName.ts +++ b/src/funcs/userGetUserByName.ts @@ -3,19 +3,19 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import * as components from "../models/components/index.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -27,113 +27,108 @@ import { Result } from "../types/fp.js"; * Get user by user name */ export async function userGetUserByName( - client$: PetstoreCore, - request: operations.GetUserByNameRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.GetUserByNameRequest, + options?: RequestOptions, ): Promise< - Result< - components.User, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + components.User, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; + const parsed = safeParse( + request, + (value) => operations.GetUserByNameRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.GetUserByNameRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const pathParams = { + username: encodeSimple("username", payload.username, { + explode: false, + charEncoding: "percent", + }), + }; - const pathParams$ = { - username: encodeSimple$("username", payload$.username, { - explode: false, - charEncoding: "percent", - }), - }; + const path = pathToFunc("/user/{username}")(pathParams); - const path$ = pathToFunc("/user/{username}")(pathParams$); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "getUserByName", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "getUserByName", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + components.User, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.User$inboundSchema), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - components.User, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, components.User$inboundSchema), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/userLoginUser.ts b/src/funcs/userLoginUser.ts index 52e3b18..b7361b0 100644 --- a/src/funcs/userLoginUser.ts +++ b/src/funcs/userLoginUser.ts @@ -3,18 +3,18 @@ */ import { PetstoreCore } from "../core.js"; -import { encodeFormQuery as encodeFormQuery$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import * as errors from "../models/errors/index.js"; import { SDKError } from "../models/errors/sdkerror.js"; @@ -26,112 +26,110 @@ import { Result } from "../types/fp.js"; * Logs user into the system */ export async function userLoginUser( - client$: PetstoreCore, - request: operations.LoginUserRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.LoginUserRequest, + options?: RequestOptions, ): Promise< - Result< - operations.LoginUserResponse, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + operations.LoginUserResponse, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = typeof request === "undefined" ? {} : request; + const parsed = safeParse( + request, + (value) => operations.LoginUserRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.LoginUserRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = null; + const path = pathToFunc("/user/login")(); - const path$ = pathToFunc("/user/login")(); + const query = encodeFormQuery({ + "password": payload.password, + "username": payload.username, + }); - const query$ = encodeFormQuery$({ - password: payload$.password, - username: payload$.username, - }); + const headers = new Headers({ + Accept: "application/json", + }); - const headers$ = new Headers({ - Accept: "application/json", - }); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "loginUser", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "loginUser", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - query: query$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "404", "4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["400", "401", "404", "4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; + const [result] = await M.match< + operations.LoginUserResponse, + | errors.ApiErrorInvalidInput + | errors.ApiErrorUnauthorized + | errors.ApiErrorNotFound + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, operations.LoginUserResponse$inboundSchema, { + hdrs: true, + key: "Result", + }), + M.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), + M.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), + M.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), + M.fail(["4XX", "5XX"]), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } - const [result$] = await m$.match< - operations.LoginUserResponse, - | errors.ApiErrorInvalidInput - | errors.ApiErrorUnauthorized - | errors.ApiErrorNotFound - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.json(200, operations.LoginUserResponse$inboundSchema, { hdrs: true, key: "Result" }), - m$.jsonErr(400, errors.ApiErrorInvalidInput$inboundSchema), - m$.jsonErr(401, errors.ApiErrorUnauthorized$inboundSchema), - m$.jsonErr(404, errors.ApiErrorNotFound$inboundSchema), - m$.fail(["4XX", "5XX"]) - )(response, { extraFields: responseFields$ }); - if (!result$.ok) { - return result$; - } - - return result$; + return result; } diff --git a/src/funcs/userLogoutUser.ts b/src/funcs/userLogoutUser.ts index a293362..0e9b51f 100644 --- a/src/funcs/userLogoutUser.ts +++ b/src/funcs/userLogoutUser.ts @@ -2,99 +2,96 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import * as m$ from "../lib/matchers.js"; +import * as M from "../lib/matchers.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Logs out current logged in user session */ export async function userLogoutUser( - client$: PetstoreCore, - options?: RequestOptions + client: PetstoreCore, + options?: RequestOptions, ): Promise< - Result< - void, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const path$ = pathToFunc("/user/logout")(); + const path = pathToFunc("/user/logout")(); - const headers$ = new Headers({ - Accept: "*/*", - }); + const headers = new Headers({ + Accept: "*/*", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "logoutUser", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "logoutUser", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "GET", - path: path$, - headers: headers$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const [result$] = await m$.match< - void, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.nil(200, z.void()), - m$.fail(["4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail(["4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/funcs/userUpdateUser.ts b/src/funcs/userUpdateUser.ts index 885e9b7..b9b3243 100644 --- a/src/funcs/userUpdateUser.ts +++ b/src/funcs/userUpdateUser.ts @@ -2,25 +2,25 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { PetstoreCore } from "../core.js"; -import { encodeJSON as encodeJSON$, encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import * as m$ from "../lib/matchers.js"; -import * as schemas$ from "../lib/schemas.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { safeParse } from "../lib/schemas.js"; import { RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import * as operations from "../models/operations/index.js"; import { Result } from "../types/fp.js"; -import * as z from "zod"; /** * Update user @@ -29,101 +29,96 @@ import * as z from "zod"; * This can only be done by the logged in user. */ export async function userUpdateUser( - client$: PetstoreCore, - request: operations.UpdateUserRequest, - options?: RequestOptions + client: PetstoreCore, + request: operations.UpdateUserRequest, + options?: RequestOptions, ): Promise< - Result< - void, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - > + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > > { - const input$ = request; - - const parsed$ = schemas$.safeParse( - input$, - (value$) => operations.UpdateUserRequest$outboundSchema.parse(value$), - "Input validation failed" - ); - if (!parsed$.ok) { - return parsed$; - } - const payload$ = parsed$.value; - const body$ = encodeJSON$("body", payload$.User, { explode: true }); + const parsed = safeParse( + request, + (value) => operations.UpdateUserRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.User, { explode: true }); - const pathParams$ = { - username: encodeSimple$("username", payload$.username, { - explode: false, - charEncoding: "percent", - }), - }; + const pathParams = { + username: encodeSimple("username", payload.username, { + explode: false, + charEncoding: "percent", + }), + }; - const path$ = pathToFunc("/user/{username}")(pathParams$); + const path = pathToFunc("/user/{username}")(pathParams); - const headers$ = new Headers({ - "Content-Type": "application/json", - Accept: "*/*", - }); + const headers = new Headers({ + "Content-Type": "application/json", + Accept: "*/*", + }); - const apiKey$ = await extractSecurity(client$.options$.apiKey); - const security$ = apiKey$ == null ? {} : { apiKey: apiKey$ }; - const context = { - operationID: "updateUser", - oAuth2Scopes: [], - securitySource: client$.options$.apiKey, - }; - const securitySettings$ = resolveGlobalSecurity(security$); + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const context = { + operationID: "updateUser", + oAuth2Scopes: [], + securitySource: client._options.apiKey, + }; + const requestSecurity = resolveGlobalSecurity(securityInput); - const requestRes = client$.createRequest$( - context, - { - security: securitySettings$, - method: "PUT", - path: path$, - headers: headers$, - body: body$, - timeoutMs: options?.timeoutMs || client$.options$.timeoutMs || -1, - }, - options - ); - if (!requestRes.ok) { - return requestRes; - } - const request$ = requestRes.value; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; - const doResult = await client$.do$(request$, { - context, - errorCodes: ["4XX", "5XX"], - retryConfig: options?.retries || client$.options$.retryConfig, - retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], - }); - if (!doResult.ok) { - return doResult; - } - const response = doResult.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: options?.retries + || client._options.retryConfig, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; - const [result$] = await m$.match< - void, - | SDKError - | SDKValidationError - | UnexpectedClientError - | InvalidRequestError - | RequestAbortedError - | RequestTimeoutError - | ConnectionError - >( - m$.nil(200, z.void()), - m$.fail(["4XX", "5XX"]) - )(response); - if (!result$.ok) { - return result$; - } + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail(["4XX", "5XX"]), + )(response); + if (!result.ok) { + return result; + } - return result$; + return result; } diff --git a/src/hooks/hooks.ts b/src/hooks/hooks.ts index a6b6e17..d1b3396 100644 --- a/src/hooks/hooks.ts +++ b/src/hooks/hooks.ts @@ -4,100 +4,109 @@ import { RequestInput } from "../lib/http.js"; import { - AfterErrorContext, - AfterErrorHook, - AfterSuccessContext, - AfterSuccessHook, - BeforeRequestContext, - BeforeRequestHook, - BeforeCreateRequestHook, - BeforeCreateRequestContext, - Hooks, - SDKInitHook, - SDKInitOptions, + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeCreateRequestContext, + BeforeCreateRequestHook, + BeforeRequestContext, + BeforeRequestHook, + Hooks, + SDKInitHook, + SDKInitOptions, } from "./types.js"; import { initHooks } from "./registration.js"; export class SDKHooks implements Hooks { - sdkInitHooks: SDKInitHook[] = []; - beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; - beforeRequestHooks: BeforeRequestHook[] = []; - afterSuccessHooks: AfterSuccessHook[] = []; - afterErrorHooks: AfterErrorHook[] = []; - - constructor() { - initHooks(this); + sdkInitHooks: SDKInitHook[] = []; + beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; + beforeRequestHooks: BeforeRequestHook[] = []; + afterSuccessHooks: AfterSuccessHook[] = []; + afterErrorHooks: AfterErrorHook[] = []; + + constructor() { + initHooks(this); + } + + registerSDKInitHook(hook: SDKInitHook) { + this.sdkInitHooks.push(hook); + } + + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { + this.beforeCreateRequestHooks.push(hook); + } + + registerBeforeRequestHook(hook: BeforeRequestHook) { + this.beforeRequestHooks.push(hook); + } + + registerAfterSuccessHook(hook: AfterSuccessHook) { + this.afterSuccessHooks.push(hook); + } + + registerAfterErrorHook(hook: AfterErrorHook) { + this.afterErrorHooks.push(hook); + } + + sdkInit(opts: SDKInitOptions): SDKInitOptions { + return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + } + + beforeCreateRequest( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ): RequestInput { + let inp = input; + + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); } - registerSDKInitHook(hook: SDKInitHook) { - this.sdkInitHooks.push(hook); - } + return inp; + } - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { - this.beforeCreateRequestHooks.push(hook); - } + async beforeRequest( + hookCtx: BeforeRequestContext, + request: Request, + ): Promise { + let req = request; - registerBeforeRequestHook(hook: BeforeRequestHook) { - this.beforeRequestHooks.push(hook); + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); } - registerAfterSuccessHook(hook: AfterSuccessHook) { - this.afterSuccessHooks.push(hook); - } + return req; + } - registerAfterErrorHook(hook: AfterErrorHook) { - this.afterErrorHooks.push(hook); - } + async afterSuccess( + hookCtx: AfterSuccessContext, + response: Response, + ): Promise { + let res = response; - sdkInit(opts: SDKInitOptions): SDKInitOptions { - return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); } - beforeCreateRequest(hookCtx: BeforeCreateRequestContext, input: RequestInput): RequestInput { - let inp = input; - - for (const hook of this.beforeCreateRequestHooks) { - inp = hook.beforeCreateRequest(hookCtx, inp); - } - - return inp; + return res; + } + + async afterError( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ): Promise<{ response: Response | null; error: unknown }> { + let res = response; + let err = error; + + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; } - async beforeRequest(hookCtx: BeforeRequestContext, request: Request): Promise { - let req = request; - - for (const hook of this.beforeRequestHooks) { - req = await hook.beforeRequest(hookCtx, req); - } - - return req; - } - - async afterSuccess(hookCtx: AfterSuccessContext, response: Response): Promise { - let res = response; - - for (const hook of this.afterSuccessHooks) { - res = await hook.afterSuccess(hookCtx, res); - } - - return res; - } - - async afterError( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ): Promise<{ response: Response | null; error: unknown }> { - let res = response; - let err = error; - - for (const hook of this.afterErrorHooks) { - const result = await hook.afterError(hookCtx, res, err); - res = result.response; - err = result.error; - } - - return { response: res, error: err }; - } + return { response: res, error: err }; + } } diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 8f0e4db..f60ec7a 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -2,5 +2,5 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./types.js"; export * from "./hooks.js"; +export * from "./types.js"; diff --git a/src/hooks/types.ts b/src/hooks/types.ts index 3a31914..656b9e3 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -5,16 +5,16 @@ import { HTTPClient, RequestInput } from "../lib/http.js"; export type HookContext = { - operationID: string; - oAuth2Scopes?: string[]; - securitySource?: any | (() => Promise); + operationID: string; + oAuth2Scopes?: string[]; + securitySource?: any | (() => Promise); }; export type Awaitable = T | Promise; export type SDKInitOptions = { - baseURL: URL | null; - client: HTTPClient; + baseURL: URL | null; + client: HTTPClient; }; export type BeforeCreateRequestContext = HookContext & {}; @@ -27,63 +27,72 @@ export type AfterErrorContext = HookContext & {}; * hook can return a new baseURL and HTTP client to be used by the SDK. */ export interface SDKInitHook { - sdkInit: (opts: SDKInitOptions) => SDKInitOptions; + sdkInit: (opts: SDKInitOptions) => SDKInitOptions; } export interface BeforeCreateRequestHook { - /** - * A hook that is called before the SDK creates a `Request` object. The hook - * can modify how a request is constructed since certain modifications, like - * changing the request URL, cannot be done on a request object directly. - */ - beforeCreateRequest: (hookCtx: BeforeCreateRequestContext, input: RequestInput) => RequestInput; + /** + * A hook that is called before the SDK creates a `Request` object. The hook + * can modify how a request is constructed since certain modifications, like + * changing the request URL, cannot be done on a request object directly. + */ + beforeCreateRequest: ( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ) => RequestInput; } export interface BeforeRequestHook { - /** - * A hook that is called before the SDK sends a request. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * replace the request before it is sent or throw an error to stop the - * request from being sent. - */ - beforeRequest: (hookCtx: BeforeRequestContext, request: Request) => Awaitable; + /** + * A hook that is called before the SDK sends a request. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * replace the request before it is sent or throw an error to stop the + * request from being sent. + */ + beforeRequest: ( + hookCtx: BeforeRequestContext, + request: Request, + ) => Awaitable; } export interface AfterSuccessHook { - /** - * A hook that is called after the SDK receives a response. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * modify the response before it is handled or throw an error to stop the - * response from being handled. - */ - afterSuccess: (hookCtx: AfterSuccessContext, response: Response) => Awaitable; + /** + * A hook that is called after the SDK receives a response. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * modify the response before it is handled or throw an error to stop the + * response from being handled. + */ + afterSuccess: ( + hookCtx: AfterSuccessContext, + response: Response, + ) => Awaitable; } export interface AfterErrorHook { - /** - * A hook that is called after the SDK encounters an error, or a - * non-successful response. The hook can introduce instrumentation code such - * as logging, tracing and metrics or modify the response or error values. - */ - afterError: ( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ) => Awaitable<{ - response: Response | null; - error: unknown; - }>; + /** + * A hook that is called after the SDK encounters an error, or a + * non-successful response. The hook can introduce instrumentation code such + * as logging, tracing and metrics or modify the response or error values. + */ + afterError: ( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ) => Awaitable<{ + response: Response | null; + error: unknown; + }>; } export interface Hooks { - /** Registers a hook to be used by the SDK for initialization event. */ - registerSDKInitHook(hook: SDKInitHook): void; - /** Registers a hook to be used by the SDK for to modify `Request` construction. */ - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; - /** Registers a hook to be used by the SDK for the before request event. */ - registerBeforeRequestHook(hook: BeforeRequestHook): void; - /** Registers a hook to be used by the SDK for the after success event. */ - registerAfterSuccessHook(hook: AfterSuccessHook): void; - /** Registers a hook to be used by the SDK for the after error event. */ - registerAfterErrorHook(hook: AfterErrorHook): void; + /** Registers a hook to be used by the SDK for initialization event. */ + registerSDKInitHook(hook: SDKInitHook): void; + /** Registers a hook to be used by the SDK for to modify `Request` construction. */ + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; + /** Registers a hook to be used by the SDK for the before request event. */ + registerBeforeRequestHook(hook: BeforeRequestHook): void; + /** Registers a hook to be used by the SDK for the after success event. */ + registerAfterSuccessHook(hook: AfterSuccessHook): void; + /** Registers a hook to be used by the SDK for the after error event. */ + registerAfterErrorHook(hook: AfterErrorHook): void; } diff --git a/src/index.ts b/src/index.ts index ceb6380..5ddc765 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,5 +2,6 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./sdk/sdk.js"; export * from "./lib/config.js"; +export * as files from "./lib/files.js"; +export * from "./sdk/sdk.js"; diff --git a/src/lib/config.ts b/src/lib/config.ts index 24b45be..4274be9 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -12,19 +12,19 @@ import { Params, pathToFunc } from "./url.js"; * Contains the list of servers available to the SDK */ export const ServerList = [ - /** - * A per-environment API. - */ - "https://{environment}.petstore.io", + /** + * A per-environment API. + */ + "https://{environment}.petstore.io", ] as const; /** * The environment name. Defaults to the production environment. */ export const ServerEnvironment = { - Prod: "prod", - Staging: "staging", - Dev: "dev", + Prod: "prod", + Staging: "staging", + Dev: "dev", } as const; /** * The environment name. Defaults to the production environment. @@ -32,56 +32,56 @@ export const ServerEnvironment = { export type ServerEnvironment = ClosedEnum; export type SDKOptions = { - apiKey?: string | (() => Promise); + apiKey?: string | (() => Promise); - httpClient?: HTTPClient; - /** - * Allows overriding the default server used by the SDK - */ - serverIdx?: number; - /** - * Sets the environment variable for url substitution - */ - environment?: ServerEnvironment; - /** - * Allows overriding the default server URL used by the SDK - */ - serverURL?: string; - /** - * Allows overriding the default retry config used by the SDK - */ - retryConfig?: RetryConfig; - timeoutMs?: number; - debugLogger?: Logger; + httpClient?: HTTPClient; + /** + * Allows overriding the default server used by the SDK + */ + serverIdx?: number; + /** + * Sets the environment variable for url substitution + */ + environment?: ServerEnvironment; + /** + * Allows overriding the default server URL used by the SDK + */ + serverURL?: string; + /** + * Allows overriding the default retry config used by the SDK + */ + retryConfig?: RetryConfig; + timeoutMs?: number; + debugLogger?: Logger; }; export function serverURLFromOptions(options: SDKOptions): URL | null { - let serverURL = options.serverURL; + let serverURL = options.serverURL; - const serverParams: Params[] = [ - { - environment: options.environment ?? "prod", - }, - ]; - let params: Params = {}; + const serverParams: Params[] = [ + { + "environment": options.environment ?? "prod", + }, + ]; + let params: Params = {}; - if (!serverURL) { - const serverIdx = options.serverIdx ?? 0; - if (serverIdx < 0 || serverIdx >= ServerList.length) { - throw new Error(`Invalid server index ${serverIdx}`); - } - serverURL = ServerList[serverIdx] || ""; - params = serverParams[serverIdx] || {}; + if (!serverURL) { + const serverIdx = options.serverIdx ?? 0; + if (serverIdx < 0 || serverIdx >= ServerList.length) { + throw new Error(`Invalid server index ${serverIdx}`); } + serverURL = ServerList[serverIdx] || ""; + params = serverParams[serverIdx] || {}; + } - const u = pathToFunc(serverURL)(params); - return new URL(u); + const u = pathToFunc(serverURL)(params); + return new URL(u); } export const SDK_METADATA = { - language: "typescript", - openapiDocVersion: "1.0.0", - sdkVersion: "0.0.3", - genVersion: "2.404.3", - userAgent: "speakeasy-sdk/typescript 0.0.3 2.404.3 1.0.0 petstore", + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "0.1.0", + genVersion: "2.436.3", + userAgent: "speakeasy-sdk/typescript 0.1.0 2.436.3 1.0.0 petstore", } as const; diff --git a/src/lib/files.ts b/src/lib/files.ts new file mode 100644 index 0000000..19e0804 --- /dev/null +++ b/src/lib/files.ts @@ -0,0 +1,40 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/** + * Consumes a stream and returns a concatenated array buffer. Useful in + * situations where we need to read the whole file because it forms part of a + * larger payload containing other fields, and we can't modify the underlying + * request structure. + */ +export async function readableStreamToArrayBuffer( + readable: ReadableStream, +): Promise { + const reader = readable.getReader(); + const chunks: Uint8Array[] = []; + + let totalLength = 0; + let done = false; + + while (!done) { + const { value, done: doneReading } = await reader.read(); + + if (doneReading) { + done = true; + } else { + chunks.push(value); + totalLength += value.length; + } + } + + const concatenatedChunks = new Uint8Array(totalLength); + let offset = 0; + + for (const chunk of chunks) { + concatenatedChunks.set(chunk, offset); + offset += chunk.length; + } + + return concatenatedChunks.buffer; +} diff --git a/src/lib/matchers.ts b/src/lib/matchers.ts index dcb468b..55a9e14 100644 --- a/src/lib/matchers.ts +++ b/src/lib/matchers.ts @@ -2,271 +2,285 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { safeParse } from "./schemas.js"; -import { StatusCodePredicate, matchResponse, matchStatusCode } from "./http.js"; -import { isPlainObject } from "./is-plain-object.js"; import { SDKError } from "../models/errors/sdkerror.js"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { Result } from "../types/fp.js"; +import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js"; +import { isPlainObject } from "./is-plain-object.js"; +import { safeParse } from "./schemas.js"; -export type Encoding = "json" | "text" | "bytes" | "stream" | "sse" | "nil" | "fail"; +export type Encoding = + | "json" + | "text" + | "bytes" + | "stream" + | "sse" + | "nil" + | "fail"; const DEFAULT_CONTENT_TYPES: Record = { - json: "application/json", - text: "text/plain", - bytes: "application/octet-stream", - stream: "application/octet-stream", - sse: "text/event-stream", - nil: "*", - fail: "*", + json: "application/json", + text: "text/plain", + bytes: "application/octet-stream", + stream: "application/octet-stream", + sse: "text/event-stream", + nil: "*", + fail: "*", }; type Schema = { parse(raw: unknown): T }; -type MatchOptions = { ctype?: string; hdrs?: boolean; key?: string; sseSentinel?: string }; +type MatchOptions = { + ctype?: string; + hdrs?: boolean; + key?: string; + sseSentinel?: string; +}; export type ValueMatcher = MatchOptions & { - enc: Encoding; - codes: StatusCodePredicate; - schema: Schema; + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; }; export type ErrorMatcher = MatchOptions & { - enc: Encoding; - codes: StatusCodePredicate; - schema: Schema; - err: true; + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; + err: true; }; export type FailMatcher = { - enc: "fail"; - codes: StatusCodePredicate; + enc: "fail"; + codes: StatusCodePredicate; }; export type Matcher = ValueMatcher | ErrorMatcher | FailMatcher; export function jsonErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "json", codes, schema }; + return { ...options, err: true, enc: "json", codes, schema }; } export function json( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "json", codes, schema }; + return { ...options, enc: "json", codes, schema }; } export function textErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "text", codes, schema }; + return { ...options, err: true, enc: "text", codes, schema }; } export function text( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "text", codes, schema }; + return { ...options, enc: "text", codes, schema }; } export function bytesErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "bytes", codes, schema }; + return { ...options, err: true, enc: "bytes", codes, schema }; } export function bytes( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "bytes", codes, schema }; + return { ...options, enc: "bytes", codes, schema }; } export function streamErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "stream", codes, schema }; + return { ...options, err: true, enc: "stream", codes, schema }; } export function stream( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "stream", codes, schema }; + return { ...options, enc: "stream", codes, schema }; } export function sseErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "sse", codes, schema }; + return { ...options, err: true, enc: "sse", codes, schema }; } export function sse( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "sse", codes, schema }; + return { ...options, enc: "sse", codes, schema }; } export function nilErr( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ErrorMatcher { - return { ...options, err: true, enc: "nil", codes, schema }; + return { ...options, err: true, enc: "nil", codes, schema }; } export function nil( - codes: StatusCodePredicate, - schema: Schema, - options?: MatchOptions + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, ): ValueMatcher { - return { ...options, enc: "nil", codes, schema }; + return { ...options, enc: "nil", codes, schema }; } export function fail(codes: StatusCodePredicate): FailMatcher { - return { enc: "fail", codes }; + return { enc: "fail", codes }; } -export type MatchedValue = Matchers extends Matcher[] ? T : never; -export type MatchedError = Matchers extends Matcher[] ? E : never; +export type MatchedValue = Matchers extends Matcher[] + ? T + : never; +export type MatchedError = Matchers extends Matcher[] + ? E + : never; export type MatchFunc = ( - response: Response, - options?: { resultKey?: string; extraFields?: Record } + response: Response, + options?: { resultKey?: string; extraFields?: Record }, ) => Promise<[result: Result, raw: unknown]>; export function match( - ...matchers: Array> + ...matchers: Array> ): MatchFunc { - return async function matchFunc( - response: Response, - options?: { resultKey?: string; extraFields?: Record } - ): Promise<[result: Result, raw: unknown]> { - let raw: unknown; - let matcher: Matcher | undefined; - for (const match of matchers) { - const { codes } = match; - const ctpattern = "ctype" in match ? match.ctype : DEFAULT_CONTENT_TYPES[match.enc]; - if (ctpattern && matchResponse(response, codes, ctpattern)) { - matcher = match; - break; - } else if (!ctpattern && matchStatusCode(response, codes)) { - matcher = match; - break; - } - } + return async function matchFunc( + response: Response, + options?: { resultKey?: string; extraFields?: Record }, + ): Promise< + [result: Result, raw: unknown] + > { + let raw: unknown; + let matcher: Matcher | undefined; + for (const match of matchers) { + const { codes } = match; + const ctpattern = "ctype" in match + ? match.ctype + : DEFAULT_CONTENT_TYPES[match.enc]; + if (ctpattern && matchResponse(response, codes, ctpattern)) { + matcher = match; + break; + } else if (!ctpattern && matchStatusCode(response, codes)) { + matcher = match; + break; + } + } - if (!matcher) { - const responseBody = await response.text(); - return [ - { - ok: false, - error: new SDKError( - "Unexpected API response status or content-type", - response, - responseBody - ), - }, - responseBody, - ]; - } + if (!matcher) { + const responseBody = await response.text(); + return [{ + ok: false, + error: new SDKError( + "Unexpected API response status or content-type", + response, + responseBody, + ), + }, responseBody]; + } - const encoding = matcher.enc; - switch (encoding) { - case "json": - raw = await response.json(); - break; - case "bytes": - raw = await response.arrayBuffer(); - break; - case "stream": - raw = response.body; - break; - case "text": - raw = await response.text(); - break; - case "sse": - raw = response.body; - break; - case "nil": - raw = await discardResponseBody(response); - break; - case "fail": - raw = await response.text(); - break; - default: - encoding satisfies never; - throw new Error(`Unsupported response type: ${encoding}`); - } + const encoding = matcher.enc; + switch (encoding) { + case "json": + raw = await response.json(); + break; + case "bytes": + raw = await response.arrayBuffer(); + break; + case "stream": + raw = response.body; + break; + case "text": + raw = await response.text(); + break; + case "sse": + raw = response.body; + break; + case "nil": + raw = await discardResponseBody(response); + break; + case "fail": + raw = await response.text(); + break; + default: + encoding satisfies never; + throw new Error(`Unsupported response type: ${encoding}`); + } - if (matcher.enc === "fail") { - return [ - { - ok: false, - error: new SDKError( - "API error occurred", - response, - typeof raw === "string" ? raw : "" - ), - }, - raw, - ]; - } + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new SDKError( + "API error occurred", + response, + typeof raw === "string" ? raw : "", + ), + }, raw]; + } - const resultKey = matcher.key || options?.resultKey; - let data: unknown; + const resultKey = matcher.key || options?.resultKey; + let data: unknown; - if ("err" in matcher) { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - ...(isPlainObject(raw) ? raw : null), - }; - } else if (resultKey) { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - [resultKey]: raw, - }; - } else if (matcher.hdrs) { - data = { - ...options?.extraFields, - ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - ...(isPlainObject(raw) ? raw : null), - }; - } else { - data = raw; - } + if ("err" in matcher) { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(isPlainObject(raw) ? raw : null), + }; + } else if (resultKey) { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + [resultKey]: raw, + }; + } else if (matcher.hdrs) { + data = { + ...options?.extraFields, + ...(matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null), + ...(isPlainObject(raw) ? raw : null), + }; + } else { + data = raw; + } - if ("err" in matcher) { - const result = safeParse( - data, - (v: unknown) => matcher.schema.parse(v), - "Response validation failed" - ); - return [result.ok ? { ok: false, error: result.value } : result, raw]; - } else { - return [ - safeParse( - data, - (v: unknown) => matcher.schema.parse(v), - "Response validation failed" - ), - raw, - ]; - } - }; + if ("err" in matcher) { + const result = safeParse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + ); + return [result.ok ? { ok: false, error: result.value } : result, raw]; + } else { + return [ + safeParse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + ), + raw, + ]; + } + }; } const headerValRE = /, */; @@ -275,13 +289,13 @@ const headerValRE = /, */; * entries. Values are represented as an array to account for repeated headers. */ export function unpackHeaders(headers: Headers): Record { - const out: Record = {}; + const out: Record = {}; - for (const [k, v] of headers.entries()) { - out[k] = v.split(headerValRE); - } + for (const [k, v] of headers.entries()) { + out[k] = v.split(headerValRE); + } - return out; + return out; } /** @@ -291,18 +305,18 @@ export function unpackHeaders(headers: Headers): Record { * https://undici.nodejs.org/#/?id=garbage-collection */ export async function discardResponseBody(res: Response) { - const reader = res.body?.getReader(); - if (reader == null) { - return; - } + const reader = res.body?.getReader(); + if (reader == null) { + return; + } - try { - let done = false; - while (!done) { - const res = await reader.read(); - done = res.done; - } - } finally { - reader.releaseLock(); + try { + let done = false; + while (!done) { + const res = await reader.read(); + done = res.done; } + } finally { + reader.releaseLock(); + } } diff --git a/src/lib/schemas.ts b/src/lib/schemas.ts index 37b0b13..f3856dc 100644 --- a/src/lib/schemas.ts +++ b/src/lib/schemas.ts @@ -2,7 +2,14 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { output, ZodEffects, ZodError, ZodObject, ZodRawShape, ZodTypeAny } from "zod"; +import { + output, + ZodEffects, + ZodError, + ZodObject, + ZodRawShape, + ZodTypeAny, +} from "zod"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; import { ERR, OK, Result } from "../types/fp.js"; @@ -11,15 +18,19 @@ import { ERR, OK, Result } from "../types/fp.js"; * intercepts this error and converts it to an SDKValidationError so as to not * leak Zod implementation details to user code. */ -export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string): Out { - try { - return fn(rawValue); - } catch (err) { - if (err instanceof ZodError) { - throw new SDKValidationError(errorMessage, err, rawValue); - } - throw err; +export function parse( + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, +): Out { + try { + return fn(rawValue); + } catch (err) { + if (err instanceof ZodError) { + throw new SDKValidationError(errorMessage, err, rawValue); } + throw err; + } } /** @@ -28,47 +39,48 @@ export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMes * leak Zod implementation details to user code. */ export function safeParse( - rawValue: Inp, - fn: (value: Inp) => Out, - errorMessage: string + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, ): Result { - try { - return OK(fn(rawValue)); - } catch (err) { - return ERR(new SDKValidationError(errorMessage, err, rawValue)); - } + try { + return OK(fn(rawValue)); + } catch (err) { + return ERR(new SDKValidationError(errorMessage, err, rawValue)); + } } export function collectExtraKeys< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - K extends string + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + K extends string, >( - obj: ZodObject, - extrasKey: K + obj: ZodObject, + extrasKey: K, ): ZodEffects< - typeof obj, - output> & { - [k in K]: Record>; - } + typeof obj, + & output> + & { + [k in K]: Record>; + } > { - return obj.transform((val) => { - const extras: Record> = {}; - const { shape } = obj; - for (const [key] of Object.entries(val)) { - if (key in shape) { - continue; - } + return obj.transform((val) => { + const extras: Record> = {}; + const { shape } = obj; + for (const [key] of Object.entries(val)) { + if (key in shape) { + continue; + } - const v = val[key]; - if (typeof v === "undefined") { - continue; - } + const v = val[key]; + if (typeof v === "undefined") { + continue; + } - extras[key] = v; - delete val[key]; - } + extras[key] = v; + delete val[key]; + } - return { ...val, [extrasKey]: extras }; - }); + return { ...val, [extrasKey]: extras }; + }); } diff --git a/src/lib/sdks.ts b/src/lib/sdks.ts index 51b49bd..a0f4de1 100644 --- a/src/lib/sdks.ts +++ b/src/lib/sdks.ts @@ -2,356 +2,383 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { - HTTPClient, - matchContentType, - matchStatusCode, - isAbortError, - isTimeoutError, - isConnectionError, -} from "./http.js"; -import { SecurityState } from "./security.js"; -import { retry, RetryConfig } from "./retries.js"; -import { Logger } from "./logger.js"; -import { encodeForm } from "./encodings.js"; -import { stringToBase64 } from "./base64.js"; -import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js"; import { SDKHooks } from "../hooks/hooks.js"; import { HookContext } from "../hooks/types.js"; import { - ConnectionError, - InvalidRequestError, - RequestAbortedError, - RequestTimeoutError, - UnexpectedClientError, + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, } from "../models/errors/httpclienterrors.js"; import { ERR, OK, Result } from "../types/fp.js"; +import { stringToBase64 } from "./base64.js"; +import { SDK_METADATA, SDKOptions, serverURLFromOptions } from "./config.js"; +import { encodeForm } from "./encodings.js"; +import { + HTTPClient, + isAbortError, + isConnectionError, + isTimeoutError, + matchContentType, + matchStatusCode, +} from "./http.js"; +import { Logger } from "./logger.js"; +import { retry, RetryConfig } from "./retries.js"; +import { SecurityState } from "./security.js"; export type RequestOptions = { - /** - * Sets a timeout, in milliseconds, on HTTP requests made by an SDK method. If - * `fetchOptions.signal` is set then it will take precedence over this option. - */ - timeoutMs?: number; - /** - * Set or override a retry policy on HTTP calls. - */ - retries?: RetryConfig; - /** - * Specifies the status codes which should be retried using the given retry policy. - */ - retryCodes?: string[]; - /** - * Sets various request options on the `fetch` call made by an SDK method. - * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} - */ - fetchOptions?: Omit; + /** + * Sets a timeout, in milliseconds, on HTTP requests made by an SDK method. If + * `fetchOptions.signal` is set then it will take precedence over this option. + */ + timeoutMs?: number; + /** + * Set or override a retry policy on HTTP calls. + */ + retries?: RetryConfig; + /** + * Specifies the status codes which should be retried using the given retry policy. + */ + retryCodes?: string[]; + /** + * Sets various request options on the `fetch` call made by an SDK method. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} + */ + fetchOptions?: Omit; }; type RequestConfig = { - method: string; - path: string; - baseURL?: string | URL; - query?: string; - body?: RequestInit["body"]; - headers?: HeadersInit; - security?: SecurityState | null; - uaHeader?: string; - timeoutMs?: number; + method: string; + path: string; + baseURL?: string | URL; + query?: string; + body?: RequestInit["body"]; + headers?: HeadersInit; + security?: SecurityState | null; + uaHeader?: string; + timeoutMs?: number; }; const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; -const webWorkerLike = - typeof gt === "object" && - gt != null && - "importScripts" in gt && - typeof gt["importScripts"] === "function"; -const isBrowserLike = - webWorkerLike || - (typeof navigator !== "undefined" && "serviceWorker" in navigator) || - (typeof window === "object" && typeof window.document !== "undefined"); +const webWorkerLike = typeof gt === "object" + && gt != null + && "importScripts" in gt + && typeof gt["importScripts"] === "function"; +const isBrowserLike = webWorkerLike + || (typeof navigator !== "undefined" && "serviceWorker" in navigator) + || (typeof window === "object" && typeof window.document !== "undefined"); export class ClientSDK { - private readonly httpClient: HTTPClient; - protected readonly baseURL: URL | null; - protected readonly hooks$: SDKHooks; - protected readonly logger?: Logger | undefined; - public readonly options$: SDKOptions & { hooks?: SDKHooks }; - - constructor(options: SDKOptions = {}) { - const opt = options as unknown; - if ( - typeof opt === "object" && - opt != null && - "hooks" in opt && - opt.hooks instanceof SDKHooks - ) { - this.hooks$ = opt.hooks; - } else { - this.hooks$ = new SDKHooks(); - } - this.options$ = { ...options, hooks: this.hooks$ }; - - const url = serverURLFromOptions(options); - if (url) { - url.pathname = url.pathname.replace(/\/+$/, "") + "/"; - } - const { baseURL, client } = this.hooks$.sdkInit({ - baseURL: url, - client: options.httpClient || new HTTPClient(), - }); - this.baseURL = baseURL; - this.httpClient = client; - this.logger = options.debugLogger; + readonly #httpClient: HTTPClient; + readonly #hooks: SDKHooks; + readonly #logger?: Logger | undefined; + protected readonly _baseURL: URL | null; + public readonly _options: SDKOptions & { hooks?: SDKHooks }; + + constructor(options: SDKOptions = {}) { + const opt = options as unknown; + if ( + typeof opt === "object" + && opt != null + && "hooks" in opt + && opt.hooks instanceof SDKHooks + ) { + this.#hooks = opt.hooks; + } else { + this.#hooks = new SDKHooks(); } + this._options = { ...options, hooks: this.#hooks }; - public createRequest$( - context: HookContext, - conf: RequestConfig, - options?: RequestOptions - ): Result { - const { method, path, query, headers: opHeaders, security } = conf; - - const base = conf.baseURL ?? this.baseURL; - if (!base) { - return ERR(new InvalidRequestError("No base URL provided for operation")); - } - const reqURL = new URL(base); - const inputURL = new URL(path, reqURL); - - if (path) { - reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); - } - - let finalQuery = query || ""; + const url = serverURLFromOptions(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + const { baseURL, client } = this.#hooks.sdkInit({ + baseURL: url, + client: options.httpClient || new HTTPClient(), + }); + this._baseURL = baseURL; + this.#httpClient = client; + this.#logger = options.debugLogger; + } + + public _createRequest( + context: HookContext, + conf: RequestConfig, + options?: RequestOptions, + ): Result { + const { method, path, query, headers: opHeaders, security } = conf; + + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return ERR(new InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path, reqURL); - const secQuery: string[] = []; - for (const [k, v] of Object.entries(security?.queryParams || {})) { - secQuery.push(encodeForm(k, v, { charEncoding: "percent" })); - } - if (secQuery.length) { - finalQuery += `&${secQuery.join("&")}`; - } + if (path) { + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } - if (finalQuery) { - const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; - reqURL.search = `?${q}`; - } + let finalQuery = query || ""; - const headers = new Headers(opHeaders); + const secQuery: string[] = []; + for (const [k, v] of Object.entries(security?.queryParams || {})) { + secQuery.push(encodeForm(k, v, { charEncoding: "percent" })); + } + if (secQuery.length) { + finalQuery += `&${secQuery.join("&")}`; + } - const username = security?.basic.username; - const password = security?.basic.password; - if (username != null || password != null) { - const encoded = stringToBase64([username || "", password || ""].join(":")); - headers.set("Authorization", `Basic ${encoded}`); - } + if (finalQuery) { + const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q}`; + } - const securityHeaders = new Headers(security?.headers || {}); - for (const [k, v] of securityHeaders) { - headers.set(k, v); - } + const headers = new Headers(opHeaders); - let cookie = headers.get("cookie") || ""; - for (const [k, v] of Object.entries(security?.cookies || {})) { - cookie += `; ${k}=${v}`; - } - cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; - headers.set("cookie", cookie); + const username = security?.basic.username; + const password = security?.basic.password; + if (username != null || password != null) { + const encoded = stringToBase64( + [username || "", password || ""].join(":"), + ); + headers.set("Authorization", `Basic ${encoded}`); + } - const userHeaders = new Headers(options?.fetchOptions?.headers); - for (const [k, v] of userHeaders) { - headers.set(k, v); - } + const securityHeaders = new Headers(security?.headers || {}); + for (const [k, v] of securityHeaders) { + headers.set(k, v); + } - // Only set user agent header in non-browser-like environments since CORS - // policy disallows setting it in browsers e.g. Chrome throws an error. - if (!isBrowserLike) { - headers.set(conf.uaHeader ?? "user-agent", SDK_METADATA.userAgent); - } + let cookie = headers.get("cookie") || ""; + for (const [k, v] of Object.entries(security?.cookies || {})) { + cookie += `; ${k}=${v}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); - let fetchOptions = options?.fetchOptions; - if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { - const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); - if (!fetchOptions) { - fetchOptions = { signal: timeoutSignal }; - } else { - fetchOptions.signal = timeoutSignal; - } - } + const userHeaders = new Headers(options?.fetchOptions?.headers); + for (const [k, v] of userHeaders) { + headers.set(k, v); + } - let input; - try { - input = this.hooks$.beforeCreateRequest(context, { - url: reqURL, - options: { - ...fetchOptions, - body: conf.body ?? null, - headers, - method, - }, - }); - } catch (err: unknown) { - return ERR( - new UnexpectedClientError("Create request hook failed to execute", { cause: err }) - ); - } + // Only set user agent header in non-browser-like environments since CORS + // policy disallows setting it in browsers e.g. Chrome throws an error. + if (!isBrowserLike) { + headers.set(conf.uaHeader ?? "user-agent", SDK_METADATA.userAgent); + } - return OK(new Request(input.url, input.options)); + let fetchOptions = options?.fetchOptions; + if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { + const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); + if (!fetchOptions) { + fetchOptions = { signal: timeoutSignal }; + } else { + fetchOptions.signal = timeoutSignal; + } } - public async do$( - request: Request, - options: { - context: HookContext; - errorCodes: number | string | (number | string)[]; - retryConfig?: RetryConfig | undefined; - retryCodes?: string[] | undefined; - } - ): Promise< - Result< - Response, - RequestAbortedError | RequestTimeoutError | ConnectionError | UnexpectedClientError - > - > { - const { context, errorCodes } = options; - const retryConfig = options.retryConfig || { strategy: "none" }; - const retryCodes = options.retryCodes || []; - - return retry( - async () => { - const req = await this.hooks$.beforeRequest(context, request.clone()); - await logRequest(this.logger, req).catch((e) => - this.logger?.log("Failed to log request:", e) - ); - - let response = await this.httpClient.request(req); - - if (matchStatusCode(response, errorCodes)) { - const result = await this.hooks$.afterError(context, response, null); - if (result.error) { - throw result.error; - } - response = result.response || response; - } else { - response = await this.hooks$.afterSuccess(context, response); - } - - await logResponse(this.logger, response, req).catch((e) => - this.logger?.log("Failed to log response:", e) - ); - - return response; - }, - { config: retryConfig, statusCodes: retryCodes } - ).then( - (r) => OK(r), - (err) => { - switch (true) { - case isAbortError(err): - return ERR( - new RequestAbortedError("Request aborted by client", { cause: err }) - ); - case isTimeoutError(err): - return ERR(new RequestTimeoutError("Request timed out", { cause: err })); - case isConnectionError(err): - return ERR(new ConnectionError("Unable to make request", { cause: err })); - default: - return ERR( - new UnexpectedClientError("Unexpected HTTP client error", { - cause: err, - }) - ); - } - } - ); + if (conf.body instanceof ReadableStream) { + if (!fetchOptions) { + fetchOptions = { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + duplex: "half", + }; + } else { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + fetchOptions.duplex = "half"; + } } -} -const jsonLikeContentTypeRE = /^application\/(?:.{0,100}\+)?json/; -async function logRequest(logger: Logger | undefined, req: Request) { - if (!logger) { - return; + let input; + try { + input = this.#hooks.beforeCreateRequest(context, { + url: reqURL, + options: { + ...fetchOptions, + body: conf.body ?? null, + headers, + method, + }, + }); + } catch (err: unknown) { + return ERR( + new UnexpectedClientError("Create request hook failed to execute", { + cause: err, + }), + ); } - const contentType = req.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; + return OK(new Request(input.url, input.options)); + } + + public async _do( + request: Request, + options: { + context: HookContext; + errorCodes: number | string | (number | string)[]; + retryConfig?: RetryConfig | undefined; + retryCodes?: string[] | undefined; + }, + ): Promise< + Result< + Response, + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + | UnexpectedClientError + > + > { + const { context, errorCodes } = options; + const retryConfig = options.retryConfig || { strategy: "none" }; + const retryCodes = options.retryCodes || []; + + return retry( + async () => { + const req = await this.#hooks.beforeRequest(context, request.clone()); + await logRequest(this.#logger, req).catch((e) => + this.#logger?.log("Failed to log request:", e) + ); - logger.group(`> Request: ${req.method} ${req.url}`); + let response = await this.#httpClient.request(req); - logger.group("Headers:"); - for (const [k, v] of req.headers.entries()) { - logger.log(`${k}: ${v}`); - } - logger.groupEnd(); - - logger.group("Body:"); - switch (true) { - case jsonLikeContentTypeRE.test(ct): - logger.log(await req.clone().json()); - break; - case ct.startsWith("text/"): - logger.log(await req.clone().text()); - break; - case ct === "multipart/form-data": { - const body = await req.clone().formData(); - for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; - logger.log(`${k}: ${vlabel}`); - } - break; + if (matchStatusCode(response, errorCodes)) { + const result = await this.#hooks.afterError(context, response, null); + if (result.error) { + throw result.error; + } + response = result.response || response; + } else { + response = await this.#hooks.afterSuccess(context, response); } - default: - logger.log(`<${contentType}>`); - break; - } - logger.groupEnd(); - logger.groupEnd(); + await logResponse(this.#logger, response, req) + .catch(e => this.#logger?.log("Failed to log response:", e)); + + return response; + }, + { config: retryConfig, statusCodes: retryCodes }, + ).then( + (r) => OK(r), + (err) => { + switch (true) { + case isAbortError(err): + return ERR( + new RequestAbortedError("Request aborted by client", { + cause: err, + }), + ); + case isTimeoutError(err): + return ERR( + new RequestTimeoutError("Request timed out", { cause: err }), + ); + case isConnectionError(err): + return ERR( + new ConnectionError("Unable to make request", { cause: err }), + ); + default: + return ERR( + new UnexpectedClientError("Unexpected HTTP client error", { + cause: err, + }), + ); + } + }, + ); + } } -async function logResponse(logger: Logger | undefined, res: Response, req: Request) { - if (!logger) { - return; +const jsonLikeContentTypeRE = /^application\/(?:.{0,100}\+)?json/; +async function logRequest(logger: Logger | undefined, req: Request) { + if (!logger) { + return; + } + + const contentType = req.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + + logger.group(`> Request: ${req.method} ${req.url}`); + + logger.group("Headers:"); + for (const [k, v] of req.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; } + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); - const contentType = res.headers.get("content-type"); - const ct = contentType?.split(";")[0] || ""; - - logger.group(`< Response: ${req.method} ${req.url}`); - logger.log("Status Code:", res.status, res.statusText); + logger.groupEnd(); +} - logger.group("Headers:"); - for (const [k, v] of res.headers.entries()) { - logger.log(`${k}: ${v}`); - } - logger.groupEnd(); - - logger.group("Body:"); - switch (true) { - case matchContentType(res, "application/json") || jsonLikeContentTypeRE.test(ct): - logger.log(await res.clone().json()); - break; - case matchContentType(res, "text/event-stream"): - logger.log(`<${contentType}>`); - break; - case matchContentType(res, "text/*"): - logger.log(await res.clone().text()); - break; - case matchContentType(res, "multipart/form-data"): { - const body = await res.clone().formData(); - for (const [k, v] of body) { - const vlabel = v instanceof Blob ? "" : v; - logger.log(`${k}: ${vlabel}`); - } - break; - } - default: - logger.log(`<${contentType}>`); - break; +async function logResponse( + logger: Logger | undefined, + res: Response, + req: Request, +) { + if (!logger) { + return; + } + + const contentType = res.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + + logger.group(`< Response: ${req.method} ${req.url}`); + logger.log("Status Code:", res.status, res.statusText); + + logger.group("Headers:"); + for (const [k, v] of res.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case matchContentType(res, "application/json") + || jsonLikeContentTypeRE.test(ct): + logger.log(await res.clone().json()); + break; + case matchContentType(res, "text/event-stream"): + logger.log(`<${contentType}>`); + break; + case matchContentType(res, "text/*"): + logger.log(await res.clone().text()); + break; + case matchContentType(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; } - logger.groupEnd(); + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); - logger.groupEnd(); + logger.groupEnd(); } diff --git a/src/lib/security.ts b/src/lib/security.ts index 908e41b..21f601f 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -5,188 +5,213 @@ import * as components from "../models/components/index.js"; export enum SecurityErrorCode { - Incomplete = "incomplete", - UnrecognisedSecurityType = "unrecognized_security_type", + Incomplete = "incomplete", + UnrecognisedSecurityType = "unrecognized_security_type", } export class SecurityError extends Error { - constructor(public code: SecurityErrorCode, message: string) { - super(message); - this.name = "SecurityError"; - } - - static incomplete(): SecurityError { - return new SecurityError( - SecurityErrorCode.Incomplete, - "Security requirements not met in order to perform the operation" - ); - } - static unrecognizedType(type: string): SecurityError { - return new SecurityError( - SecurityErrorCode.UnrecognisedSecurityType, - `Unrecognised security type: ${type}` - ); - } + constructor( + public code: SecurityErrorCode, + message: string, + ) { + super(message); + this.name = "SecurityError"; + } + + static incomplete(): SecurityError { + return new SecurityError( + SecurityErrorCode.Incomplete, + "Security requirements not met in order to perform the operation", + ); + } + static unrecognizedType(type: string): SecurityError { + return new SecurityError( + SecurityErrorCode.UnrecognisedSecurityType, + `Unrecognised security type: ${type}`, + ); + } } export type SecurityState = { - basic: { username?: string | undefined; password?: string | undefined }; - headers: Record; - queryParams: Record; - cookies: Record; + basic: { username?: string | undefined; password?: string | undefined }; + headers: Record; + queryParams: Record; + cookies: Record; }; type SecurityInputBasic = { - type: "http:basic"; - value: { username?: string | undefined; password?: string | undefined } | null | undefined; + type: "http:basic"; + value: + | { username?: string | undefined; password?: string | undefined } + | null + | undefined; }; type SecurityInputBearer = { - type: "http:bearer"; - value: string | null | undefined; - fieldName: string; + type: "http:bearer"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputAPIKey = { - type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; - value: string | null | undefined; - fieldName: string; + type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOIDC = { - type: "openIdConnect"; - value: string | null | undefined; - fieldName: string; + type: "openIdConnect"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2 = { - type: "oauth2"; - value: string | null | undefined; - fieldName: string; + type: "oauth2"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2ClientCredentials = { - type: "oauth2:client_credentials"; - value: string | null | undefined; - fieldName: string; + type: "oauth2:client_credentials"; + value: string | null | undefined; + fieldName: string; +}; + +type SecurityInputCustom = { + type: "http:custom"; + value: any | null | undefined; + fieldName: string; }; export type SecurityInput = - | SecurityInputBasic - | SecurityInputBearer - | SecurityInputAPIKey - | SecurityInputOAuth2 - | SecurityInputOAuth2ClientCredentials - | SecurityInputOIDC; - -export function resolveSecurity(...options: SecurityInput[][]): SecurityState | null { - const state: SecurityState = { - basic: { username: "", password: "" }, - headers: {}, - queryParams: {}, - cookies: {}, - }; - - const option = options.find((opts) => { - return opts.every((o) => { - if (o.value == null) { - return false; - } else if (o.type === "http:basic") { - return o.value.username != null || o.value.password != null; - } else if (typeof o.value === "string") { - return !!o.value; - } else { - throw new Error( - `Unrecognized security type: ${o.type} (value type: ${typeof o.value})` - ); - } - }); - }); - if (option == null) { + | SecurityInputBasic + | SecurityInputBearer + | SecurityInputAPIKey + | SecurityInputOAuth2 + | SecurityInputOAuth2ClientCredentials + | SecurityInputOIDC + | SecurityInputCustom; + +export function resolveSecurity( + ...options: SecurityInput[][] +): SecurityState | null { + const state: SecurityState = { + basic: { username: "", password: "" }, + headers: {}, + queryParams: {}, + cookies: {}, + }; + + const option = options.find((opts) => { + return opts.every((o) => { + if (o.value == null) { + return false; + } else if (o.type === "http:basic") { + return o.value.username != null || o.value.password != null; + } else if (o.type === "http:custom") { return null; + } else if (typeof o.value === "string") { + return !!o.value; + } else { + throw new Error( + `Unrecognized security type: ${o.type} (value type: ${typeof o + .value})`, + ); + } + }); + }); + if (option == null) { + return null; + } + + option.forEach((spec) => { + if (spec.value == null) { + return; } - option.forEach((spec) => { - if (spec.value == null) { - return; - } - - const { type } = spec; - - switch (type) { - case "apiKey:header": - state.headers[spec.fieldName] = spec.value; - break; - case "apiKey:query": - state.queryParams[spec.fieldName] = spec.value; - break; - case "apiKey:cookie": - state.cookies[spec.fieldName] = spec.value; - break; - case "http:basic": - applyBasic(state, spec); - break; - case "http:bearer": - applyBearer(state, spec); - break; - case "oauth2": - applyBearer(state, spec); - break; - case "oauth2:client_credentials": - break; - case "openIdConnect": - applyBearer(state, spec); - break; - default: - spec satisfies never; - throw SecurityError.unrecognizedType(type); - } - }); + const { type } = spec; + + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + spec satisfies never; + throw SecurityError.unrecognizedType(type); + } + }); - return state; + return state; } -function applyBasic(state: SecurityState, spec: SecurityInputBasic) { - if (spec.value == null) { - return; - } +function applyBasic( + state: SecurityState, + spec: SecurityInputBasic, +) { + if (spec.value == null) { + return; + } - state.basic = spec.value; + state.basic = spec.value; } function applyBearer( - state: SecurityState, - spec: SecurityInputBearer | SecurityInputOAuth2 | SecurityInputOIDC + state: SecurityState, + spec: SecurityInputBearer | SecurityInputOAuth2 | SecurityInputOIDC, ) { - if (spec.value == null) { - return; - } + if (spec.value == null) { + return; + } - let value = spec.value; - if (value.slice(0, 7).toLowerCase() !== "bearer ") { - value = `Bearer ${value}`; - } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } - state.headers[spec.fieldName] = value; + state.headers[spec.fieldName] = value; } export function resolveGlobalSecurity( - security: Partial | null | undefined + security: Partial | null | undefined, ): SecurityState | null { - return resolveSecurity([ - { - fieldName: "api_key", - type: "apiKey:header", - value: security?.apiKey, - }, - ]); + return resolveSecurity( + [ + { + fieldName: "api_key", + type: "apiKey:header", + value: security?.apiKey, + }, + ], + ); } -export async function extractSecurity>( - sec: T | (() => Promise) | undefined -): Promise { - if (sec == null) { - return; - } +export async function extractSecurity< + T extends string | Record, +>(sec: T | (() => Promise) | undefined): Promise { + if (sec == null) { + return; + } - return typeof sec === "function" ? sec() : sec; + return typeof sec === "function" ? sec() : sec; } diff --git a/src/models/components/apiresponse.ts b/src/models/components/apiresponse.ts index f30a2b2..5301b8c 100644 --- a/src/models/components/apiresponse.ts +++ b/src/models/components/apiresponse.ts @@ -5,34 +5,38 @@ import * as z from "zod"; export type ApiResponse = { - code?: number | undefined; - type?: string | undefined; - message?: string | undefined; + code?: number | undefined; + type?: string | undefined; + message?: string | undefined; }; /** @internal */ -export const ApiResponse$inboundSchema: z.ZodType = z.object({ - code: z.number().int().optional(), - type: z.string().optional(), - message: z.string().optional(), +export const ApiResponse$inboundSchema: z.ZodType< + ApiResponse, + z.ZodTypeDef, + unknown +> = z.object({ + code: z.number().int().optional(), + type: z.string().optional(), + message: z.string().optional(), }); /** @internal */ export type ApiResponse$Outbound = { - code?: number | undefined; - type?: string | undefined; - message?: string | undefined; + code?: number | undefined; + type?: string | undefined; + message?: string | undefined; }; /** @internal */ export const ApiResponse$outboundSchema: z.ZodType< - ApiResponse$Outbound, - z.ZodTypeDef, - ApiResponse + ApiResponse$Outbound, + z.ZodTypeDef, + ApiResponse > = z.object({ - code: z.number().int().optional(), - type: z.string().optional(), - message: z.string().optional(), + code: z.number().int().optional(), + type: z.string().optional(), + message: z.string().optional(), }); /** @@ -40,10 +44,10 @@ export const ApiResponse$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ApiResponse$ { - /** @deprecated use `ApiResponse$inboundSchema` instead. */ - export const inboundSchema = ApiResponse$inboundSchema; - /** @deprecated use `ApiResponse$outboundSchema` instead. */ - export const outboundSchema = ApiResponse$outboundSchema; - /** @deprecated use `ApiResponse$Outbound` instead. */ - export type Outbound = ApiResponse$Outbound; + /** @deprecated use `ApiResponse$inboundSchema` instead. */ + export const inboundSchema = ApiResponse$inboundSchema; + /** @deprecated use `ApiResponse$outboundSchema` instead. */ + export const outboundSchema = ApiResponse$outboundSchema; + /** @deprecated use `ApiResponse$Outbound` instead. */ + export type Outbound = ApiResponse$Outbound; } diff --git a/src/models/components/category.ts b/src/models/components/category.ts index bac3d16..6b941f3 100644 --- a/src/models/components/category.ts +++ b/src/models/components/category.ts @@ -5,38 +5,45 @@ import * as z from "zod"; export type Category = { - id?: number | undefined; - name?: string | undefined; + id?: number | undefined; + name?: string | undefined; }; /** @internal */ -export const Category$inboundSchema: z.ZodType = z.object({ - id: z.number().int().optional(), - name: z.string().optional(), +export const Category$inboundSchema: z.ZodType< + Category, + z.ZodTypeDef, + unknown +> = z.object({ + id: z.number().int().optional(), + name: z.string().optional(), }); /** @internal */ export type Category$Outbound = { - id?: number | undefined; - name?: string | undefined; + id?: number | undefined; + name?: string | undefined; }; /** @internal */ -export const Category$outboundSchema: z.ZodType = - z.object({ - id: z.number().int().optional(), - name: z.string().optional(), - }); +export const Category$outboundSchema: z.ZodType< + Category$Outbound, + z.ZodTypeDef, + Category +> = z.object({ + id: z.number().int().optional(), + name: z.string().optional(), +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Category$ { - /** @deprecated use `Category$inboundSchema` instead. */ - export const inboundSchema = Category$inboundSchema; - /** @deprecated use `Category$outboundSchema` instead. */ - export const outboundSchema = Category$outboundSchema; - /** @deprecated use `Category$Outbound` instead. */ - export type Outbound = Category$Outbound; + /** @deprecated use `Category$inboundSchema` instead. */ + export const inboundSchema = Category$inboundSchema; + /** @deprecated use `Category$outboundSchema` instead. */ + export const outboundSchema = Category$outboundSchema; + /** @deprecated use `Category$Outbound` instead. */ + export type Outbound = Category$Outbound; } diff --git a/src/models/components/order.ts b/src/models/components/order.ts index f7e124c..28c6912 100644 --- a/src/models/components/order.ts +++ b/src/models/components/order.ts @@ -2,16 +2,16 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { ClosedEnum } from "../../types/enums.js"; import * as z from "zod"; +import { ClosedEnum } from "../../types/enums.js"; /** * Order Status */ export const OrderStatus = { - Placed: "placed", - Approved: "approved", - Delivered: "delivered", + Placed: "placed", + Approved: "approved", + Delivered: "delivered", } as const; /** * Order Status @@ -19,71 +19,70 @@ export const OrderStatus = { export type OrderStatus = ClosedEnum; export type Order = { - id?: number | undefined; - petId?: number | undefined; - quantity?: number | undefined; - shipDate?: Date | undefined; - /** - * Order Status - */ - status?: OrderStatus | undefined; - complete?: boolean | undefined; + id?: number | undefined; + petId?: number | undefined; + quantity?: number | undefined; + shipDate?: Date | undefined; + /** + * Order Status + */ + status?: OrderStatus | undefined; + complete?: boolean | undefined; }; /** @internal */ -export const OrderStatus$inboundSchema: z.ZodNativeEnum = - z.nativeEnum(OrderStatus); +export const OrderStatus$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(OrderStatus); /** @internal */ export const OrderStatus$outboundSchema: z.ZodNativeEnum = - OrderStatus$inboundSchema; + OrderStatus$inboundSchema; /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace OrderStatus$ { - /** @deprecated use `OrderStatus$inboundSchema` instead. */ - export const inboundSchema = OrderStatus$inboundSchema; - /** @deprecated use `OrderStatus$outboundSchema` instead. */ - export const outboundSchema = OrderStatus$outboundSchema; + /** @deprecated use `OrderStatus$inboundSchema` instead. */ + export const inboundSchema = OrderStatus$inboundSchema; + /** @deprecated use `OrderStatus$outboundSchema` instead. */ + export const outboundSchema = OrderStatus$outboundSchema; } /** @internal */ -export const Order$inboundSchema: z.ZodType = z.object({ +export const Order$inboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), petId: z.number().int().optional(), quantity: z.number().int().optional(), - shipDate: z - .string() - .datetime({ offset: true }) - .transform((v) => new Date(v)) - .optional(), + shipDate: z.string().datetime({ offset: true }).transform(v => new Date(v)) + .optional(), status: OrderStatus$inboundSchema.optional(), complete: z.boolean().optional(), -}); + }); /** @internal */ export type Order$Outbound = { - id?: number | undefined; - petId?: number | undefined; - quantity?: number | undefined; - shipDate?: string | undefined; - status?: string | undefined; - complete?: boolean | undefined; + id?: number | undefined; + petId?: number | undefined; + quantity?: number | undefined; + shipDate?: string | undefined; + status?: string | undefined; + complete?: boolean | undefined; }; /** @internal */ -export const Order$outboundSchema: z.ZodType = z.object({ - id: z.number().int().optional(), - petId: z.number().int().optional(), - quantity: z.number().int().optional(), - shipDate: z - .date() - .transform((v) => v.toISOString()) - .optional(), - status: OrderStatus$outboundSchema.optional(), - complete: z.boolean().optional(), +export const Order$outboundSchema: z.ZodType< + Order$Outbound, + z.ZodTypeDef, + Order +> = z.object({ + id: z.number().int().optional(), + petId: z.number().int().optional(), + quantity: z.number().int().optional(), + shipDate: z.date().transform(v => v.toISOString()).optional(), + status: OrderStatus$outboundSchema.optional(), + complete: z.boolean().optional(), }); /** @@ -91,10 +90,10 @@ export const Order$outboundSchema: z.ZodType; export type Pet = { - id?: number | undefined; - name: string; - category?: Category | undefined; - photoUrls: Array; - tags?: Array | undefined; - /** - * pet status in the store - */ - status?: Status | undefined; + id?: number | undefined; + name: string; + category?: Category | undefined; + photoUrls: Array; + tags?: Array | undefined; + /** + * pet status in the store + */ + status?: Status | undefined; }; /** @internal */ -export const Status$inboundSchema: z.ZodNativeEnum = z.nativeEnum(Status); +export const Status$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(Status); /** @internal */ -export const Status$outboundSchema: z.ZodNativeEnum = Status$inboundSchema; +export const Status$outboundSchema: z.ZodNativeEnum = + Status$inboundSchema; /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Status$ { - /** @deprecated use `Status$inboundSchema` instead. */ - export const inboundSchema = Status$inboundSchema; - /** @deprecated use `Status$outboundSchema` instead. */ - export const outboundSchema = Status$outboundSchema; + /** @deprecated use `Status$inboundSchema` instead. */ + export const inboundSchema = Status$inboundSchema; + /** @deprecated use `Status$outboundSchema` instead. */ + export const outboundSchema = Status$outboundSchema; } /** @internal */ -export const Pet$inboundSchema: z.ZodType = z.object({ +export const Pet$inboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), name: z.string(), category: Category$inboundSchema.optional(), photoUrls: z.array(z.string()), tags: z.array(Tag$inboundSchema).optional(), status: Status$inboundSchema.optional(), -}); + }); /** @internal */ export type Pet$Outbound = { - id?: number | undefined; - name: string; - category?: Category$Outbound | undefined; - photoUrls: Array; - tags?: Array | undefined; - status?: string | undefined; + id?: number | undefined; + name: string; + category?: Category$Outbound | undefined; + photoUrls: Array; + tags?: Array | undefined; + status?: string | undefined; }; /** @internal */ -export const Pet$outboundSchema: z.ZodType = z.object({ +export const Pet$outboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), name: z.string(), category: Category$outboundSchema.optional(), photoUrls: z.array(z.string()), tags: z.array(Tag$outboundSchema).optional(), status: Status$outboundSchema.optional(), -}); + }); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Pet$ { - /** @deprecated use `Pet$inboundSchema` instead. */ - export const inboundSchema = Pet$inboundSchema; - /** @deprecated use `Pet$outboundSchema` instead. */ - export const outboundSchema = Pet$outboundSchema; - /** @deprecated use `Pet$Outbound` instead. */ - export type Outbound = Pet$Outbound; + /** @deprecated use `Pet$inboundSchema` instead. */ + export const inboundSchema = Pet$inboundSchema; + /** @deprecated use `Pet$outboundSchema` instead. */ + export const outboundSchema = Pet$outboundSchema; + /** @deprecated use `Pet$Outbound` instead. */ + export type Outbound = Pet$Outbound; } diff --git a/src/models/components/security.ts b/src/models/components/security.ts index 6890210..35f7a37 100644 --- a/src/models/components/security.ts +++ b/src/models/components/security.ts @@ -2,49 +2,53 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { remap as remap$ } from "../../lib/primitives.js"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; export type Security = { - apiKey: string; + apiKey: string; }; /** @internal */ -export const Security$inboundSchema: z.ZodType = z - .object({ - api_key: z.string(), - }) - .transform((v) => { - return remap$(v, { - api_key: "apiKey", - }); - }); +export const Security$inboundSchema: z.ZodType< + Security, + z.ZodTypeDef, + unknown +> = z.object({ + api_key: z.string(), +}).transform((v) => { + return remap$(v, { + "api_key": "apiKey", + }); +}); /** @internal */ export type Security$Outbound = { - api_key: string; + api_key: string; }; /** @internal */ -export const Security$outboundSchema: z.ZodType = z - .object({ - apiKey: z.string(), - }) - .transform((v) => { - return remap$(v, { - apiKey: "api_key", - }); - }); +export const Security$outboundSchema: z.ZodType< + Security$Outbound, + z.ZodTypeDef, + Security +> = z.object({ + apiKey: z.string(), +}).transform((v) => { + return remap$(v, { + apiKey: "api_key", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Security$ { - /** @deprecated use `Security$inboundSchema` instead. */ - export const inboundSchema = Security$inboundSchema; - /** @deprecated use `Security$outboundSchema` instead. */ - export const outboundSchema = Security$outboundSchema; - /** @deprecated use `Security$Outbound` instead. */ - export type Outbound = Security$Outbound; + /** @deprecated use `Security$inboundSchema` instead. */ + export const inboundSchema = Security$inboundSchema; + /** @deprecated use `Security$outboundSchema` instead. */ + export const outboundSchema = Security$outboundSchema; + /** @deprecated use `Security$Outbound` instead. */ + export type Outbound = Security$Outbound; } diff --git a/src/models/components/tag.ts b/src/models/components/tag.ts index c69b6e9..c0c166e 100644 --- a/src/models/components/tag.ts +++ b/src/models/components/tag.ts @@ -5,37 +5,39 @@ import * as z from "zod"; export type Tag = { - id?: number | undefined; - name?: string | undefined; + id?: number | undefined; + name?: string | undefined; }; /** @internal */ -export const Tag$inboundSchema: z.ZodType = z.object({ +export const Tag$inboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), name: z.string().optional(), -}); + }); /** @internal */ export type Tag$Outbound = { - id?: number | undefined; - name?: string | undefined; + id?: number | undefined; + name?: string | undefined; }; /** @internal */ -export const Tag$outboundSchema: z.ZodType = z.object({ +export const Tag$outboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), name: z.string().optional(), -}); + }); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Tag$ { - /** @deprecated use `Tag$inboundSchema` instead. */ - export const inboundSchema = Tag$inboundSchema; - /** @deprecated use `Tag$outboundSchema` instead. */ - export const outboundSchema = Tag$outboundSchema; - /** @deprecated use `Tag$Outbound` instead. */ - export type Outbound = Tag$Outbound; + /** @deprecated use `Tag$inboundSchema` instead. */ + export const inboundSchema = Tag$inboundSchema; + /** @deprecated use `Tag$outboundSchema` instead. */ + export const outboundSchema = Tag$outboundSchema; + /** @deprecated use `Tag$Outbound` instead. */ + export type Outbound = Tag$Outbound; } diff --git a/src/models/components/user.ts b/src/models/components/user.ts index 83772e7..48d6ffb 100644 --- a/src/models/components/user.ts +++ b/src/models/components/user.ts @@ -5,21 +5,22 @@ import * as z from "zod"; export type User = { - id?: number | undefined; - username?: string | undefined; - firstName?: string | undefined; - lastName?: string | undefined; - email?: string | undefined; - password?: string | undefined; - phone?: string | undefined; - /** - * User Status - */ - userStatus?: number | undefined; + id?: number | undefined; + username?: string | undefined; + firstName?: string | undefined; + lastName?: string | undefined; + email?: string | undefined; + password?: string | undefined; + phone?: string | undefined; + /** + * User Status + */ + userStatus?: number | undefined; }; /** @internal */ -export const User$inboundSchema: z.ZodType = z.object({ +export const User$inboundSchema: z.ZodType = z + .object({ id: z.number().int().optional(), username: z.string().optional(), firstName: z.string().optional(), @@ -28,22 +29,23 @@ export const User$inboundSchema: z.ZodType = z.obje password: z.string().optional(), phone: z.string().optional(), userStatus: z.number().int().optional(), -}); + }); /** @internal */ export type User$Outbound = { - id?: number | undefined; - username?: string | undefined; - firstName?: string | undefined; - lastName?: string | undefined; - email?: string | undefined; - password?: string | undefined; - phone?: string | undefined; - userStatus?: number | undefined; + id?: number | undefined; + username?: string | undefined; + firstName?: string | undefined; + lastName?: string | undefined; + email?: string | undefined; + password?: string | undefined; + phone?: string | undefined; + userStatus?: number | undefined; }; /** @internal */ -export const User$outboundSchema: z.ZodType = z.object({ +export const User$outboundSchema: z.ZodType = + z.object({ id: z.number().int().optional(), username: z.string().optional(), firstName: z.string().optional(), @@ -52,17 +54,17 @@ export const User$outboundSchema: z.ZodType = password: z.string().optional(), phone: z.string().optional(), userStatus: z.number().int().optional(), -}); + }); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace User$ { - /** @deprecated use `User$inboundSchema` instead. */ - export const inboundSchema = User$inboundSchema; - /** @deprecated use `User$outboundSchema` instead. */ - export const outboundSchema = User$outboundSchema; - /** @deprecated use `User$Outbound` instead. */ - export type Outbound = User$Outbound; + /** @deprecated use `User$inboundSchema` instead. */ + export const inboundSchema = User$inboundSchema; + /** @deprecated use `User$outboundSchema` instead. */ + export const outboundSchema = User$outboundSchema; + /** @deprecated use `User$Outbound` instead. */ + export type Outbound = User$Outbound; } diff --git a/src/models/errors/apierrorinvalidinput.ts b/src/models/errors/apierrorinvalidinput.ts index dfcffa6..9ad1368 100644 --- a/src/models/errors/apierrorinvalidinput.ts +++ b/src/models/errors/apierrorinvalidinput.ts @@ -8,79 +8,74 @@ import * as z from "zod"; * Not Found error */ export type ApiErrorInvalidInputData = { - status: number; - error: string; + status: number; + error: string; }; /** * Not Found error */ export class ApiErrorInvalidInput extends Error { - status: number; - error: string; + status: number; + error: string; - /** The original data that was passed to this error instance. */ - data$: ApiErrorInvalidInputData; + /** The original data that was passed to this error instance. */ + data$: ApiErrorInvalidInputData; - constructor(err: ApiErrorInvalidInputData) { - const message = - "message" in err && typeof err.message === "string" - ? err.message - : `API error occurred: ${JSON.stringify(err)}`; - super(message); - this.data$ = err; + constructor(err: ApiErrorInvalidInputData) { + const message = "message" in err && typeof err.message === "string" + ? err.message + : `API error occurred: ${JSON.stringify(err)}`; + super(message); + this.data$ = err; - this.status = err.status; - this.error = err.error; + this.status = err.status; + this.error = err.error; - this.name = "ApiErrorInvalidInput"; - } + this.name = "ApiErrorInvalidInput"; + } } /** @internal */ export const ApiErrorInvalidInput$inboundSchema: z.ZodType< - ApiErrorInvalidInput, - z.ZodTypeDef, - unknown -> = z - .object({ - status: z.number().int(), - error: z.string(), - }) - .transform((v) => { - return new ApiErrorInvalidInput(v); - }); + ApiErrorInvalidInput, + z.ZodTypeDef, + unknown +> = z.object({ + status: z.number().int(), + error: z.string(), +}) + .transform((v) => { + return new ApiErrorInvalidInput(v); + }); /** @internal */ export type ApiErrorInvalidInput$Outbound = { - status: number; - error: string; + status: number; + error: string; }; /** @internal */ export const ApiErrorInvalidInput$outboundSchema: z.ZodType< - ApiErrorInvalidInput$Outbound, - z.ZodTypeDef, - ApiErrorInvalidInput -> = z - .instanceof(ApiErrorInvalidInput) - .transform((v) => v.data$) - .pipe( - z.object({ - status: z.number().int(), - error: z.string(), - }) - ); + ApiErrorInvalidInput$Outbound, + z.ZodTypeDef, + ApiErrorInvalidInput +> = z.instanceof(ApiErrorInvalidInput) + .transform(v => v.data$) + .pipe(z.object({ + status: z.number().int(), + error: z.string(), + })); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ApiErrorInvalidInput$ { - /** @deprecated use `ApiErrorInvalidInput$inboundSchema` instead. */ - export const inboundSchema = ApiErrorInvalidInput$inboundSchema; - /** @deprecated use `ApiErrorInvalidInput$outboundSchema` instead. */ - export const outboundSchema = ApiErrorInvalidInput$outboundSchema; - /** @deprecated use `ApiErrorInvalidInput$Outbound` instead. */ - export type Outbound = ApiErrorInvalidInput$Outbound; + /** @deprecated use `ApiErrorInvalidInput$inboundSchema` instead. */ + export const inboundSchema = ApiErrorInvalidInput$inboundSchema; + /** @deprecated use `ApiErrorInvalidInput$outboundSchema` instead. */ + export const outboundSchema = ApiErrorInvalidInput$outboundSchema; + /** @deprecated use `ApiErrorInvalidInput$Outbound` instead. */ + export type Outbound = ApiErrorInvalidInput$Outbound; } diff --git a/src/models/errors/apierrornotfound.ts b/src/models/errors/apierrornotfound.ts index 558e1bd..77fb74f 100644 --- a/src/models/errors/apierrornotfound.ts +++ b/src/models/errors/apierrornotfound.ts @@ -8,81 +8,80 @@ import * as z from "zod"; * Not Found error */ export type ApiErrorNotFoundData = { - status: number; - error: string; - code: string; + status: number; + error: string; + code: string; }; /** * Not Found error */ export class ApiErrorNotFound extends Error { - status: number; - error: string; - code: string; + status: number; + error: string; + code: string; - /** The original data that was passed to this error instance. */ - data$: ApiErrorNotFoundData; + /** The original data that was passed to this error instance. */ + data$: ApiErrorNotFoundData; - constructor(err: ApiErrorNotFoundData) { - const message = - "message" in err && typeof err.message === "string" - ? err.message - : `API error occurred: ${JSON.stringify(err)}`; - super(message); - this.data$ = err; + constructor(err: ApiErrorNotFoundData) { + const message = "message" in err && typeof err.message === "string" + ? err.message + : `API error occurred: ${JSON.stringify(err)}`; + super(message); + this.data$ = err; - this.status = err.status; - this.error = err.error; - this.code = err.code; + this.status = err.status; + this.error = err.error; + this.code = err.code; - this.name = "ApiErrorNotFound"; - } + this.name = "ApiErrorNotFound"; + } } /** @internal */ -export const ApiErrorNotFound$inboundSchema: z.ZodType = z - .object({ - status: z.number().int(), - error: z.string(), - code: z.string(), - }) - .transform((v) => { - return new ApiErrorNotFound(v); - }); +export const ApiErrorNotFound$inboundSchema: z.ZodType< + ApiErrorNotFound, + z.ZodTypeDef, + unknown +> = z.object({ + status: z.number().int(), + error: z.string(), + code: z.string(), +}) + .transform((v) => { + return new ApiErrorNotFound(v); + }); /** @internal */ export type ApiErrorNotFound$Outbound = { - status: number; - error: string; - code: string; + status: number; + error: string; + code: string; }; /** @internal */ export const ApiErrorNotFound$outboundSchema: z.ZodType< - ApiErrorNotFound$Outbound, - z.ZodTypeDef, - ApiErrorNotFound -> = z - .instanceof(ApiErrorNotFound) - .transform((v) => v.data$) - .pipe( - z.object({ - status: z.number().int(), - error: z.string(), - code: z.string(), - }) - ); + ApiErrorNotFound$Outbound, + z.ZodTypeDef, + ApiErrorNotFound +> = z.instanceof(ApiErrorNotFound) + .transform(v => v.data$) + .pipe(z.object({ + status: z.number().int(), + error: z.string(), + code: z.string(), + })); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ApiErrorNotFound$ { - /** @deprecated use `ApiErrorNotFound$inboundSchema` instead. */ - export const inboundSchema = ApiErrorNotFound$inboundSchema; - /** @deprecated use `ApiErrorNotFound$outboundSchema` instead. */ - export const outboundSchema = ApiErrorNotFound$outboundSchema; - /** @deprecated use `ApiErrorNotFound$Outbound` instead. */ - export type Outbound = ApiErrorNotFound$Outbound; + /** @deprecated use `ApiErrorNotFound$inboundSchema` instead. */ + export const inboundSchema = ApiErrorNotFound$inboundSchema; + /** @deprecated use `ApiErrorNotFound$outboundSchema` instead. */ + export const outboundSchema = ApiErrorNotFound$outboundSchema; + /** @deprecated use `ApiErrorNotFound$Outbound` instead. */ + export type Outbound = ApiErrorNotFound$Outbound; } diff --git a/src/models/errors/apierrorunauthorized.ts b/src/models/errors/apierrorunauthorized.ts index 781d5cc..ce34f37 100644 --- a/src/models/errors/apierrorunauthorized.ts +++ b/src/models/errors/apierrorunauthorized.ts @@ -8,79 +8,74 @@ import * as z from "zod"; * Unauthorized error */ export type ApiErrorUnauthorizedData = { - status: number; - error: string; + status: number; + error: string; }; /** * Unauthorized error */ export class ApiErrorUnauthorized extends Error { - status: number; - error: string; + status: number; + error: string; - /** The original data that was passed to this error instance. */ - data$: ApiErrorUnauthorizedData; + /** The original data that was passed to this error instance. */ + data$: ApiErrorUnauthorizedData; - constructor(err: ApiErrorUnauthorizedData) { - const message = - "message" in err && typeof err.message === "string" - ? err.message - : `API error occurred: ${JSON.stringify(err)}`; - super(message); - this.data$ = err; + constructor(err: ApiErrorUnauthorizedData) { + const message = "message" in err && typeof err.message === "string" + ? err.message + : `API error occurred: ${JSON.stringify(err)}`; + super(message); + this.data$ = err; - this.status = err.status; - this.error = err.error; + this.status = err.status; + this.error = err.error; - this.name = "ApiErrorUnauthorized"; - } + this.name = "ApiErrorUnauthorized"; + } } /** @internal */ export const ApiErrorUnauthorized$inboundSchema: z.ZodType< - ApiErrorUnauthorized, - z.ZodTypeDef, - unknown -> = z - .object({ - status: z.number().int(), - error: z.string(), - }) - .transform((v) => { - return new ApiErrorUnauthorized(v); - }); + ApiErrorUnauthorized, + z.ZodTypeDef, + unknown +> = z.object({ + status: z.number().int(), + error: z.string(), +}) + .transform((v) => { + return new ApiErrorUnauthorized(v); + }); /** @internal */ export type ApiErrorUnauthorized$Outbound = { - status: number; - error: string; + status: number; + error: string; }; /** @internal */ export const ApiErrorUnauthorized$outboundSchema: z.ZodType< - ApiErrorUnauthorized$Outbound, - z.ZodTypeDef, - ApiErrorUnauthorized -> = z - .instanceof(ApiErrorUnauthorized) - .transform((v) => v.data$) - .pipe( - z.object({ - status: z.number().int(), - error: z.string(), - }) - ); + ApiErrorUnauthorized$Outbound, + z.ZodTypeDef, + ApiErrorUnauthorized +> = z.instanceof(ApiErrorUnauthorized) + .transform(v => v.data$) + .pipe(z.object({ + status: z.number().int(), + error: z.string(), + })); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace ApiErrorUnauthorized$ { - /** @deprecated use `ApiErrorUnauthorized$inboundSchema` instead. */ - export const inboundSchema = ApiErrorUnauthorized$inboundSchema; - /** @deprecated use `ApiErrorUnauthorized$outboundSchema` instead. */ - export const outboundSchema = ApiErrorUnauthorized$outboundSchema; - /** @deprecated use `ApiErrorUnauthorized$Outbound` instead. */ - export type Outbound = ApiErrorUnauthorized$Outbound; + /** @deprecated use `ApiErrorUnauthorized$inboundSchema` instead. */ + export const inboundSchema = ApiErrorUnauthorized$inboundSchema; + /** @deprecated use `ApiErrorUnauthorized$outboundSchema` instead. */ + export const outboundSchema = ApiErrorUnauthorized$outboundSchema; + /** @deprecated use `ApiErrorUnauthorized$Outbound` instead. */ + export type Outbound = ApiErrorUnauthorized$Outbound; } diff --git a/src/models/errors/httpclienterrors.ts b/src/models/errors/httpclienterrors.ts index cdb2995..b34f612 100644 --- a/src/models/errors/httpclienterrors.ts +++ b/src/models/errors/httpclienterrors.ts @@ -6,43 +6,43 @@ * Base class for all HTTP errors. */ export class HTTPClientError extends Error { - /** The underlying cause of the error. */ - override readonly cause: unknown; - override name = "HTTPClientError"; - constructor(message: string, opts?: { cause?: unknown }) { - let msg = message; - if (opts?.cause) { - msg += `: ${opts.cause}`; - } + /** The underlying cause of the error. */ + override readonly cause: unknown; + override name = "HTTPClientError"; + constructor(message: string, opts?: { cause?: unknown }) { + let msg = message; + if (opts?.cause) { + msg += `: ${opts.cause}`; + } - super(msg, opts); - // In older runtimes, the cause field would not have been assigned through - // the super() call. - if (typeof this.cause === "undefined") { - this.cause = opts?.cause; - } + super(msg, opts); + // In older runtimes, the cause field would not have been assigned through + // the super() call. + if (typeof this.cause === "undefined") { + this.cause = opts?.cause; } + } } /** * An error to capture unrecognised or unexpected errors when making HTTP calls. */ export class UnexpectedClientError extends HTTPClientError { - override name = "UnexpectedClientError"; + override name = "UnexpectedClientError"; } /** * An error that is raised when any inputs used to create a request are invalid. */ export class InvalidRequestError extends HTTPClientError { - override name = "InvalidRequestError"; + override name = "InvalidRequestError"; } /** * An error that is raised when a HTTP request was aborted by the client error. */ export class RequestAbortedError extends HTTPClientError { - override readonly name = "RequestAbortedError"; + override readonly name = "RequestAbortedError"; } /** @@ -50,7 +50,7 @@ export class RequestAbortedError extends HTTPClientError { * signal timeout. */ export class RequestTimeoutError extends HTTPClientError { - override readonly name = "RequestTimeoutError"; + override readonly name = "RequestTimeoutError"; } /** @@ -58,5 +58,5 @@ export class RequestTimeoutError extends HTTPClientError { * a server. */ export class ConnectionError extends HTTPClientError { - override readonly name = "ConnectionError"; + override readonly name = "ConnectionError"; } diff --git a/src/models/errors/sdkerror.ts b/src/models/errors/sdkerror.ts index 80e3aa4..001f465 100644 --- a/src/models/errors/sdkerror.ts +++ b/src/models/errors/sdkerror.ts @@ -3,23 +3,25 @@ */ export class SDKError extends Error { - public readonly statusCode: number; - public readonly contentType: string; + public readonly statusCode: number; + public readonly contentType: string; - constructor( - message: string, - public readonly rawResponse: Response, - public readonly body: string = "" - ) { - const statusCode = rawResponse.status; - const contentType = rawResponse.headers.get("content-type") || ""; - const bodyString = body.length > 0 ? `\n${body}` : ""; + constructor( + message: string, + public readonly rawResponse: Response, + public readonly body: string = "", + ) { + const statusCode = rawResponse.status; + const contentType = rawResponse.headers.get("content-type") || ""; + const bodyString = body.length > 0 ? `\n${body}` : ""; - super(`${message}: Status ${statusCode} Content-Type ${contentType} Body ${bodyString}`); + super( + `${message}: Status ${statusCode} Content-Type ${contentType} Body ${bodyString}`, + ); - this.statusCode = statusCode; - this.contentType = contentType; + this.statusCode = statusCode; + this.contentType = contentType; - this.name = "SDKError"; - } + this.name = "SDKError"; + } } diff --git a/src/models/operations/deleteorder.ts b/src/models/operations/deleteorder.ts index 759f385..5752765 100644 --- a/src/models/operations/deleteorder.ts +++ b/src/models/operations/deleteorder.ts @@ -5,33 +5,33 @@ import * as z from "zod"; export type DeleteOrderRequest = { - /** - * ID of the order that needs to be deleted - */ - orderId: number; + /** + * ID of the order that needs to be deleted + */ + orderId: number; }; /** @internal */ export const DeleteOrderRequest$inboundSchema: z.ZodType< - DeleteOrderRequest, - z.ZodTypeDef, - unknown + DeleteOrderRequest, + z.ZodTypeDef, + unknown > = z.object({ - orderId: z.number().int(), + orderId: z.number().int(), }); /** @internal */ export type DeleteOrderRequest$Outbound = { - orderId: number; + orderId: number; }; /** @internal */ export const DeleteOrderRequest$outboundSchema: z.ZodType< - DeleteOrderRequest$Outbound, - z.ZodTypeDef, - DeleteOrderRequest + DeleteOrderRequest$Outbound, + z.ZodTypeDef, + DeleteOrderRequest > = z.object({ - orderId: z.number().int(), + orderId: z.number().int(), }); /** @@ -39,10 +39,10 @@ export const DeleteOrderRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace DeleteOrderRequest$ { - /** @deprecated use `DeleteOrderRequest$inboundSchema` instead. */ - export const inboundSchema = DeleteOrderRequest$inboundSchema; - /** @deprecated use `DeleteOrderRequest$outboundSchema` instead. */ - export const outboundSchema = DeleteOrderRequest$outboundSchema; - /** @deprecated use `DeleteOrderRequest$Outbound` instead. */ - export type Outbound = DeleteOrderRequest$Outbound; + /** @deprecated use `DeleteOrderRequest$inboundSchema` instead. */ + export const inboundSchema = DeleteOrderRequest$inboundSchema; + /** @deprecated use `DeleteOrderRequest$outboundSchema` instead. */ + export const outboundSchema = DeleteOrderRequest$outboundSchema; + /** @deprecated use `DeleteOrderRequest$Outbound` instead. */ + export type Outbound = DeleteOrderRequest$Outbound; } diff --git a/src/models/operations/deletepet.ts b/src/models/operations/deletepet.ts index 5499405..66fadae 100644 --- a/src/models/operations/deletepet.ts +++ b/src/models/operations/deletepet.ts @@ -2,60 +2,60 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { remap as remap$ } from "../../lib/primitives.js"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; export type DeletePetRequest = { - apiKey?: string | undefined; - /** - * Pet id to delete - */ - petId: number; + apiKey?: string | undefined; + /** + * Pet id to delete + */ + petId: number; }; /** @internal */ -export const DeletePetRequest$inboundSchema: z.ZodType = z - .object({ - api_key: z.string().optional(), - petId: z.number().int(), - }) - .transform((v) => { - return remap$(v, { - api_key: "apiKey", - }); - }); +export const DeletePetRequest$inboundSchema: z.ZodType< + DeletePetRequest, + z.ZodTypeDef, + unknown +> = z.object({ + api_key: z.string().optional(), + petId: z.number().int(), +}).transform((v) => { + return remap$(v, { + "api_key": "apiKey", + }); +}); /** @internal */ export type DeletePetRequest$Outbound = { - api_key?: string | undefined; - petId: number; + api_key?: string | undefined; + petId: number; }; /** @internal */ export const DeletePetRequest$outboundSchema: z.ZodType< - DeletePetRequest$Outbound, - z.ZodTypeDef, - DeletePetRequest -> = z - .object({ - apiKey: z.string().optional(), - petId: z.number().int(), - }) - .transform((v) => { - return remap$(v, { - apiKey: "api_key", - }); - }); + DeletePetRequest$Outbound, + z.ZodTypeDef, + DeletePetRequest +> = z.object({ + apiKey: z.string().optional(), + petId: z.number().int(), +}).transform((v) => { + return remap$(v, { + apiKey: "api_key", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace DeletePetRequest$ { - /** @deprecated use `DeletePetRequest$inboundSchema` instead. */ - export const inboundSchema = DeletePetRequest$inboundSchema; - /** @deprecated use `DeletePetRequest$outboundSchema` instead. */ - export const outboundSchema = DeletePetRequest$outboundSchema; - /** @deprecated use `DeletePetRequest$Outbound` instead. */ - export type Outbound = DeletePetRequest$Outbound; + /** @deprecated use `DeletePetRequest$inboundSchema` instead. */ + export const inboundSchema = DeletePetRequest$inboundSchema; + /** @deprecated use `DeletePetRequest$outboundSchema` instead. */ + export const outboundSchema = DeletePetRequest$outboundSchema; + /** @deprecated use `DeletePetRequest$Outbound` instead. */ + export type Outbound = DeletePetRequest$Outbound; } diff --git a/src/models/operations/deleteuser.ts b/src/models/operations/deleteuser.ts index cd85492..67d6906 100644 --- a/src/models/operations/deleteuser.ts +++ b/src/models/operations/deleteuser.ts @@ -5,30 +5,33 @@ import * as z from "zod"; export type DeleteUserRequest = { - /** - * The name that needs to be deleted - */ - username: string; + /** + * The name that needs to be deleted + */ + username: string; }; /** @internal */ -export const DeleteUserRequest$inboundSchema: z.ZodType = - z.object({ - username: z.string(), - }); +export const DeleteUserRequest$inboundSchema: z.ZodType< + DeleteUserRequest, + z.ZodTypeDef, + unknown +> = z.object({ + username: z.string(), +}); /** @internal */ export type DeleteUserRequest$Outbound = { - username: string; + username: string; }; /** @internal */ export const DeleteUserRequest$outboundSchema: z.ZodType< - DeleteUserRequest$Outbound, - z.ZodTypeDef, - DeleteUserRequest + DeleteUserRequest$Outbound, + z.ZodTypeDef, + DeleteUserRequest > = z.object({ - username: z.string(), + username: z.string(), }); /** @@ -36,10 +39,10 @@ export const DeleteUserRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace DeleteUserRequest$ { - /** @deprecated use `DeleteUserRequest$inboundSchema` instead. */ - export const inboundSchema = DeleteUserRequest$inboundSchema; - /** @deprecated use `DeleteUserRequest$outboundSchema` instead. */ - export const outboundSchema = DeleteUserRequest$outboundSchema; - /** @deprecated use `DeleteUserRequest$Outbound` instead. */ - export type Outbound = DeleteUserRequest$Outbound; + /** @deprecated use `DeleteUserRequest$inboundSchema` instead. */ + export const inboundSchema = DeleteUserRequest$inboundSchema; + /** @deprecated use `DeleteUserRequest$outboundSchema` instead. */ + export const outboundSchema = DeleteUserRequest$outboundSchema; + /** @deprecated use `DeleteUserRequest$Outbound` instead. */ + export type Outbound = DeleteUserRequest$Outbound; } diff --git a/src/models/operations/findpetsbystatus.ts b/src/models/operations/findpetsbystatus.ts index ed0fcae..61d1afd 100644 --- a/src/models/operations/findpetsbystatus.ts +++ b/src/models/operations/findpetsbystatus.ts @@ -2,16 +2,16 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { ClosedEnum } from "../../types/enums.js"; import * as z from "zod"; +import { ClosedEnum } from "../../types/enums.js"; /** * Status values that need to be considered for filter */ export const Status = { - Available: "available", - Pending: "pending", - Sold: "sold", + Available: "available", + Pending: "pending", + Sold: "sold", } as const; /** * Status values that need to be considered for filter @@ -19,50 +19,52 @@ export const Status = { export type Status = ClosedEnum; export type FindPetsByStatusRequest = { - /** - * Status values that need to be considered for filter - */ - status?: Status | undefined; + /** + * Status values that need to be considered for filter + */ + status?: Status | undefined; }; /** @internal */ -export const Status$inboundSchema: z.ZodNativeEnum = z.nativeEnum(Status); +export const Status$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(Status); /** @internal */ -export const Status$outboundSchema: z.ZodNativeEnum = Status$inboundSchema; +export const Status$outboundSchema: z.ZodNativeEnum = + Status$inboundSchema; /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace Status$ { - /** @deprecated use `Status$inboundSchema` instead. */ - export const inboundSchema = Status$inboundSchema; - /** @deprecated use `Status$outboundSchema` instead. */ - export const outboundSchema = Status$outboundSchema; + /** @deprecated use `Status$inboundSchema` instead. */ + export const inboundSchema = Status$inboundSchema; + /** @deprecated use `Status$outboundSchema` instead. */ + export const outboundSchema = Status$outboundSchema; } /** @internal */ export const FindPetsByStatusRequest$inboundSchema: z.ZodType< - FindPetsByStatusRequest, - z.ZodTypeDef, - unknown + FindPetsByStatusRequest, + z.ZodTypeDef, + unknown > = z.object({ - status: Status$inboundSchema.default("available"), + status: Status$inboundSchema.default("available"), }); /** @internal */ export type FindPetsByStatusRequest$Outbound = { - status: string; + status: string; }; /** @internal */ export const FindPetsByStatusRequest$outboundSchema: z.ZodType< - FindPetsByStatusRequest$Outbound, - z.ZodTypeDef, - FindPetsByStatusRequest + FindPetsByStatusRequest$Outbound, + z.ZodTypeDef, + FindPetsByStatusRequest > = z.object({ - status: Status$outboundSchema.default("available"), + status: Status$outboundSchema.default("available"), }); /** @@ -70,10 +72,10 @@ export const FindPetsByStatusRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace FindPetsByStatusRequest$ { - /** @deprecated use `FindPetsByStatusRequest$inboundSchema` instead. */ - export const inboundSchema = FindPetsByStatusRequest$inboundSchema; - /** @deprecated use `FindPetsByStatusRequest$outboundSchema` instead. */ - export const outboundSchema = FindPetsByStatusRequest$outboundSchema; - /** @deprecated use `FindPetsByStatusRequest$Outbound` instead. */ - export type Outbound = FindPetsByStatusRequest$Outbound; + /** @deprecated use `FindPetsByStatusRequest$inboundSchema` instead. */ + export const inboundSchema = FindPetsByStatusRequest$inboundSchema; + /** @deprecated use `FindPetsByStatusRequest$outboundSchema` instead. */ + export const outboundSchema = FindPetsByStatusRequest$outboundSchema; + /** @deprecated use `FindPetsByStatusRequest$Outbound` instead. */ + export type Outbound = FindPetsByStatusRequest$Outbound; } diff --git a/src/models/operations/findpetsbytags.ts b/src/models/operations/findpetsbytags.ts index dcb2d51..356eab3 100644 --- a/src/models/operations/findpetsbytags.ts +++ b/src/models/operations/findpetsbytags.ts @@ -5,33 +5,33 @@ import * as z from "zod"; export type FindPetsByTagsRequest = { - /** - * Tags to filter by - */ - tags?: Array | undefined; + /** + * Tags to filter by + */ + tags?: Array | undefined; }; /** @internal */ export const FindPetsByTagsRequest$inboundSchema: z.ZodType< - FindPetsByTagsRequest, - z.ZodTypeDef, - unknown + FindPetsByTagsRequest, + z.ZodTypeDef, + unknown > = z.object({ - tags: z.array(z.string()).optional(), + tags: z.array(z.string()).optional(), }); /** @internal */ export type FindPetsByTagsRequest$Outbound = { - tags?: Array | undefined; + tags?: Array | undefined; }; /** @internal */ export const FindPetsByTagsRequest$outboundSchema: z.ZodType< - FindPetsByTagsRequest$Outbound, - z.ZodTypeDef, - FindPetsByTagsRequest + FindPetsByTagsRequest$Outbound, + z.ZodTypeDef, + FindPetsByTagsRequest > = z.object({ - tags: z.array(z.string()).optional(), + tags: z.array(z.string()).optional(), }); /** @@ -39,10 +39,10 @@ export const FindPetsByTagsRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace FindPetsByTagsRequest$ { - /** @deprecated use `FindPetsByTagsRequest$inboundSchema` instead. */ - export const inboundSchema = FindPetsByTagsRequest$inboundSchema; - /** @deprecated use `FindPetsByTagsRequest$outboundSchema` instead. */ - export const outboundSchema = FindPetsByTagsRequest$outboundSchema; - /** @deprecated use `FindPetsByTagsRequest$Outbound` instead. */ - export type Outbound = FindPetsByTagsRequest$Outbound; + /** @deprecated use `FindPetsByTagsRequest$inboundSchema` instead. */ + export const inboundSchema = FindPetsByTagsRequest$inboundSchema; + /** @deprecated use `FindPetsByTagsRequest$outboundSchema` instead. */ + export const outboundSchema = FindPetsByTagsRequest$outboundSchema; + /** @deprecated use `FindPetsByTagsRequest$Outbound` instead. */ + export type Outbound = FindPetsByTagsRequest$Outbound; } diff --git a/src/models/operations/getorderbyid.ts b/src/models/operations/getorderbyid.ts index 1eedf54..cef4081 100644 --- a/src/models/operations/getorderbyid.ts +++ b/src/models/operations/getorderbyid.ts @@ -5,33 +5,33 @@ import * as z from "zod"; export type GetOrderByIdRequest = { - /** - * ID of order that needs to be fetched - */ - orderId: number; + /** + * ID of order that needs to be fetched + */ + orderId: number; }; /** @internal */ export const GetOrderByIdRequest$inboundSchema: z.ZodType< - GetOrderByIdRequest, - z.ZodTypeDef, - unknown + GetOrderByIdRequest, + z.ZodTypeDef, + unknown > = z.object({ - orderId: z.number().int(), + orderId: z.number().int(), }); /** @internal */ export type GetOrderByIdRequest$Outbound = { - orderId: number; + orderId: number; }; /** @internal */ export const GetOrderByIdRequest$outboundSchema: z.ZodType< - GetOrderByIdRequest$Outbound, - z.ZodTypeDef, - GetOrderByIdRequest + GetOrderByIdRequest$Outbound, + z.ZodTypeDef, + GetOrderByIdRequest > = z.object({ - orderId: z.number().int(), + orderId: z.number().int(), }); /** @@ -39,10 +39,10 @@ export const GetOrderByIdRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace GetOrderByIdRequest$ { - /** @deprecated use `GetOrderByIdRequest$inboundSchema` instead. */ - export const inboundSchema = GetOrderByIdRequest$inboundSchema; - /** @deprecated use `GetOrderByIdRequest$outboundSchema` instead. */ - export const outboundSchema = GetOrderByIdRequest$outboundSchema; - /** @deprecated use `GetOrderByIdRequest$Outbound` instead. */ - export type Outbound = GetOrderByIdRequest$Outbound; + /** @deprecated use `GetOrderByIdRequest$inboundSchema` instead. */ + export const inboundSchema = GetOrderByIdRequest$inboundSchema; + /** @deprecated use `GetOrderByIdRequest$outboundSchema` instead. */ + export const outboundSchema = GetOrderByIdRequest$outboundSchema; + /** @deprecated use `GetOrderByIdRequest$Outbound` instead. */ + export type Outbound = GetOrderByIdRequest$Outbound; } diff --git a/src/models/operations/getpetbyid.ts b/src/models/operations/getpetbyid.ts index a96a8e4..a9d76a5 100644 --- a/src/models/operations/getpetbyid.ts +++ b/src/models/operations/getpetbyid.ts @@ -5,30 +5,33 @@ import * as z from "zod"; export type GetPetByIdRequest = { - /** - * ID of pet to return - */ - petId: number; + /** + * ID of pet to return + */ + petId: number; }; /** @internal */ -export const GetPetByIdRequest$inboundSchema: z.ZodType = - z.object({ - petId: z.number().int(), - }); +export const GetPetByIdRequest$inboundSchema: z.ZodType< + GetPetByIdRequest, + z.ZodTypeDef, + unknown +> = z.object({ + petId: z.number().int(), +}); /** @internal */ export type GetPetByIdRequest$Outbound = { - petId: number; + petId: number; }; /** @internal */ export const GetPetByIdRequest$outboundSchema: z.ZodType< - GetPetByIdRequest$Outbound, - z.ZodTypeDef, - GetPetByIdRequest + GetPetByIdRequest$Outbound, + z.ZodTypeDef, + GetPetByIdRequest > = z.object({ - petId: z.number().int(), + petId: z.number().int(), }); /** @@ -36,10 +39,10 @@ export const GetPetByIdRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace GetPetByIdRequest$ { - /** @deprecated use `GetPetByIdRequest$inboundSchema` instead. */ - export const inboundSchema = GetPetByIdRequest$inboundSchema; - /** @deprecated use `GetPetByIdRequest$outboundSchema` instead. */ - export const outboundSchema = GetPetByIdRequest$outboundSchema; - /** @deprecated use `GetPetByIdRequest$Outbound` instead. */ - export type Outbound = GetPetByIdRequest$Outbound; + /** @deprecated use `GetPetByIdRequest$inboundSchema` instead. */ + export const inboundSchema = GetPetByIdRequest$inboundSchema; + /** @deprecated use `GetPetByIdRequest$outboundSchema` instead. */ + export const outboundSchema = GetPetByIdRequest$outboundSchema; + /** @deprecated use `GetPetByIdRequest$Outbound` instead. */ + export type Outbound = GetPetByIdRequest$Outbound; } diff --git a/src/models/operations/getuserbyname.ts b/src/models/operations/getuserbyname.ts index d2a2e4f..e089fcb 100644 --- a/src/models/operations/getuserbyname.ts +++ b/src/models/operations/getuserbyname.ts @@ -5,33 +5,33 @@ import * as z from "zod"; export type GetUserByNameRequest = { - /** - * The name that needs to be fetched. Use user1 for testing. - */ - username: string; + /** + * The name that needs to be fetched. Use user1 for testing. + */ + username: string; }; /** @internal */ export const GetUserByNameRequest$inboundSchema: z.ZodType< - GetUserByNameRequest, - z.ZodTypeDef, - unknown + GetUserByNameRequest, + z.ZodTypeDef, + unknown > = z.object({ - username: z.string(), + username: z.string(), }); /** @internal */ export type GetUserByNameRequest$Outbound = { - username: string; + username: string; }; /** @internal */ export const GetUserByNameRequest$outboundSchema: z.ZodType< - GetUserByNameRequest$Outbound, - z.ZodTypeDef, - GetUserByNameRequest + GetUserByNameRequest$Outbound, + z.ZodTypeDef, + GetUserByNameRequest > = z.object({ - username: z.string(), + username: z.string(), }); /** @@ -39,10 +39,10 @@ export const GetUserByNameRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace GetUserByNameRequest$ { - /** @deprecated use `GetUserByNameRequest$inboundSchema` instead. */ - export const inboundSchema = GetUserByNameRequest$inboundSchema; - /** @deprecated use `GetUserByNameRequest$outboundSchema` instead. */ - export const outboundSchema = GetUserByNameRequest$outboundSchema; - /** @deprecated use `GetUserByNameRequest$Outbound` instead. */ - export type Outbound = GetUserByNameRequest$Outbound; + /** @deprecated use `GetUserByNameRequest$inboundSchema` instead. */ + export const inboundSchema = GetUserByNameRequest$inboundSchema; + /** @deprecated use `GetUserByNameRequest$outboundSchema` instead. */ + export const outboundSchema = GetUserByNameRequest$outboundSchema; + /** @deprecated use `GetUserByNameRequest$Outbound` instead. */ + export type Outbound = GetUserByNameRequest$Outbound; } diff --git a/src/models/operations/loginuser.ts b/src/models/operations/loginuser.ts index 153a483..0932d42 100644 --- a/src/models/operations/loginuser.ts +++ b/src/models/operations/loginuser.ts @@ -2,46 +2,49 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { remap as remap$ } from "../../lib/primitives.js"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; export type LoginUserRequest = { - /** - * The user name for login - */ - username?: string | undefined; - /** - * The password for login in clear text - */ - password?: string | undefined; + /** + * The user name for login + */ + username?: string | undefined; + /** + * The password for login in clear text + */ + password?: string | undefined; }; export type LoginUserResponse = { - headers: { [k: string]: Array }; - result: string; + headers: { [k: string]: Array }; + result: string; }; /** @internal */ -export const LoginUserRequest$inboundSchema: z.ZodType = - z.object({ - username: z.string().optional(), - password: z.string().optional(), - }); +export const LoginUserRequest$inboundSchema: z.ZodType< + LoginUserRequest, + z.ZodTypeDef, + unknown +> = z.object({ + username: z.string().optional(), + password: z.string().optional(), +}); /** @internal */ export type LoginUserRequest$Outbound = { - username?: string | undefined; - password?: string | undefined; + username?: string | undefined; + password?: string | undefined; }; /** @internal */ export const LoginUserRequest$outboundSchema: z.ZodType< - LoginUserRequest$Outbound, - z.ZodTypeDef, - LoginUserRequest + LoginUserRequest$Outbound, + z.ZodTypeDef, + LoginUserRequest > = z.object({ - username: z.string().optional(), - password: z.string().optional(), + username: z.string().optional(), + password: z.string().optional(), }); /** @@ -49,60 +52,59 @@ export const LoginUserRequest$outboundSchema: z.ZodType< * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace LoginUserRequest$ { - /** @deprecated use `LoginUserRequest$inboundSchema` instead. */ - export const inboundSchema = LoginUserRequest$inboundSchema; - /** @deprecated use `LoginUserRequest$outboundSchema` instead. */ - export const outboundSchema = LoginUserRequest$outboundSchema; - /** @deprecated use `LoginUserRequest$Outbound` instead. */ - export type Outbound = LoginUserRequest$Outbound; + /** @deprecated use `LoginUserRequest$inboundSchema` instead. */ + export const inboundSchema = LoginUserRequest$inboundSchema; + /** @deprecated use `LoginUserRequest$outboundSchema` instead. */ + export const outboundSchema = LoginUserRequest$outboundSchema; + /** @deprecated use `LoginUserRequest$Outbound` instead. */ + export type Outbound = LoginUserRequest$Outbound; } /** @internal */ -export const LoginUserResponse$inboundSchema: z.ZodType = - z - .object({ - Headers: z.record(z.array(z.string())), - Result: z.string(), - }) - .transform((v) => { - return remap$(v, { - Headers: "headers", - Result: "result", - }); - }); +export const LoginUserResponse$inboundSchema: z.ZodType< + LoginUserResponse, + z.ZodTypeDef, + unknown +> = z.object({ + Headers: z.record(z.array(z.string())), + Result: z.string(), +}).transform((v) => { + return remap$(v, { + "Headers": "headers", + "Result": "result", + }); +}); /** @internal */ export type LoginUserResponse$Outbound = { - Headers: { [k: string]: Array }; - Result: string; + Headers: { [k: string]: Array }; + Result: string; }; /** @internal */ export const LoginUserResponse$outboundSchema: z.ZodType< - LoginUserResponse$Outbound, - z.ZodTypeDef, - LoginUserResponse -> = z - .object({ - headers: z.record(z.array(z.string())), - result: z.string(), - }) - .transform((v) => { - return remap$(v, { - headers: "Headers", - result: "Result", - }); - }); + LoginUserResponse$Outbound, + z.ZodTypeDef, + LoginUserResponse +> = z.object({ + headers: z.record(z.array(z.string())), + result: z.string(), +}).transform((v) => { + return remap$(v, { + headers: "Headers", + result: "Result", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace LoginUserResponse$ { - /** @deprecated use `LoginUserResponse$inboundSchema` instead. */ - export const inboundSchema = LoginUserResponse$inboundSchema; - /** @deprecated use `LoginUserResponse$outboundSchema` instead. */ - export const outboundSchema = LoginUserResponse$outboundSchema; - /** @deprecated use `LoginUserResponse$Outbound` instead. */ - export type Outbound = LoginUserResponse$Outbound; + /** @deprecated use `LoginUserResponse$inboundSchema` instead. */ + export const inboundSchema = LoginUserResponse$inboundSchema; + /** @deprecated use `LoginUserResponse$outboundSchema` instead. */ + export const outboundSchema = LoginUserResponse$outboundSchema; + /** @deprecated use `LoginUserResponse$Outbound` instead. */ + export type Outbound = LoginUserResponse$Outbound; } diff --git a/src/models/operations/updateuser.ts b/src/models/operations/updateuser.ts index 149005d..4d7e0d0 100644 --- a/src/models/operations/updateuser.ts +++ b/src/models/operations/updateuser.ts @@ -2,65 +2,64 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import * as z from "zod"; import { remap as remap$ } from "../../lib/primitives.js"; import * as components from "../components/index.js"; -import * as z from "zod"; export type UpdateUserRequest = { - /** - * name that needs to be updated - */ - username: string; - /** - * Update an existent user in the store - */ - user?: components.User | undefined; + /** + * name that needs to be updated + */ + username: string; + /** + * Update an existent user in the store + */ + user?: components.User | undefined; }; /** @internal */ -export const UpdateUserRequest$inboundSchema: z.ZodType = - z - .object({ - username: z.string(), - User: components.User$inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - User: "user", - }); - }); +export const UpdateUserRequest$inboundSchema: z.ZodType< + UpdateUserRequest, + z.ZodTypeDef, + unknown +> = z.object({ + username: z.string(), + User: components.User$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "User": "user", + }); +}); /** @internal */ export type UpdateUserRequest$Outbound = { - username: string; - User?: components.User$Outbound | undefined; + username: string; + User?: components.User$Outbound | undefined; }; /** @internal */ export const UpdateUserRequest$outboundSchema: z.ZodType< - UpdateUserRequest$Outbound, - z.ZodTypeDef, - UpdateUserRequest -> = z - .object({ - username: z.string(), - user: components.User$outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - user: "User", - }); - }); + UpdateUserRequest$Outbound, + z.ZodTypeDef, + UpdateUserRequest +> = z.object({ + username: z.string(), + user: components.User$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + user: "User", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace UpdateUserRequest$ { - /** @deprecated use `UpdateUserRequest$inboundSchema` instead. */ - export const inboundSchema = UpdateUserRequest$inboundSchema; - /** @deprecated use `UpdateUserRequest$outboundSchema` instead. */ - export const outboundSchema = UpdateUserRequest$outboundSchema; - /** @deprecated use `UpdateUserRequest$Outbound` instead. */ - export type Outbound = UpdateUserRequest$Outbound; + /** @deprecated use `UpdateUserRequest$inboundSchema` instead. */ + export const inboundSchema = UpdateUserRequest$inboundSchema; + /** @deprecated use `UpdateUserRequest$outboundSchema` instead. */ + export const outboundSchema = UpdateUserRequest$outboundSchema; + /** @deprecated use `UpdateUserRequest$Outbound` instead. */ + export type Outbound = UpdateUserRequest$Outbound; } diff --git a/src/models/operations/uploadfile.ts b/src/models/operations/uploadfile.ts index 87d8bef..15040b1 100644 --- a/src/models/operations/uploadfile.ts +++ b/src/models/operations/uploadfile.ts @@ -2,69 +2,87 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import * as b64$ from "../../lib/base64.js"; -import { remap as remap$ } from "../../lib/primitives.js"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; export type UploadFileRequest = { - /** - * ID of pet to update - */ - petId: number; - /** - * Additional Metadata - */ - additionalMetadata?: string | undefined; - requestBody?: Uint8Array | string | undefined; + /** + * ID of pet to update + */ + petId: number; + /** + * Additional Metadata + */ + additionalMetadata?: string | undefined; + requestBody?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined; }; /** @internal */ -export const UploadFileRequest$inboundSchema: z.ZodType = - z - .object({ - petId: z.number().int(), - additionalMetadata: z.string().optional(), - RequestBody: b64$.zodInbound.optional(), - }) - .transform((v) => { - return remap$(v, { - RequestBody: "requestBody", - }); - }); +export const UploadFileRequest$inboundSchema: z.ZodType< + UploadFileRequest, + z.ZodTypeDef, + unknown +> = z.object({ + petId: z.number().int(), + additionalMetadata: z.string().optional(), + RequestBody: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional(), +}).transform((v) => { + return remap$(v, { + "RequestBody": "requestBody", + }); +}); /** @internal */ export type UploadFileRequest$Outbound = { - petId: number; - additionalMetadata?: string | undefined; - RequestBody?: Uint8Array | undefined; + petId: number; + additionalMetadata?: string | undefined; + RequestBody?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined; }; /** @internal */ export const UploadFileRequest$outboundSchema: z.ZodType< - UploadFileRequest$Outbound, - z.ZodTypeDef, - UploadFileRequest -> = z - .object({ - petId: z.number().int(), - additionalMetadata: z.string().optional(), - requestBody: b64$.zodOutbound.optional(), - }) - .transform((v) => { - return remap$(v, { - requestBody: "RequestBody", - }); - }); + UploadFileRequest$Outbound, + z.ZodTypeDef, + UploadFileRequest +> = z.object({ + petId: z.number().int(), + additionalMetadata: z.string().optional(), + requestBody: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional(), +}).transform((v) => { + return remap$(v, { + requestBody: "RequestBody", + }); +}); /** * @internal * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. */ export namespace UploadFileRequest$ { - /** @deprecated use `UploadFileRequest$inboundSchema` instead. */ - export const inboundSchema = UploadFileRequest$inboundSchema; - /** @deprecated use `UploadFileRequest$outboundSchema` instead. */ - export const outboundSchema = UploadFileRequest$outboundSchema; - /** @deprecated use `UploadFileRequest$Outbound` instead. */ - export type Outbound = UploadFileRequest$Outbound; + /** @deprecated use `UploadFileRequest$inboundSchema` instead. */ + export const inboundSchema = UploadFileRequest$inboundSchema; + /** @deprecated use `UploadFileRequest$outboundSchema` instead. */ + export const outboundSchema = UploadFileRequest$outboundSchema; + /** @deprecated use `UploadFileRequest$Outbound` instead. */ + export type Outbound = UploadFileRequest$Outbound; } diff --git a/src/sdk/pet.ts b/src/sdk/pet.ts index 5a8cd8b..71d3f61 100644 --- a/src/sdk/pet.ts +++ b/src/sdk/pet.ts @@ -15,82 +15,116 @@ import * as operations from "../models/operations/index.js"; import { unwrapAsync } from "../types/fp.js"; export class Pet extends ClientSDK { - /** - * Update an existing pet - * - * @remarks - * Update an existing pet by Id - */ - async updatePet(request: components.Pet, options?: RequestOptions): Promise { - return unwrapAsync(petUpdatePet(this, request, options)); - } + /** + * Update an existing pet + * + * @remarks + * Update an existing pet by Id + */ + async updatePet( + request: components.Pet, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petUpdatePet( + this, + request, + options, + )); + } - /** - * Add a new pet to the store - * - * @remarks - * Add a new pet to the store - */ - async addPet(request: components.Pet, options?: RequestOptions): Promise { - return unwrapAsync(petAddPet(this, request, options)); - } + /** + * Add a new pet to the store + * + * @remarks + * Add a new pet to the store + */ + async addPet( + request: components.Pet, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petAddPet( + this, + request, + options, + )); + } - /** - * Finds Pets by status - * - * @remarks - * Multiple status values can be provided with comma separated strings - */ - async findPetsByStatus( - request: operations.FindPetsByStatusRequest, - options?: RequestOptions - ): Promise> { - return unwrapAsync(petFindPetsByStatus(this, request, options)); - } + /** + * Finds Pets by status + * + * @remarks + * Multiple status values can be provided with comma separated strings + */ + async findPetsByStatus( + request: operations.FindPetsByStatusRequest, + options?: RequestOptions, + ): Promise> { + return unwrapAsync(petFindPetsByStatus( + this, + request, + options, + )); + } - /** - * Finds Pets by tags - * - * @remarks - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - */ - async findPetsByTags( - request: operations.FindPetsByTagsRequest, - options?: RequestOptions - ): Promise> { - return unwrapAsync(petFindPetsByTags(this, request, options)); - } + /** + * Finds Pets by tags + * + * @remarks + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + */ + async findPetsByTags( + request: operations.FindPetsByTagsRequest, + options?: RequestOptions, + ): Promise> { + return unwrapAsync(petFindPetsByTags( + this, + request, + options, + )); + } - /** - * Find pet by ID - * - * @remarks - * Returns a single pet - */ - async getPetById( - request: operations.GetPetByIdRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(petGetPetById(this, request, options)); - } + /** + * Find pet by ID + * + * @remarks + * Returns a single pet + */ + async getPetById( + request: operations.GetPetByIdRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petGetPetById( + this, + request, + options, + )); + } - /** - * Deletes a pet - */ - async deletePet( - request: operations.DeletePetRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(petDeletePet(this, request, options)); - } + /** + * Deletes a pet + */ + async deletePet( + request: operations.DeletePetRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petDeletePet( + this, + request, + options, + )); + } - /** - * uploads an image - */ - async uploadFile( - request: operations.UploadFileRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(petUploadFile(this, request, options)); - } + /** + * uploads an image + */ + async uploadFile( + request: operations.UploadFileRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(petUploadFile( + this, + request, + options, + )); + } } diff --git a/src/sdk/sdk.ts b/src/sdk/sdk.ts index 8f30ce2..52f37c6 100644 --- a/src/sdk/sdk.ts +++ b/src/sdk/sdk.ts @@ -8,18 +8,18 @@ import { Store } from "./store.js"; import { User } from "./user.js"; export class Petstore extends ClientSDK { - private _pet?: Pet; - get pet(): Pet { - return (this._pet ??= new Pet(this.options$)); - } + private _pet?: Pet; + get pet(): Pet { + return (this._pet ??= new Pet(this._options)); + } - private _store?: Store; - get store(): Store { - return (this._store ??= new Store(this.options$)); - } + private _store?: Store; + get store(): Store { + return (this._store ??= new Store(this._options)); + } - private _user?: User; - get user(): User { - return (this._user ??= new User(this.options$)); - } + private _user?: User; + get user(): User { + return (this._user ??= new User(this._options)); + } } diff --git a/src/sdk/store.ts b/src/sdk/store.ts index 8c3129a..b824a07 100644 --- a/src/sdk/store.ts +++ b/src/sdk/store.ts @@ -12,52 +12,69 @@ import * as operations from "../models/operations/index.js"; import { unwrapAsync } from "../types/fp.js"; export class Store extends ClientSDK { - /** - * Returns pet inventories by status - * - * @remarks - * Returns a map of status codes to quantities - */ - async getInventory(options?: RequestOptions): Promise<{ [k: string]: number }> { - return unwrapAsync(storeGetInventory(this, options)); - } + /** + * Returns pet inventories by status + * + * @remarks + * Returns a map of status codes to quantities + */ + async getInventory( + options?: RequestOptions, + ): Promise<{ [k: string]: number }> { + return unwrapAsync(storeGetInventory( + this, + options, + )); + } - /** - * Place an order for a pet - * - * @remarks - * Place a new order in the store - */ - async placeOrder( - request?: components.Order | undefined, - options?: RequestOptions - ): Promise { - return unwrapAsync(storePlaceOrder(this, request, options)); - } + /** + * Place an order for a pet + * + * @remarks + * Place a new order in the store + */ + async placeOrder( + request?: components.Order | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(storePlaceOrder( + this, + request, + options, + )); + } - /** - * Find purchase order by ID - * - * @remarks - * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. - */ - async getOrderById( - request: operations.GetOrderByIdRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(storeGetOrderById(this, request, options)); - } + /** + * Find purchase order by ID + * + * @remarks + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions. + */ + async getOrderById( + request: operations.GetOrderByIdRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(storeGetOrderById( + this, + request, + options, + )); + } - /** - * Delete purchase order by ID - * - * @remarks - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - */ - async deleteOrder( - request: operations.DeleteOrderRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(storeDeleteOrder(this, request, options)); - } + /** + * Delete purchase order by ID + * + * @remarks + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + async deleteOrder( + request: operations.DeleteOrderRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(storeDeleteOrder( + this, + request, + options, + )); + } } diff --git a/src/sdk/user.ts b/src/sdk/user.ts index c48965e..3f7e84c 100644 --- a/src/sdk/user.ts +++ b/src/sdk/user.ts @@ -15,82 +15,111 @@ import * as operations from "../models/operations/index.js"; import { unwrapAsync } from "../types/fp.js"; export class User extends ClientSDK { - /** - * Create user - * - * @remarks - * This can only be done by the logged in user. - */ - async createUser( - request?: components.User | undefined, - options?: RequestOptions - ): Promise { - return unwrapAsync(userCreateUser(this, request, options)); - } + /** + * Create user + * + * @remarks + * This can only be done by the logged in user. + */ + async createUser( + request?: components.User | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userCreateUser( + this, + request, + options, + )); + } - /** - * Creates list of users with given input array - * - * @remarks - * Creates list of users with given input array - */ - async createUsersWithListInput( - request?: Array | undefined, - options?: RequestOptions - ): Promise { - return unwrapAsync(userCreateUsersWithListInput(this, request, options)); - } + /** + * Creates list of users with given input array + * + * @remarks + * Creates list of users with given input array + */ + async createUsersWithListInput( + request?: Array | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userCreateUsersWithListInput( + this, + request, + options, + )); + } - /** - * Logs user into the system - */ - async loginUser( - request: operations.LoginUserRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(userLoginUser(this, request, options)); - } + /** + * Logs user into the system + */ + async loginUser( + request: operations.LoginUserRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userLoginUser( + this, + request, + options, + )); + } - /** - * Logs out current logged in user session - */ - async logoutUser(options?: RequestOptions): Promise { - return unwrapAsync(userLogoutUser(this, options)); - } + /** + * Logs out current logged in user session + */ + async logoutUser( + options?: RequestOptions, + ): Promise { + return unwrapAsync(userLogoutUser( + this, + options, + )); + } - /** - * Get user by user name - */ - async getUserByName( - request: operations.GetUserByNameRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(userGetUserByName(this, request, options)); - } + /** + * Get user by user name + */ + async getUserByName( + request: operations.GetUserByNameRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userGetUserByName( + this, + request, + options, + )); + } - /** - * Update user - * - * @remarks - * This can only be done by the logged in user. - */ - async updateUser( - request: operations.UpdateUserRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(userUpdateUser(this, request, options)); - } + /** + * Update user + * + * @remarks + * This can only be done by the logged in user. + */ + async updateUser( + request: operations.UpdateUserRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userUpdateUser( + this, + request, + options, + )); + } - /** - * Delete user - * - * @remarks - * This can only be done by the logged in user. - */ - async deleteUser( - request: operations.DeleteUserRequest, - options?: RequestOptions - ): Promise { - return unwrapAsync(userDeleteUser(this, request, options)); - } + /** + * Delete user + * + * @remarks + * This can only be done by the logged in user. + */ + async deleteUser( + request: operations.DeleteUserRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(userDeleteUser( + this, + request, + options, + )); + } } diff --git a/src/types/index.ts b/src/types/index.ts index dbaa5e6..e124e81 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -2,10 +2,10 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export { RFCDate } from "./rfcdate.js"; export { blobLikeSchema, isBlobLike } from "./blobs.js"; -export type { Paginator, PageIterator } from "./operations.js"; -export { createPageIterator } from "./operations.js"; export { catchUnrecognizedEnum } from "./enums.js"; -export type { OpenEnum, ClosedEnum, Unrecognized } from "./enums.js"; +export type { ClosedEnum, OpenEnum, Unrecognized } from "./enums.js"; export type { Result } from "./fp.js"; +export type { PageIterator, Paginator } from "./operations.js"; +export { createPageIterator } from "./operations.js"; +export { RFCDate } from "./rfcdate.js"; diff --git a/src/types/streams.ts b/src/types/streams.ts new file mode 100644 index 0000000..a0163e7 --- /dev/null +++ b/src/types/streams.ts @@ -0,0 +1,21 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export function isReadableStream( + val: unknown, +): val is ReadableStream { + if (typeof val !== "object" || val === null) { + return false; + } + + // Check for the presence of methods specific to ReadableStream + const stream = val as ReadableStream; + + // ReadableStream has methods like getReader, cancel, and tee + return ( + typeof stream.getReader === "function" && + typeof stream.cancel === "function" && + typeof stream.tee === "function" + ); +}