From 749b45d1acc2c507c42a0624e1727456c5360341 Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Sat, 24 Aug 2024 01:15:26 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc , Speakeasy CLI 1.378.0 --- .speakeasy/workflow.lock | 8 +- finance/.gitignore | 2 + finance/.speakeasy/gen.lock | 26 +- finance/.speakeasy/gen.yaml | 2 +- finance/CONTRIBUTING.md | 26 + finance/FUNCTIONS.md | 102 +++ finance/README.md | 105 +++ finance/RELEASES.md | 10 +- finance/RUNTIMES.md | 2 +- finance/docs/lib/utils/retryconfig.md | 24 + finance/docs/models/components/errort.md | 10 + finance/docs/models/components/pet.md | 10 + .../docs/models/operations/listpetsrequest.md | 7 + .../models/operations/listpetsresponse.md | 15 + .../operations/listpetsresponseresult.md | 10 + .../models/operations/showpetbyidrequest.md | 9 + .../models/operations/showpetbyidresponse.md | 10 + finance/docs/sdks/financesdk/README.md | 6 +- finance/docs/sdks/pets/README.md | 102 ++- finance/jsr.json | 2 +- finance/package-lock.json | 17 +- finance/package.json | 3 +- finance/src/core.ts | 13 + finance/src/funcs/petsCreatePets.ts | 110 +++ finance/src/funcs/petsListPets.ts | 118 +++ finance/src/funcs/petsShowPetById.ts | 113 +++ finance/src/hooks/hooks.ts | 2 +- finance/src/hooks/index.ts | 2 +- finance/src/hooks/types.ts | 2 +- finance/src/index.ts | 2 +- finance/src/lib/base64.ts | 2 +- finance/src/lib/config.ts | 11 +- finance/src/lib/dlv.ts | 53 ++ finance/src/lib/encodings.ts | 32 +- finance/src/lib/http.ts | 693 +++++++----------- finance/src/lib/is-plain-object.ts | 2 +- finance/src/lib/logger.ts | 9 + finance/src/lib/matchers.ts | 308 ++++++++ finance/src/lib/primitives.ts | 2 +- finance/src/lib/retries.ts | 45 +- finance/src/lib/schemas.ts | 20 +- finance/src/lib/sdks.ts | 290 +++++++- finance/src/lib/security.ts | 2 +- finance/src/lib/url.ts | 2 +- finance/src/models/components/error.ts | 41 +- finance/src/models/components/index.ts | 2 +- finance/src/models/components/pet.ts | 47 +- finance/src/models/errors/httpclienterrors.ts | 62 ++ finance/src/models/errors/index.ts | 3 +- finance/src/models/errors/sdkerror.ts | 2 +- .../src/models/errors/sdkvalidationerror.ts | 16 +- finance/src/models/operations/index.ts | 2 +- finance/src/models/operations/listpets.ts | 147 ++-- finance/src/models/operations/showpetbyid.ts | 79 +- finance/src/sdk/index.ts | 2 +- finance/src/sdk/pets.ts | 159 +--- finance/src/sdk/sdk.ts | 31 +- finance/src/types/blobs.ts | 2 +- finance/src/types/constdatetime.ts | 15 + finance/src/types/enums.ts | 2 +- finance/src/types/fp.ts | 50 ++ finance/src/types/index.ts | 3 +- finance/src/types/operations.ts | 90 ++- finance/src/types/rfcdate.ts | 2 +- 64 files changed, 2214 insertions(+), 884 deletions(-) create mode 100644 finance/CONTRIBUTING.md create mode 100644 finance/FUNCTIONS.md create mode 100644 finance/docs/lib/utils/retryconfig.md create mode 100644 finance/src/core.ts create mode 100644 finance/src/funcs/petsCreatePets.ts create mode 100644 finance/src/funcs/petsListPets.ts create mode 100644 finance/src/funcs/petsShowPetById.ts create mode 100644 finance/src/lib/dlv.ts create mode 100644 finance/src/lib/logger.ts create mode 100644 finance/src/lib/matchers.ts create mode 100644 finance/src/models/errors/httpclienterrors.ts create mode 100644 finance/src/types/constdatetime.ts create mode 100644 finance/src/types/fp.ts diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock index 7540c5e..570937e 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -2,7 +2,7 @@ speakeasyVersion: 1.378.0 sources: source1: sourceNamespace: source-1 - sourceRevisionDigest: sha256:00d024558a05b3efdf72d1e2e3fbe7070c818b431d7f3f054b0418ba11990f53 + sourceRevisionDigest: sha256:429d7585fe3e0d880661c3f9df4fcb1705c94bf4bf705fd516aaa2a030a93dd1 sourceBlobDigest: sha256:7c35756702030633a8d2ebb1d378d34f883126319b06edcd798ac7bb2fddb189 tags: - latest @@ -17,9 +17,9 @@ targets: finance: source: source1 sourceNamespace: source-1 - sourceRevisionDigest: sha256:7888ff64b55debf12a4956f902014ac3b3915c2121d71e54dc098efe1baea462 - sourceBlobDigest: sha256:9aca1349a1b742af9714ce27e0b65a5a7a8e4672a57e9aba3580b520cbc83427 - outLocation: finance + sourceRevisionDigest: sha256:429d7585fe3e0d880661c3f9df4fcb1705c94bf4bf705fd516aaa2a030a93dd1 + sourceBlobDigest: sha256:7c35756702030633a8d2ebb1d378d34f883126319b06edcd798ac7bb2fddb189 + outLocation: ./finance lending: source: source1 sourceNamespace: source-1 diff --git a/finance/.gitignore b/finance/.gitignore index 9d9015a..b4c5e19 100644 --- a/finance/.gitignore +++ b/finance/.gitignore @@ -1,3 +1,5 @@ +/funcs +/core.* /models /models/errors /types diff --git a/finance/.speakeasy/gen.lock b/finance/.speakeasy/gen.lock index c11d7e2..a86c82d 100755 --- a/finance/.speakeasy/gen.lock +++ b/finance/.speakeasy/gen.lock @@ -3,10 +3,10 @@ id: 5b68364e-620c-4c04-8117-a75f11dd6079 management: docChecksum: 1bdb7a6f8bf3995d4b40475228403253 docVersion: 1.0.0 - speakeasyVersion: 1.326.0 - generationVersion: 2.359.0 - releaseVersion: 0.0.3 - configChecksum: faccd0b9715040230ee64732c925d97e + speakeasyVersion: 1.378.0 + generationVersion: 2.404.3 + releaseVersion: 0.1.0 + configChecksum: c77aaece2b35f042875d813684c7a3a2 repoURL: https://github.com/ryan-timothy-albert/sample-ts-monorepo.git repoSubDirectory: finance installationURL: https://gitpkg.now.sh/ryan-timothy-albert/sample-ts-monorepo/finance @@ -14,25 +14,36 @@ management: features: typescript: additionalDependencies: 0.1.0 - core: 3.11.0 + core: 3.14.1 + defaultEnabledRetries: 0.1.0 + envVarSecurityUsage: 0.1.1 globalSecurityCallbacks: 0.1.0 globalServerURLs: 2.82.4 responseFormat: 0.2.3 + retries: 2.83.0 sdkHooks: 0.1.0 generatedFiles: + - src/funcs/petsListPets.ts + - src/funcs/petsCreatePets.ts + - src/funcs/petsShowPetById.ts - src/sdk/pets.ts - src/sdk/sdk.ts - .eslintrc.cjs - .npmignore + - FUNCTIONS.md - RUNTIMES.md - jsr.json - package.json + - src/core.ts - src/index.ts - src/lib/base64.ts - src/lib/config.ts + - src/lib/dlv.ts - src/lib/encodings.ts - src/lib/http.ts - src/lib/is-plain-object.ts + - src/lib/logger.ts + - src/lib/matchers.ts - src/lib/primitives.ts - src/lib/retries.ts - src/lib/schemas.ts @@ -40,10 +51,13 @@ generatedFiles: - src/lib/security.ts - src/lib/url.ts - src/sdk/index.ts + - src/models/errors/httpclienterrors.ts - src/models/errors/sdkerror.ts - src/models/errors/sdkvalidationerror.ts - src/types/blobs.ts + - src/types/constdatetime.ts - src/types/enums.ts + - src/types/fp.ts - src/types/index.ts - src/types/operations.ts - src/types/rfcdate.ts @@ -63,9 +77,11 @@ generatedFiles: - docs/models/components/pet.md - docs/models/components/errort.md - docs/sdks/financesdk/README.md + - docs/lib/utils/retryconfig.md - docs/sdks/pets/README.md - USAGE.md - .gitattributes - src/hooks/hooks.ts - src/hooks/types.ts - src/hooks/index.ts + - CONTRIBUTING.md diff --git a/finance/.speakeasy/gen.yaml b/finance/.speakeasy/gen.yaml index 8f448f3..b8cbcd7 100644 --- a/finance/.speakeasy/gen.yaml +++ b/finance/.speakeasy/gen.yaml @@ -12,7 +12,7 @@ generation: auth: oAuth2ClientCredentialsEnabled: true typescript: - version: 0.0.3 + version: 0.1.0 additionalDependencies: dependencies: {} devDependencies: {} diff --git a/finance/CONTRIBUTING.md b/finance/CONTRIBUTING.md new file mode 100644 index 0000000..d585717 --- /dev/null +++ b/finance/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing to This Repository + +Thank you for your interest in contributing to this repository. Please note that this repository contains generated code. As such, we do not accept direct changes or pull requests. Instead, we encourage you to follow the guidelines below to report issues and suggest improvements. + +## How to Report Issues + +If you encounter any bugs or have suggestions for improvements, please open an issue on GitHub. When reporting an issue, please provide as much detail as possible to help us reproduce the problem. This includes: + +- A clear and descriptive title +- Steps to reproduce the issue +- Expected and actual behavior +- Any relevant logs, screenshots, or error messages +- Information about your environment (e.g., operating system, software versions) + - For example can be collected using the `npx envinfo` command from your terminal if you have Node.js installed + +## Issue Triage and Upstream Fixes + +We will review and triage issues as quickly as possible. Our goal is to address bugs and incorporate improvements in the upstream source code. Fixes will be included in the next generation of the generated code. + +## Contact + +If you have any questions or need further assistance, please feel free to reach out by opening an issue. + +Thank you for your understanding and cooperation! + +The Maintainers diff --git a/finance/FUNCTIONS.md b/finance/FUNCTIONS.md new file mode 100644 index 0000000..af46a2e --- /dev/null +++ b/finance/FUNCTIONS.md @@ -0,0 +1,102 @@ +# Standalone Functions + +> [!NOTE] +> This section is useful if you are using a bundler and targetting browsers and +> runtimes where the size of an application affects performance and load times. + +Every method in this SDK is also available as a standalone function. This +alternative API is suitable when targetting the browser or serverless runtimes +and using a bundler to build your application since all unused functionality +will be tree-shaken away. This includes code for unused methods, Zod schemas, +encoding helpers and response handlers. The result is dramatically smaller +impact on the application's final bundle size which grows very slowly as you use +more and more functionality from this SDK. + +Calling methods through the main SDK class remains a valid and generally more +more ergonomic option. Standalone functions represent an optimisation for a +specific category of applications. + +## Example + +```typescript +import { FinanceSDKCore } from "ryan-finance/core.js"; +import { petsListPets } from "ryan-finance/funcs/petsListPets.js"; +import { SDKValidationError } from "ryan-finance/models/errors/sdkvalidationerror.js"; + +// Use `FinanceSDKCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const financeSDK = new FinanceSDKCore(); + +async function run() { + const res = await petsListPets(financeSDK, {}); + + switch (true) { + case res.ok: + // The success case will be handled outside of the switch block + break; + case res.error instanceof SDKValidationError: + // Pretty-print validation errors. + return console.log(res.error.pretty()); + case res.error instanceof Error: + return console.log(res.error); + default: + // TypeScript's type checking will fail on the following line if the above + // cases were not exhaustive. + res.error satisfies never; + throw new Error("Assertion failed: expected error checks to be exhaustive: " + res.error); + } + + + const { value: result } = res; + + // Handle the result + console.log(result) +} + +run(); +``` + +## Result types + +Standalone functions differ from SDK methods in that they return a +`Result` type to capture _known errors_ and document them using +the type system. By avoiding throwing errors, application code maintains clear +control flow and error-handling become part of the regular flow of application +code. + +> We use the term "known errors" because standalone functions, and JavaScript +> code in general, can still throw unexpected errors such as `TypeError`s, +> `RangeError`s and `DOMException`s. Exhaustively catching all errors may be +> something this SDK addresses in the future. Nevertheless, there is still a lot +> of benefit from capturing most errors and turning them into values. + +The second reason for this style of programming is because these functions will +typically be used in front-end applications where exception throwing is +sometimes discouraged or considered unidiomatic. React and similar ecosystems +and libraries tend to promote this style of programming so that components +render useful content under all states (loading, success, error and so on). + +The general pattern when calling standalone functions looks like this: + +```typescript +import { Core } from ""; +import { fetchSomething } from "/funcs/fetchSomething.js"; + +const client = new Core(); + +async function run() { + const result = await fetchSomething(client, { id: "123" }); + if (!result.ok) { + // You can throw the error or handle it. It's your choice now. + throw result.error; + } + + console.log(result.value); +} + +run(); +``` + +Notably, `result.error` above will have an explicit type compared to a try-catch +variation where the error in the catch block can only be of type `unknown` (or +`any` depending on your TypeScript settings). \ No newline at end of file diff --git a/finance/README.md b/finance/README.md index 2470a15..3cf2a90 100644 --- a/finance/README.md +++ b/finance/README.md @@ -233,6 +233,111 @@ const sdk = new FinanceSDK({ httpClient }); ``` + +## Standalone functions + +All the methods listed above are available as standalone functions. These +functions are ideal for use in applications running in the browser, serverless +runtimes or other environments where application bundle size is a primary +concern. When using a bundler to build your application, all unused +functionality will be either excluded from the final bundle or tree-shaken away. + +To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md). + +
+ +Available standalone functions + +- [petsCreatePets](docs/sdks/pets/README.md#createpets) +- [petsListPets](docs/sdks/pets/README.md#listpets) +- [petsShowPetById](docs/sdks/pets/README.md#showpetbyid) + + +
+ + + +## Retries + +Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK. + +To change the default retry strategy for a single API call, simply provide a retryConfig object to the call: +```typescript +import { FinanceSDK } from "ryan-finance"; + +const financeSDK = new FinanceSDK(); + +async function run() { + const result = await financeSDK.pets.listPets( + {}, + { + retries: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, + } + ); + + // Handle the result + console.log(result); +} + +run(); + +``` + +If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization: +```typescript +import { FinanceSDK } from "ryan-finance"; + +const financeSDK = new FinanceSDK({ + retryConfig: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, +}); + +async function run() { + const result = await financeSDK.pets.listPets({}); + + // Handle the result + console.log(result); +} + +run(); + +``` + + + +## Debugging + +You can setup your SDK to emit debug logs for SDK requests and responses. + +You can pass a logger that matches `console`'s interface as an SDK option. + +> [!WARNING] +> Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production. + +```typescript +import { FinanceSDK } from "ryan-finance"; + +const sdk = new FinanceSDK({ debugLogger: console }); +``` + + # Development diff --git a/finance/RELEASES.md b/finance/RELEASES.md index ef7057e..36fbcfb 100644 --- a/finance/RELEASES.md +++ b/finance/RELEASES.md @@ -8,4 +8,12 @@ Based on: ### Generated - [typescript v0.0.3] finance ### Releases -- [NPM v0.0.3] https://www.npmjs.com/package/ryan-finance/v/0.0.3 - finance \ No newline at end of file +- [NPM v0.0.3] https://www.npmjs.com/package/ryan-finance/v/0.0.3 - finance + +## 2024-08-24 01:14:59 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.378.0 (2.404.3) https://github.com/speakeasy-api/speakeasy +### Generated +- [typescript v0.1.0] finance \ No newline at end of file diff --git a/finance/RUNTIMES.md b/finance/RUNTIMES.md index 71fa3da..d08a0c0 100644 --- a/finance/RUNTIMES.md +++ b/finance/RUNTIMES.md @@ -3,7 +3,7 @@ This SDK is intended to be used in JavaScript runtimes that support the following features: * [Web Fetch API][web-fetch] -* [Web Streams API](web-streams) and in particular `ReadableStream` +* [Web Streams API][web-streams] and in particular `ReadableStream` * [Async iterables][async-iter] using `Symbol.asyncIterator` [web-fetch]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API diff --git a/finance/docs/lib/utils/retryconfig.md b/finance/docs/lib/utils/retryconfig.md new file mode 100644 index 0000000..08f95f4 --- /dev/null +++ b/finance/docs/lib/utils/retryconfig.md @@ -0,0 +1,24 @@ +# RetryConfig + +Allows customizing the default retry configuration. It is only permitted in methods that accept retry policies. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------ | ----------- | +| `strategy` | `"backoff" | "none"` | The retry strategy to use. | `"backoff"` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | When strategy is "backoff", this configurates for the backoff parameters. | | +| `retryConnectionErrors` | `*boolean*` | When strategy is "backoff", this determines whether or not to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | ------------ | ----------------------------------------- | -------- | +| `initialInterval` | `*number*` | The initial interval in milliseconds. | `500` | +| `maxInterval` | `*number*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*number*` | The exponent to use for the backoff. | `1.5` | +| `maxElapsedTime` | `*number*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/finance/docs/models/components/errort.md b/finance/docs/models/components/errort.md index 582ea2c..82bf5c4 100644 --- a/finance/docs/models/components/errort.md +++ b/finance/docs/models/components/errort.md @@ -1,5 +1,15 @@ # ErrorT +## Example Usage + +```typescript +import { ErrorT } from "ryan-finance/models/components"; + +let value: ErrorT = { + code: 847252, + message: "", +}; +``` ## Fields diff --git a/finance/docs/models/components/pet.md b/finance/docs/models/components/pet.md index f4d881f..143c526 100644 --- a/finance/docs/models/components/pet.md +++ b/finance/docs/models/components/pet.md @@ -1,5 +1,15 @@ # Pet +## Example Usage + +```typescript +import { Pet } from "ryan-finance/models/components"; + +let value: Pet = { + id: 544883, + name: "", +}; +``` ## Fields diff --git a/finance/docs/models/operations/listpetsrequest.md b/finance/docs/models/operations/listpetsrequest.md index 97ebaa9..a249c13 100644 --- a/finance/docs/models/operations/listpetsrequest.md +++ b/finance/docs/models/operations/listpetsrequest.md @@ -1,5 +1,12 @@ # ListPetsRequest +## Example Usage + +```typescript +import { ListPetsRequest } from "ryan-finance/models/operations"; + +let value: ListPetsRequest = {}; +``` ## Fields diff --git a/finance/docs/models/operations/listpetsresponse.md b/finance/docs/models/operations/listpetsresponse.md index ce3194a..74ccabd 100644 --- a/finance/docs/models/operations/listpetsresponse.md +++ b/finance/docs/models/operations/listpetsresponse.md @@ -1,5 +1,20 @@ # ListPetsResponse +## Example Usage + +```typescript +import { ListPetsResponse } from "ryan-finance/models/operations"; + +let value: ListPetsResponse = { + headers: { + key: [""], + }, + result: { + code: 844266, + message: "", + }, +}; +``` ## Fields diff --git a/finance/docs/models/operations/listpetsresponseresult.md b/finance/docs/models/operations/listpetsresponseresult.md index dfbd55a..6494030 100644 --- a/finance/docs/models/operations/listpetsresponseresult.md +++ b/finance/docs/models/operations/listpetsresponseresult.md @@ -1,5 +1,15 @@ # ListPetsResponseResult +## Example Usage + +```typescript +import { ListPetsResponseResult } from "ryan-finance/models/operations"; + +let value: ListPetsResponseResult = { + code: 592845, + message: "", +}; +``` ## Supported Types diff --git a/finance/docs/models/operations/showpetbyidrequest.md b/finance/docs/models/operations/showpetbyidrequest.md index cc75c5f..883bcb3 100644 --- a/finance/docs/models/operations/showpetbyidrequest.md +++ b/finance/docs/models/operations/showpetbyidrequest.md @@ -1,5 +1,14 @@ # ShowPetByIdRequest +## Example Usage + +```typescript +import { ShowPetByIdRequest } from "ryan-finance/models/operations"; + +let value: ShowPetByIdRequest = { + petId: "", +}; +``` ## Fields diff --git a/finance/docs/models/operations/showpetbyidresponse.md b/finance/docs/models/operations/showpetbyidresponse.md index 50868ef..9c5893c 100644 --- a/finance/docs/models/operations/showpetbyidresponse.md +++ b/finance/docs/models/operations/showpetbyidresponse.md @@ -1,5 +1,15 @@ # ShowPetByIdResponse +## Example Usage + +```typescript +import { ShowPetByIdResponse } from "ryan-finance/models/operations"; + +let value: ShowPetByIdResponse = { + code: 857946, + message: "", +}; +``` ## Supported Types diff --git a/finance/docs/sdks/financesdk/README.md b/finance/docs/sdks/financesdk/README.md index d390c64..1fccd1d 100644 --- a/finance/docs/sdks/financesdk/README.md +++ b/finance/docs/sdks/financesdk/README.md @@ -1,7 +1,3 @@ # FinanceSDK - -## Overview - -### Available Operations - +## Overview \ No newline at end of file diff --git a/finance/docs/sdks/pets/README.md b/finance/docs/sdks/pets/README.md index 13b5278..a42c864 100644 --- a/finance/docs/sdks/pets/README.md +++ b/finance/docs/sdks/pets/README.md @@ -1,6 +1,8 @@ # Pets (*pets*) +## Overview + ### Available Operations * [listPets](#listpets) - List all pets @@ -28,6 +30,34 @@ async function run() { run(); ``` +### Standalone function + +The standalone function version of this method: + +```typescript +import { FinanceSDKCore } from "ryan-finance/core.js"; +import { petsListPets } from "ryan-finance/funcs/petsListPets.js"; + +// Use `FinanceSDKCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const financeSDK = new FinanceSDKCore(); + +async function run() { + const res = await petsListPets(financeSDK, {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result) +} + +run(); +``` + ### Parameters | Parameter | Type | Required | Description | @@ -35,17 +65,19 @@ run(); | `request` | [operations.ListPetsRequest](../../models/operations/listpetsrequest.md) | :heavy_check_mark: | The request object to use for the request. | | `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | | `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | - +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | ### Response **Promise\<[operations.ListPetsResponse](../../models/operations/listpetsresponse.md)\>** + ### Errors | Error Object | Status Code | Content Type | | --------------- | --------------- | --------------- | | errors.SDKError | 4xx-5xx | */* | + ## createPets Create a pet @@ -70,6 +102,37 @@ async function run() { run(); ``` +### Standalone function + +The standalone function version of this method: + +```typescript +import { FinanceSDKCore } from "ryan-finance/core.js"; +import { petsCreatePets } from "ryan-finance/funcs/petsCreatePets.js"; + +// Use `FinanceSDKCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const financeSDK = new FinanceSDKCore(); + +async function run() { + const res = await petsCreatePets(financeSDK, { + id: 589113, + name: "", + }); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result) +} + +run(); +``` + ### Parameters | Parameter | Type | Required | Description | @@ -77,17 +140,19 @@ run(); | `request` | [components.Pet](../../models/components/pet.md) | :heavy_check_mark: | The request object to use for the request. | | `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | | `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | - +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | ### Response **Promise\<[components.ErrorT](../../models/components/errort.md)\>** + ### Errors | Error Object | Status Code | Content Type | | --------------- | --------------- | --------------- | | errors.SDKError | 4xx-5xx | */* | + ## showPetById Info for a specific pet @@ -111,6 +176,36 @@ async function run() { run(); ``` +### Standalone function + +The standalone function version of this method: + +```typescript +import { FinanceSDKCore } from "ryan-finance/core.js"; +import { petsShowPetById } from "ryan-finance/funcs/petsShowPetById.js"; + +// Use `FinanceSDKCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const financeSDK = new FinanceSDKCore(); + +async function run() { + const res = await petsShowPetById(financeSDK, { + petId: "", + }); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result) +} + +run(); +``` + ### Parameters | Parameter | Type | Required | Description | @@ -118,11 +213,12 @@ run(); | `request` | [operations.ShowPetByIdRequest](../../models/operations/showpetbyidrequest.md) | :heavy_check_mark: | The request object to use for the request. | | `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | | `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | - +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | ### Response **Promise\<[operations.ShowPetByIdResponse](../../models/operations/showpetbyidresponse.md)\>** + ### Errors | Error Object | Status Code | Content Type | diff --git a/finance/jsr.json b/finance/jsr.json index cd2ccea..f6e57d5 100644 --- a/finance/jsr.json +++ b/finance/jsr.json @@ -2,7 +2,7 @@ { "name": "ryan-finance", - "version": "0.0.3", + "version": "0.1.0", "exports": { ".": "./src/index.ts", "./models/errors": "./src/models/errors/index.ts", diff --git a/finance/package-lock.json b/finance/package-lock.json index abc2af6..d385349 100644 --- a/finance/package-lock.json +++ b/finance/package-lock.json @@ -1,14 +1,13 @@ { "name": "ryan-finance", - "version": "0.0.3", + "version": "0.1.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "ryan-finance", - "version": "0.0.3", + "version": "0.1.0", "devDependencies": { - "@types/jsonpath": "^0.2.4", "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", "eslint": "^8.57.0", @@ -197,12 +196,6 @@ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true }, - "node_modules/@types/jsonpath": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/@types/jsonpath/-/jsonpath-0.2.4.tgz", - "integrity": "sha512-K3hxB8Blw0qgW6ExKgMbXQv2UPZBoE2GqLpVY+yr7nMD2Pq86lsuIzyAaiQ7eMqFL5B6di6pxSkogLJEyEHoGA==", - "dev": true - }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.15.0.tgz", @@ -3216,12 +3209,6 @@ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true }, - "@types/jsonpath": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/@types/jsonpath/-/jsonpath-0.2.4.tgz", - "integrity": "sha512-K3hxB8Blw0qgW6ExKgMbXQv2UPZBoE2GqLpVY+yr7nMD2Pq86lsuIzyAaiQ7eMqFL5B6di6pxSkogLJEyEHoGA==", - "dev": true - }, "@typescript-eslint/eslint-plugin": { "version": "7.15.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.15.0.tgz", diff --git a/finance/package.json b/finance/package.json index 218cdb5..79f4f41 100644 --- a/finance/package.json +++ b/finance/package.json @@ -1,6 +1,6 @@ { "name": "ryan-finance", - "version": "0.0.3", + "version": "0.1.0", "author": "ryan-timothy-albert", "main": "./index.js", "sideEffects": false, @@ -18,7 +18,6 @@ "zod": ">= 3" }, "devDependencies": { - "@types/jsonpath": "^0.2.4", "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", "eslint": "^8.57.0", diff --git a/finance/src/core.ts b/finance/src/core.ts new file mode 100644 index 0000000..2381e82 --- /dev/null +++ b/finance/src/core.ts @@ -0,0 +1,13 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ClientSDK } from "./lib/sdks.js"; + +/** + * A minimal client to use when calling standalone SDK functions. Typically, an + * instance of this class would be instantiated once at the start of an + * application and passed around through some dependency injection mechanism to + * parts of an application that need to make SDK calls. + */ +export class FinanceSDKCore extends ClientSDK {} diff --git a/finance/src/funcs/petsCreatePets.ts b/finance/src/funcs/petsCreatePets.ts new file mode 100644 index 0000000..7a89217 --- /dev/null +++ b/finance/src/funcs/petsCreatePets.ts @@ -0,0 +1,110 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { FinanceSDKCore } 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 { RequestOptions } from "../lib/sdks.js"; +import { pathToFunc } from "../lib/url.js"; +import * as components from "../models/components/index.js"; +import { + 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"; + +/** + * Create a pet + */ +export async function petsCreatePets( + client$: FinanceSDKCore, + request: components.Pet, + options?: RequestOptions +): Promise< + Result< + components.ErrorT | undefined, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input$ = request; + + 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("/pets")(); + + const headers$ = new Headers({ + "Content-Type": "application/json", + Accept: "application/json", + }); + + const context = { operationID: "createPets", oAuth2Scopes: [], securitySource: null }; + + const requestRes = client$.createRequest$( + context, + { + 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$(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.ErrorT | undefined, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + m$.nil(201, components.ErrorT$inboundSchema.optional()), + m$.fail(["4XX", "5XX"]), + m$.json("default", components.ErrorT$inboundSchema.optional()) + )(response); + if (!result$.ok) { + return result$; + } + + return result$; +} diff --git a/finance/src/funcs/petsListPets.ts b/finance/src/funcs/petsListPets.ts new file mode 100644 index 0000000..be17de8 --- /dev/null +++ b/finance/src/funcs/petsListPets.ts @@ -0,0 +1,118 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { FinanceSDKCore } 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 { RequestOptions } from "../lib/sdks.js"; +import { pathToFunc } from "../lib/url.js"; +import { + 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"; + +/** + * List all pets + */ +export async function petsListPets( + client$: FinanceSDKCore, + request: operations.ListPetsRequest, + options?: RequestOptions +): Promise< + Result< + operations.ListPetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input$ = typeof request === "undefined" ? {} : request; + + const parsed$ = schemas$.safeParse( + input$, + (value$) => operations.ListPetsRequest$outboundSchema.parse(value$), + "Input validation failed" + ); + if (!parsed$.ok) { + return parsed$; + } + const payload$ = parsed$.value; + const body$ = null; + + const path$ = pathToFunc("/pets")(); + + const query$ = encodeFormQuery$({ + limit: payload$.limit, + }); + + const headers$ = new Headers({ + Accept: "application/json", + }); + + const context = { operationID: "listPets", oAuth2Scopes: [], securitySource: null }; + + const requestRes = client$.createRequest$( + context, + { + 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$(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 responseFields$ = { + HttpMeta: { Response: response, Request: request$ }, + }; + + const [result$] = await m$.match< + operations.ListPetsResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + m$.json(200, operations.ListPetsResponse$inboundSchema, { hdrs: true, key: "Result" }), + m$.fail(["4XX", "5XX"]), + m$.json("default", operations.ListPetsResponse$inboundSchema, { key: "Result" }) + )(response, { extraFields: responseFields$ }); + if (!result$.ok) { + return result$; + } + + return result$; +} diff --git a/finance/src/funcs/petsShowPetById.ts b/finance/src/funcs/petsShowPetById.ts new file mode 100644 index 0000000..afe6216 --- /dev/null +++ b/finance/src/funcs/petsShowPetById.ts @@ -0,0 +1,113 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { FinanceSDKCore } 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 { RequestOptions } from "../lib/sdks.js"; +import { pathToFunc } from "../lib/url.js"; +import { + 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"; + +/** + * Info for a specific pet + */ +export async function petsShowPetById( + client$: FinanceSDKCore, + request: operations.ShowPetByIdRequest, + options?: RequestOptions +): Promise< + Result< + operations.ShowPetByIdResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input$ = request; + + const parsed$ = schemas$.safeParse( + input$, + (value$) => operations.ShowPetByIdRequest$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 path$ = pathToFunc("/pets/{petId}")(pathParams$); + + const headers$ = new Headers({ + Accept: "application/json", + }); + + const context = { operationID: "showPetById", oAuth2Scopes: [], securitySource: null }; + + const requestRes = client$.createRequest$( + context, + { + 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$(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< + operations.ShowPetByIdResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + m$.json(200, operations.ShowPetByIdResponse$inboundSchema), + m$.fail(["4XX", "5XX"]), + m$.json("default", operations.ShowPetByIdResponse$inboundSchema) + )(response); + if (!result$.ok) { + return result$; + } + + return result$; +} diff --git a/finance/src/hooks/hooks.ts b/finance/src/hooks/hooks.ts index 6a1e31e..a6b6e17 100644 --- a/finance/src/hooks/hooks.ts +++ b/finance/src/hooks/hooks.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { RequestInput } from "../lib/http.js"; diff --git a/finance/src/hooks/index.ts b/finance/src/hooks/index.ts index d5fdd74..8f0e4db 100644 --- a/finance/src/hooks/index.ts +++ b/finance/src/hooks/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export * from "./types.js"; diff --git a/finance/src/hooks/types.ts b/finance/src/hooks/types.ts index dd23b02..3a31914 100644 --- a/finance/src/hooks/types.ts +++ b/finance/src/hooks/types.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { HTTPClient, RequestInput } from "../lib/http.js"; diff --git a/finance/src/index.ts b/finance/src/index.ts index 8bc6ae3..ceb6380 100644 --- a/finance/src/index.ts +++ b/finance/src/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export * from "./sdk/sdk.js"; diff --git a/finance/src/lib/base64.ts b/finance/src/lib/base64.ts index cda0764..c2d5b38 100644 --- a/finance/src/lib/base64.ts +++ b/finance/src/lib/base64.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as z from "zod"; diff --git a/finance/src/lib/config.ts b/finance/src/lib/config.ts index 9a2904b..4d5f751 100644 --- a/finance/src/lib/config.ts +++ b/finance/src/lib/config.ts @@ -1,8 +1,9 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { HTTPClient } from "./http.js"; +import { Logger } from "./logger.js"; import { RetryConfig } from "./retries.js"; import { Params, pathToFunc } from "./url.js"; @@ -25,6 +26,8 @@ export type SDKOptions = { * Allows overriding the default retry config used by the SDK */ retryConfig?: RetryConfig; + timeoutMs?: number; + debugLogger?: Logger; }; export function serverURLFromOptions(options: SDKOptions): URL | null { @@ -47,7 +50,7 @@ export function serverURLFromOptions(options: SDKOptions): URL | null { export const SDK_METADATA = { language: "typescript", openapiDocVersion: "1.0.0", - sdkVersion: "0.0.3", - genVersion: "2.359.0", - userAgent: "speakeasy-sdk/typescript 0.0.3 2.359.0 1.0.0 ryan-finance", + sdkVersion: "0.1.0", + genVersion: "2.404.3", + userAgent: "speakeasy-sdk/typescript 0.1.0 2.404.3 1.0.0 ryan-finance", } as const; diff --git a/finance/src/lib/dlv.ts b/finance/src/lib/dlv.ts new file mode 100644 index 0000000..e81091f --- /dev/null +++ b/finance/src/lib/dlv.ts @@ -0,0 +1,53 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/* +MIT License + +Copyright (c) 2024 Jason Miller (http://jasonformat.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/** + * @param obj The object to walk + * @param key The key path to walk the object with + * @param def A default value to return if the result is undefined + * + * @example + * dlv(obj, "a.b.c.d") + * @example + * dlv(object, ["a", "b", "c", "d"]) + * @example + * dlv(object, "foo.bar.baz", "Hello, default value!") + */ +export function dlv( + obj: any, + key: string | string[], + def?: T, + p?: number, + undef?: never, +): T | undefined { + key = Array.isArray(key) ? key : key.split("."); + for (p = 0; p < key.length; p++) { + const k = key[p]; + obj = k != null && obj ? obj[k] : undef; + } + return obj === undef ? def : obj; +} diff --git a/finance/src/lib/encodings.ts b/finance/src/lib/encodings.ts index 49f536b..44fa728 100644 --- a/finance/src/lib/encodings.ts +++ b/finance/src/lib/encodings.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { bytesToBase64 } from "./base64.js"; @@ -212,6 +212,24 @@ export function encodeDeepObject( return ""; } + if (!isPlainObject(value)) { + throw new EncodingError( + `Value of parameter '${key}' which uses deepObject encoding must be an object`, + ); + } + + return encodeDeepObjectObject(key, value, options); +} + +export function encodeDeepObjectObject( + key: string, + value: unknown, + options?: { charEncoding?: "percent" | "none" }, +): string { + if (value == null) { + return ""; + } + let out = ""; const encodeString = (v: string) => { @@ -219,9 +237,7 @@ export function encodeDeepObject( }; if (!isPlainObject(value)) { - throw new EncodingError( - `Value of parameter '${key}' which uses deepObject encoding must be an object`, - ); + throw new EncodingError(`Expected parameter '${key}' to be an object.`); } Object.entries(value).forEach(([ck, cv]) => { @@ -232,9 +248,11 @@ export function encodeDeepObject( const pk = `${key}[${ck}]`; if (isPlainObject(cv)) { - throw new EncodingError( - `Value of parameter field '${pk}' cannot be an array or object.`, - ); + const objOut = encodeDeepObjectObject(pk, cv, options); + + out += `&${objOut}`; + + return; } const pairs: unknown[] = Array.isArray(cv) ? cv : [cv]; diff --git a/finance/src/lib/http.ts b/finance/src/lib/http.ts index 7c5107a..13cf1fd 100644 --- a/finance/src/lib/http.ts +++ b/finance/src/lib/http.ts @@ -1,41 +1,39 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { never as znever } from "zod"; -import { parse } from "./schemas.js"; -import { isPlainObject } from "./is-plain-object.js"; -import { SDKError } from "../models/errors/sdkerror.js"; - -export type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise; +export type Fetcher = ( + input: RequestInfo | URL, + init?: RequestInit, +) => Promise; export type Awaitable = T | Promise; const DEFAULT_FETCHER: Fetcher = (input, init) => { - // If input is a Request and init is undefined, Bun will discard the method, - // headers, body and other options that were set on the request object. - // Node.js and browers would ignore an undefined init value. This check is - // therefore needed for interop with Bun. - if (init == null) { - return fetch(input); - } else { - return fetch(input, init); - } + // If input is a Request and init is undefined, Bun will discard the method, + // headers, body and other options that were set on the request object. + // Node.js and browers would ignore an undefined init value. This check is + // therefore needed for interop with Bun. + if (init == null) { + return fetch(input); + } else { + return fetch(input, init); + } }; export type RequestInput = { - /** - * The URL the request will use. - */ - url: URL; - /** - * Options used to create a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). - */ - options?: RequestInit | undefined; + /** + * The URL the request will use. + */ + url: URL; + /** + * Options used to create a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + */ + options?: RequestInit | undefined; }; export interface HTTPClientOptions { - fetcher?: Fetcher; + fetcher?: Fetcher; } export type BeforeRequestHook = (req: Request) => Awaitable; @@ -43,114 +41,114 @@ export type RequestErrorHook = (err: unknown, req: Request) => Awaitable; export type ResponseHook = (res: Response, req: Request) => Awaitable; export class HTTPClient { - private fetcher: Fetcher; - private requestHooks: BeforeRequestHook[] = []; - private requestErrorHooks: RequestErrorHook[] = []; - private responseHooks: ResponseHook[] = []; - - constructor(private options: HTTPClientOptions = {}) { - this.fetcher = options.fetcher || DEFAULT_FETCHER; + private fetcher: Fetcher; + private requestHooks: BeforeRequestHook[] = []; + private requestErrorHooks: RequestErrorHook[] = []; + private responseHooks: ResponseHook[] = []; + + constructor(private options: HTTPClientOptions = {}) { + this.fetcher = options.fetcher || DEFAULT_FETCHER; + } + + async request(request: Request): Promise { + let req = request; + for (const hook of this.requestHooks) { + const nextRequest = await hook(req); + if (nextRequest) { + req = nextRequest; + } } - async request(request: Request): Promise { - let req = request; - for (const hook of this.requestHooks) { - const nextRequest = await hook(req); - if (nextRequest) { - req = nextRequest; - } - } - - try { - const res = await this.fetcher(req); - - for (const hook of this.responseHooks) { - await hook(res, req); - } - - return res; - } catch (err) { - for (const hook of this.requestErrorHooks) { - await hook(err, req); - } - - throw err; - } - } + try { + const res = await this.fetcher(req); + + for (const hook of this.responseHooks) { + await hook(res, req); + } + + return res; + } catch (err) { + for (const hook of this.requestErrorHooks) { + await hook(err, req); + } - /** - * Registers a hook that is called before a request is made. The hook function - * can mutate the request or return a new request. This may be useful to add - * additional information to request such as request IDs and tracing headers. - */ - addHook(hook: "beforeRequest", fn: BeforeRequestHook): this; - /** - * Registers a hook that is called when a request cannot be made due to a - * network error. - */ - addHook(hook: "requestError", fn: RequestErrorHook): this; - /** - * Registers a hook that is called when a response has been received from the - * server. - */ - addHook(hook: "response", fn: ResponseHook): this; - addHook( - ...args: - | [hook: "beforeRequest", fn: BeforeRequestHook] - | [hook: "requestError", fn: RequestErrorHook] - | [hook: "response", fn: ResponseHook] - ) { - if (args[0] === "beforeRequest") { - this.requestHooks.push(args[1]); - } else if (args[0] === "requestError") { - this.requestErrorHooks.push(args[1]); - } else if (args[0] === "response") { - this.responseHooks.push(args[1]); - } else { - throw new Error(`Invalid hook type: ${args[0]}`); - } - return this; + throw err; + } + } + + /** + * Registers a hook that is called before a request is made. The hook function + * can mutate the request or return a new request. This may be useful to add + * additional information to request such as request IDs and tracing headers. + */ + addHook(hook: "beforeRequest", fn: BeforeRequestHook): this; + /** + * Registers a hook that is called when a request cannot be made due to a + * network error. + */ + addHook(hook: "requestError", fn: RequestErrorHook): this; + /** + * Registers a hook that is called when a response has been received from the + * server. + */ + addHook(hook: "response", fn: ResponseHook): this; + addHook( + ...args: + | [hook: "beforeRequest", fn: BeforeRequestHook] + | [hook: "requestError", fn: RequestErrorHook] + | [hook: "response", fn: ResponseHook] + ) { + if (args[0] === "beforeRequest") { + this.requestHooks.push(args[1]); + } else if (args[0] === "requestError") { + this.requestErrorHooks.push(args[1]); + } else if (args[0] === "response") { + this.responseHooks.push(args[1]); + } else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + return this; + } + + /** Removes a hook that was previously registered with `addHook`. */ + removeHook(hook: "beforeRequest", fn: BeforeRequestHook): this; + /** Removes a hook that was previously registered with `addHook`. */ + removeHook(hook: "requestError", fn: RequestErrorHook): this; + /** Removes a hook that was previously registered with `addHook`. */ + removeHook(hook: "response", fn: ResponseHook): this; + removeHook( + ...args: + | [hook: "beforeRequest", fn: BeforeRequestHook] + | [hook: "requestError", fn: RequestErrorHook] + | [hook: "response", fn: ResponseHook] + ): this { + let target: unknown[]; + if (args[0] === "beforeRequest") { + target = this.requestHooks; + } else if (args[0] === "requestError") { + target = this.requestErrorHooks; + } else if (args[0] === "response") { + target = this.responseHooks; + } else { + throw new Error(`Invalid hook type: ${args[0]}`); } - /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "beforeRequest", fn: BeforeRequestHook): this; - /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "requestError", fn: RequestErrorHook): this; - /** Removes a hook that was previously registered with `addHook`. */ - removeHook(hook: "response", fn: ResponseHook): this; - removeHook( - ...args: - | [hook: "beforeRequest", fn: BeforeRequestHook] - | [hook: "requestError", fn: RequestErrorHook] - | [hook: "response", fn: ResponseHook] - ): this { - let target: unknown[]; - if (args[0] === "beforeRequest") { - target = this.requestHooks; - } else if (args[0] === "requestError") { - target = this.requestErrorHooks; - } else if (args[0] === "response") { - target = this.responseHooks; - } else { - throw new Error(`Invalid hook type: ${args[0]}`); - } - - const index = target.findIndex((v) => v === args[1]); - if (index >= 0) { - target.splice(index, 1); - } - - return this; + const index = target.findIndex((v) => v === args[1]); + if (index >= 0) { + target.splice(index, 1); } - clone(): HTTPClient { - const child = new HTTPClient(this.options); - child.requestHooks = this.requestHooks.slice(); - child.requestErrorHooks = this.requestErrorHooks.slice(); - child.responseHooks = this.responseHooks.slice(); + return this; + } - return child; - } + clone(): HTTPClient { + const child = new HTTPClient(this.options); + child.requestHooks = this.requestHooks.slice(); + child.requestErrorHooks = this.requestErrorHooks.slice(); + child.responseHooks = this.responseHooks.slice(); + + return child; + } } export type StatusCodePredicate = number | string | (number | string)[]; @@ -159,346 +157,167 @@ export type StatusCodePredicate = number | string | (number | string)[]; // segments in a media type string. const mediaParamSeparator = /\s*;\s*/g; -function matchContentType(response: Response, pattern: string): boolean { - // `*` is a special case which means anything is acceptable. - if (pattern === "*") { - return true; +export function matchContentType(response: Response, pattern: string): boolean { + // `*` is a special case which means anything is acceptable. + if (pattern === "*") { + return true; + } + + let contentType = + response.headers.get("content-type")?.trim() || "application/octet-stream"; + contentType = contentType.toLowerCase(); + + const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); + const [wantType = "", ...wantParams] = wantParts; + + if (wantType.split("/").length !== 2) { + return false; + } + + const gotParts = contentType.split(mediaParamSeparator); + const [gotType = "", ...gotParams] = gotParts; + + const [type = "", subtype = ""] = gotType.split("/"); + if (!type || !subtype) { + return false; + } + + if ( + wantType !== "*/*" && + gotType !== wantType && + `${type}/*` !== wantType && + `*/${subtype}` !== wantType + ) { + return false; + } + + if (gotParams.length < wantParams.length) { + return false; + } + + const params = new Set(gotParams); + for (const wantParam of wantParams) { + if (!params.has(wantParam)) { + return false; } + } - let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream"; - contentType = contentType.toLowerCase(); + return true; +} - const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); - const [wantType = "", ...wantParams] = wantParts; +const codeRangeRE = new RegExp("^[0-9]xx$", "i"); - if (wantType.split("/").length !== 2) { - return false; - } +export function matchStatusCode( + response: Response, + codes: StatusCodePredicate, +): boolean { + const actual = `${response.status}`; + const expectedCodes = Array.isArray(codes) ? codes : [codes]; + if (!expectedCodes.length) { + return false; + } - const gotParts = contentType.split(mediaParamSeparator); - const [gotType = "", ...gotParams] = gotParts; + return expectedCodes.some((ec) => { + const code = `${ec}`; - const [type = "", subtype = ""] = gotType.split("/"); - if (!type || !subtype) { - return false; + if (code === "default") { + return true; } - if ( - wantType !== "*/*" && - gotType !== wantType && - `${type}/*` !== wantType && - `*/${subtype}` !== wantType - ) { - return false; + if (!codeRangeRE.test(`${code}`)) { + return code === actual; } - if (gotParams.length < wantParams.length) { - return false; + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); } - const params = new Set(gotParams); - for (const wantParam of wantParams) { - if (!params.has(wantParam)) { - return false; - } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); } - return true; -} - -const codeRangeRE = new RegExp("^[0-9]xx$", "i"); - -export function matchStatusCode(response: Response, codes: StatusCodePredicate): boolean { - const actual = `${response.status}`; - const expectedCodes = Array.isArray(codes) ? codes : [codes]; - if (!expectedCodes.length) { - return false; - } - - return expectedCodes.some((ec) => { - const code = `${ec}`; - - if (code === "default") { - return true; - } - - if (!codeRangeRE.test(`${code}`)) { - return code === actual; - } - - const expectFamily = code.charAt(0); - if (!expectFamily) { - throw new Error("Invalid status code range"); - } - - const actualFamily = actual.charAt(0); - if (!actualFamily) { - throw new Error(`Invalid response status code: ${actual}`); - } - - return actualFamily === expectFamily; - }); + return actualFamily === expectFamily; + }); } export function matchResponse( - response: Response, - code: StatusCodePredicate, - contentTypePattern: string + response: Response, + code: StatusCodePredicate, + contentTypePattern: string, ): boolean { - return matchStatusCode(response, code) && matchContentType(response, contentTypePattern); -} - -const headerValRE = /, */; -export function unpackHeaders(headers: Headers): Record { - const out: Record = {}; - - for (const [k, v] of headers.entries()) { - out[k] = v.split(headerValRE); - } - - return out; + return ( + matchStatusCode(response, code) && + matchContentType(response, contentTypePattern) + ); } -type ResponseMatcherSchema = - | { parse: (data: unknown) => T } - | { inboundSchema: { parse: (data: unknown) => T } }; +/** + * Uses various heurisitics to determine if an error is a connection error. + */ +export function isConnectionError(err: unknown): boolean { + if (typeof err !== "object" || err == null) { + return false; + } -type SerializationMethod = "sse" | "json" | "rawBytes" | "rawStream" | "text" | "void" | "fail"; + // Covers fetch in Deno as well + const isBrowserErr = + err instanceof TypeError && + err.message.toLowerCase().startsWith("failed to fetch"); -const defaultContentTypes: Record = { - sse: "text/event-stream", - json: "application/json", - rawBytes: "application/octet-stream", - rawStream: "application/octet-stream", - text: "text/plain", - void: "", - fail: "", -}; + const isNodeErr = + err instanceof TypeError && + err.message.toLowerCase().startsWith("fetch failed"); -type ResponsePredicateMatch = { - method: SerializationMethod; - codes: StatusCodePredicate; - ctype: string; - schema: ResponseMatcherSchema; - hdrs: boolean; - key: string | undefined; - err: boolean; - fail: boolean; -}; + const isBunErr = "name" in err && err.name === "ConnectionError"; -type ResponsePredicateOptions = { - /** Content type to match on. */ - ctype?: string; - /** Pass HTTP headers to deserializer. */ - hdrs?: boolean; -} & ( - | { - /** The result key to store the deserialized value into. */ - key?: string; - fail?: never; - err?: never; - } - | { - /** Indicates the matched response must throw the built-in error. */ - fail: true; - key?: never; - err?: never; - } - | { - /** Indicates the matched response is a custom error. */ - err: true; - key?: never; - fail?: never; - } -); - -export class ResponseMatcher { - private predicates: ResponsePredicateMatch[] = []; - - #any( - method: SerializationMethod, - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: ResponsePredicateOptions - ) { - const ctype = opts?.ctype || defaultContentTypes[method]; - const hdrs = !!opts?.hdrs; - const key = opts?.key; - const err = !!opts?.err; - const fail = !!opts?.fail; - this.predicates.push({ - method, - codes, - ctype, - schema, - hdrs, - key, - err, - fail, - }); - return this; - } + const isGenericErr = + "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnreset"; - json( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: ResponsePredicateOptions - ): this { - return this.#any("json", codes, schema, opts); - } - bytes( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: ResponsePredicateOptions - ): this { - return this.#any("rawBytes", codes, schema, opts); - } - stream( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: ResponsePredicateOptions - ): this { - return this.#any("rawStream", codes, schema, opts); - } - text( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: ResponsePredicateOptions - ): this { - return this.#any("text", codes, schema, opts); - } - sse( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: Omit - ): this { - return this.#any("sse", codes, schema, opts); - } - void( - codes: StatusCodePredicate, - schema: ResponseMatcherSchema, - opts?: Pick - ): this { - return this.#any("void", codes, schema, opts); - } - fail(codes: StatusCodePredicate): this { - return this.#any("fail", codes, znever(), { fail: true }); - } - - async match( - response: Response, - // flat - options?: { - resultKey?: string; - extraFields?: Record; - } - ): Promise<[result: Result, rawData: unknown]> { - let pred: ResponsePredicateMatch | undefined; - for (const predicate of this.predicates) { - const { codes, ctype } = predicate; - if (ctype && matchResponse(response, codes, ctype)) { - pred = predicate; - break; - } else if (!ctype && matchStatusCode(response, codes)) { - pred = predicate; - break; - } - } - if (pred == null) { - const responseBody = await response.text(); - throw new SDKError( - "Unexpected API response status or content-type", - response, - responseBody - ); - } - - const { method, schema } = pred; - - let raw: unknown; - switch (method) { - case "json": - raw = await response.json(); - break; - case "rawBytes": - raw = await response.arrayBuffer(); - break; - case "rawStream": - raw = response.body; - break; - case "text": - raw = await response.text(); - break; - case "sse": - raw = response.body; - break; - case "void": - raw = await discardResponseBody(response); - break; - case "fail": - raw = await response.text(); - break; - default: - method satisfies never; - throw new Error(`Unsupported response type: ${method}`); - } - - const resultKey = pred.key || options?.resultKey; - let data: unknown; - if (pred.fail) { - throw new SDKError("API error occurred", response, typeof raw === "string" ? raw : ""); - } else if (pred.err) { - data = { - ...options?.extraFields, - ...(pred.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - ...(isPlainObject(raw) ? raw : null), - }; - } else if (resultKey) { - data = { - ...options?.extraFields, - ...(pred.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - [resultKey]: raw, - }; - } else if (pred.hdrs) { - data = { - ...options?.extraFields, - ...(pred.hdrs ? { Headers: unpackHeaders(response.headers) } : null), - ...(isPlainObject(raw) ? raw : null), - }; - } else { - data = raw; - } - - const parser = "inboundSchema" in schema ? schema.inboundSchema : schema; - const body = parse(data, (v: unknown) => parser.parse(v), "Response validation failed"); - - if (body instanceof Error) { - throw body; - } - - return [body, raw]; - } + return isBrowserErr || isNodeErr || isGenericErr || isBunErr; } /** - * Discards the response body to free up resources. - * - * To learn why this is need, see the undici docs: - * https://undici.nodejs.org/#/?id=garbage-collection + * Uses various heurisitics to determine if an error is a timeout error. */ -export async function discardResponseBody(res: Response) { - const reader = res.body?.getReader(); - if (reader == null) { - return; - } +export function isTimeoutError(err: unknown): boolean { + if (typeof err !== "object" || err == null) { + return false; + } + + // Fetch in browser, Node.js, Bun, Deno + const isNative = "name" in err && err.name === "TimeoutError"; + const isLegacyNative = "code" in err && err.code === 23; + + // Node.js HTTP client and Axios + const isGenericErr = + "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnaborted"; + + return isNative || isLegacyNative || isGenericErr; +} - try { - let done = false; - while (!done) { - const res = await reader.read(); - done = res.done; - } - } finally { - reader.releaseLock(); - } +/** + * Uses various heurisitics to determine if an error is a abort error. + */ +export function isAbortError(err: unknown): boolean { + if (typeof err !== "object" || err == null) { + return false; + } + + // Fetch in browser, Node.js, Bun, Deno + const isNative = "name" in err && err.name === "AbortError"; + const isLegacyNative = "code" in err && err.code === 20; + + // Node.js HTTP client and Axios + const isGenericErr = + "code" in err && + typeof err.code === "string" && + err.code.toLowerCase() === "econnaborted"; + + return isNative || isLegacyNative || isGenericErr; } diff --git a/finance/src/lib/is-plain-object.ts b/finance/src/lib/is-plain-object.ts index af0d6e7..61070d3 100644 --- a/finance/src/lib/is-plain-object.ts +++ b/finance/src/lib/is-plain-object.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ /* diff --git a/finance/src/lib/logger.ts b/finance/src/lib/logger.ts new file mode 100644 index 0000000..d181f29 --- /dev/null +++ b/finance/src/lib/logger.ts @@ -0,0 +1,9 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export interface Logger { + group(label?: string): void; + groupEnd(): void; + log(message: any, ...args: any[]): void; +} diff --git a/finance/src/lib/matchers.ts b/finance/src/lib/matchers.ts new file mode 100644 index 0000000..dcb468b --- /dev/null +++ b/finance/src/lib/matchers.ts @@ -0,0 +1,308 @@ +/* + * 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"; + +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: "*", +}; + +type Schema = { parse(raw: unknown): T }; + +type MatchOptions = { ctype?: string; hdrs?: boolean; key?: string; sseSentinel?: string }; + +export type ValueMatcher = MatchOptions & { + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; +}; + +export type ErrorMatcher = MatchOptions & { + enc: Encoding; + codes: StatusCodePredicate; + schema: Schema; + err: true; +}; + +export type FailMatcher = { + enc: "fail"; + codes: StatusCodePredicate; +}; + +export type Matcher = ValueMatcher | ErrorMatcher | FailMatcher; + +export function jsonErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "json", codes, schema }; +} +export function json( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "json", codes, schema }; +} + +export function textErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "text", codes, schema }; +} +export function text( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "text", codes, schema }; +} + +export function bytesErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "bytes", codes, schema }; +} +export function bytes( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "bytes", codes, schema }; +} + +export function streamErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "stream", codes, schema }; +} +export function stream( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "stream", codes, schema }; +} + +export function sseErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "sse", codes, schema }; +} +export function sse( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "sse", codes, schema }; +} + +export function nilErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ErrorMatcher { + return { ...options, err: true, enc: "nil", codes, schema }; +} +export function nil( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions +): ValueMatcher { + return { ...options, enc: "nil", codes, schema }; +} + +export function fail(codes: StatusCodePredicate): FailMatcher { + return { enc: "fail", codes }; +} + +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 } +) => Promise<[result: Result, raw: unknown]>; + +export function match( + ...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; + } + } + + 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}`); + } + + 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; + + 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, + ]; + } + }; +} + +const headerValRE = /, */; +/** + * Iterates over a Headers object and returns an object with all the header + * entries. Values are represented as an array to account for repeated headers. + */ +export function unpackHeaders(headers: Headers): Record { + const out: Record = {}; + + for (const [k, v] of headers.entries()) { + out[k] = v.split(headerValRE); + } + + return out; +} + +/** + * Discards the response body to free up resources. + * + * To learn why this is need, see the undici docs: + * https://undici.nodejs.org/#/?id=garbage-collection + */ +export async function discardResponseBody(res: Response) { + 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(); + } +} diff --git a/finance/src/lib/primitives.ts b/finance/src/lib/primitives.ts index d3aae30..23794a2 100644 --- a/finance/src/lib/primitives.ts +++ b/finance/src/lib/primitives.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export type Remap = { diff --git a/finance/src/lib/retries.ts b/finance/src/lib/retries.ts index ed9b495..df3e0bc 100644 --- a/finance/src/lib/retries.ts +++ b/finance/src/lib/retries.ts @@ -1,7 +1,9 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import { isConnectionError, isTimeoutError } from "./http.js"; + export type BackoffStrategy = { initialInterval: number; maxInterval: number; @@ -99,47 +101,6 @@ function wrapFetcher( }; } -function isConnectionError(err: unknown) { - if (typeof err !== "object" || err == null) { - return false; - } - - // Covers fetch in Deno as well - const isBrowserErr = - err instanceof TypeError && - err.message.toLowerCase().startsWith("failed to fetch"); - - const isNodeErr = - err instanceof TypeError && - err.message.toLowerCase().startsWith("fetch failed"); - - const isBunErr = "name" in err && err.name === "ConnectionError"; - - const isGenericErr = - "code" in err && - typeof err.code === "string" && - err.code.toLowerCase() === "econnreset"; - - return isBrowserErr || isNodeErr || isGenericErr || isBunErr; -} - -function isTimeoutError(err: unknown) { - if (typeof err !== "object" || err == null) { - return false; - } - - // Fetch in browser, Node.js, Bun, Deno - const isNative = "name" in err && err.name === "TimeoutError"; - - // Node.js HTTP client and Axios - const isGenericErr = - "code" in err && - typeof err.code === "string" && - err.code.toLowerCase() === "econnaborted"; - - return isNative || isGenericErr; -} - const codeRangeRE = new RegExp("^[0-9]xx$", "i"); function isRetryableResponse(res: Response, statusCodes: string[]): boolean { diff --git a/finance/src/lib/schemas.ts b/finance/src/lib/schemas.ts index 94b0535..37b0b13 100644 --- a/finance/src/lib/schemas.ts +++ b/finance/src/lib/schemas.ts @@ -1,9 +1,10 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { output, ZodEffects, ZodError, ZodObject, ZodRawShape, ZodTypeAny } from "zod"; import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { ERR, OK, Result } from "../types/fp.js"; /** * Utility function that executes some code which may throw a ZodError. It @@ -21,6 +22,23 @@ export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMes } } +/** + * Utility function that executes some code which may result in a ZodError. It + * intercepts this error and converts it to an SDKValidationError so as to not + * leak Zod implementation details to user code. + */ +export function safeParse( + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string +): Result { + try { + return OK(fn(rawValue)); + } catch (err) { + return ERR(new SDKValidationError(errorMessage, err, rawValue)); + } +} + export function collectExtraKeys< Shape extends ZodRawShape, Catchall extends ZodTypeAny, diff --git a/finance/src/lib/sdks.ts b/finance/src/lib/sdks.ts index cbda9d8..51b49bd 100644 --- a/finance/src/lib/sdks.ts +++ b/finance/src/lib/sdks.ts @@ -1,16 +1,51 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { ResponseMatcher, HTTPClient, matchStatusCode } from "./http.js"; -import { SecurityState, resolveSecurity } from "./security.js"; -import { pathToFunc } from "./url.js"; +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, +} from "../models/errors/httpclienterrors.js"; +import { ERR, OK, Result } from "../types/fp.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; }; @@ -22,35 +57,65 @@ type RequestConfig = { 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"); + export class ClientSDK { - private readonly client: HTTPClient; + 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(init: { client: HTTPClient; baseURL: URL | null; hooks: SDKHooks }) { - const url = init.baseURL; + 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(/\/+$/, "") + "/"; } - - this.hooks$ = init.hooks; - const { baseURL, client } = this.hooks$.sdkInit({ baseURL: url, client: init.client }); + const { baseURL, client } = this.hooks$.sdkInit({ + baseURL: url, + client: options.httpClient || new HTTPClient(), + }); this.baseURL = baseURL; - this.client = client; + this.httpClient = client; + this.logger = options.debugLogger; } - protected createRequest$( + public createRequest$( context: HookContext, conf: RequestConfig, options?: RequestOptions - ): Request { + ): Result { const { method, path, query, headers: opHeaders, security } = conf; const base = conf.baseURL ?? this.baseURL; if (!base) { - throw new TypeError("No base URL provided for operation"); + return ERR(new InvalidRequestError("No base URL provided for operation")); } const reqURL = new URL(base); const inputURL = new URL(path, reqURL); @@ -100,48 +165,193 @@ export class ClientSDK { headers.set(k, v); } - const input = this.hooks$.beforeCreateRequest(context, { - url: reqURL, - options: { - ...options?.fetchOptions, - body: conf.body ?? null, - headers, - method, - }, - }); + // 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 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; + } + } + + 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 }) + ); + } + + return OK(new Request(input.url, input.options)); } - protected async do$( - req: Request, + public async do$( + request: Request, options: { context: HookContext; errorCodes: number | string | (number | string)[]; + retryConfig?: RetryConfig | undefined; + retryCodes?: string[] | undefined; } - ): Promise { + ): 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.client.request(await this.hooks$.beforeRequest(context, req)); + 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; + 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, + }) + ); + } } - response = result.response || response; - } else { - response = await this.hooks$.afterSuccess(context, response); + ); + } +} + +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(); - return response; + logger.groupEnd(); +} + +async function logResponse(logger: Logger | undefined, res: Response, req: Request) { + if (!logger) { + return; } - protected matcher(): ResponseMatcher { - return new ResponseMatcher(); + 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(); - protected templateURLComponent = pathToFunc; + 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; + } + logger.groupEnd(); - protected resolveSecurity = resolveSecurity; + logger.groupEnd(); } diff --git a/finance/src/lib/security.ts b/finance/src/lib/security.ts index 560cb62..94dcf92 100644 --- a/finance/src/lib/security.ts +++ b/finance/src/lib/security.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export enum SecurityErrorCode { diff --git a/finance/src/lib/url.ts b/finance/src/lib/url.ts index df58acb..6bc6356 100644 --- a/finance/src/lib/url.ts +++ b/finance/src/lib/url.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ const hasOwn = Object.prototype.hasOwnProperty; diff --git a/finance/src/models/components/error.ts b/finance/src/models/components/error.ts index 1ebc730..8caa141 100644 --- a/finance/src/models/components/error.ts +++ b/finance/src/models/components/error.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as z from "zod"; @@ -10,19 +10,32 @@ export type ErrorT = { }; /** @internal */ -export namespace ErrorT$ { - export const inboundSchema: z.ZodType = z.object({ - code: z.number().int(), - message: z.string(), - }); +export const ErrorT$inboundSchema: z.ZodType = z.object({ + code: z.number().int(), + message: z.string(), +}); - export type Outbound = { - code: number; - message: string; - }; +/** @internal */ +export type ErrorT$Outbound = { + code: number; + message: string; +}; - export const outboundSchema: z.ZodType = z.object({ - code: z.number().int(), - message: z.string(), - }); +/** @internal */ +export const ErrorT$outboundSchema: z.ZodType = z.object({ + code: z.number().int(), + message: 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 ErrorT$ { + /** @deprecated use `ErrorT$inboundSchema` instead. */ + export const inboundSchema = ErrorT$inboundSchema; + /** @deprecated use `ErrorT$outboundSchema` instead. */ + export const outboundSchema = ErrorT$outboundSchema; + /** @deprecated use `ErrorT$Outbound` instead. */ + export type Outbound = ErrorT$Outbound; } diff --git a/finance/src/models/components/index.ts b/finance/src/models/components/index.ts index e304610..4709ef0 100644 --- a/finance/src/models/components/index.ts +++ b/finance/src/models/components/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export * from "./error.js"; diff --git a/finance/src/models/components/pet.ts b/finance/src/models/components/pet.ts index 4b766b0..333a92d 100644 --- a/finance/src/models/components/pet.ts +++ b/finance/src/models/components/pet.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as z from "zod"; @@ -11,22 +11,35 @@ export type Pet = { }; /** @internal */ -export namespace Pet$ { - export const inboundSchema: z.ZodType = z.object({ - id: z.number().int(), - name: z.string(), - tag: z.string().optional(), - }); +export const Pet$inboundSchema: z.ZodType = z.object({ + id: z.number().int(), + name: z.string(), + tag: z.string().optional(), +}); + +/** @internal */ +export type Pet$Outbound = { + id: number; + name: string; + tag?: string | undefined; +}; - export type Outbound = { - id: number; - name: string; - tag?: string | undefined; - }; +/** @internal */ +export const Pet$outboundSchema: z.ZodType = z.object({ + id: z.number().int(), + name: z.string(), + tag: z.string().optional(), +}); - export const outboundSchema: z.ZodType = z.object({ - id: z.number().int(), - name: z.string(), - tag: 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 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; } diff --git a/finance/src/models/errors/httpclienterrors.ts b/finance/src/models/errors/httpclienterrors.ts new file mode 100644 index 0000000..cdb2995 --- /dev/null +++ b/finance/src/models/errors/httpclienterrors.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/** + * 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}`; + } + + 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"; +} + +/** + * An error that is raised when any inputs used to create a request are invalid. + */ +export class InvalidRequestError extends HTTPClientError { + 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"; +} + +/** + * An error that is raised when a HTTP request timed out due to an AbortSignal + * signal timeout. + */ +export class RequestTimeoutError extends HTTPClientError { + override readonly name = "RequestTimeoutError"; +} + +/** + * An error that is raised when a HTTP client is unable to make a request to + * a server. + */ +export class ConnectionError extends HTTPClientError { + override readonly name = "ConnectionError"; +} diff --git a/finance/src/models/errors/index.ts b/finance/src/models/errors/index.ts index 629f225..900ee9d 100644 --- a/finance/src/models/errors/index.ts +++ b/finance/src/models/errors/index.ts @@ -1,6 +1,7 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +export * from "./httpclienterrors.js"; export * from "./sdkerror.js"; export * from "./sdkvalidationerror.js"; diff --git a/finance/src/models/errors/sdkerror.ts b/finance/src/models/errors/sdkerror.ts index 5a94e84..80e3aa4 100644 --- a/finance/src/models/errors/sdkerror.ts +++ b/finance/src/models/errors/sdkerror.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export class SDKError extends Error { diff --git a/finance/src/models/errors/sdkvalidationerror.ts b/finance/src/models/errors/sdkvalidationerror.ts index 5eb9218..16929b9 100644 --- a/finance/src/models/errors/sdkvalidationerror.ts +++ b/finance/src/models/errors/sdkvalidationerror.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as z from "zod"; @@ -10,15 +10,17 @@ export class SDKValidationError extends Error { */ public readonly rawValue: unknown; + /** + * The raw message that failed validation. + */ + public readonly rawMessage: unknown; + constructor(message: string, cause: unknown, rawValue: unknown) { - super(message); + super(`${message}: ${cause}`); this.name = "SDKValidationError"; this.cause = cause; this.rawValue = rawValue; - } - - public override toString(): string { - return `${this.message}: ${this.cause}`; + this.rawMessage = message; } /** @@ -28,7 +30,7 @@ export class SDKValidationError extends Error { */ public pretty(): string { if (this.cause instanceof z.ZodError) { - return `${this.message}\n${formatZodError(this.cause)}`; + return `${this.rawMessage}\n${formatZodError(this.cause)}`; } else { return this.toString(); } diff --git a/finance/src/models/operations/index.ts b/finance/src/models/operations/index.ts index e5a5faa..05633b0 100644 --- a/finance/src/models/operations/index.ts +++ b/finance/src/models/operations/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export * from "./listpets.js"; diff --git a/finance/src/models/operations/listpets.ts b/finance/src/models/operations/listpets.ts index 0ca1dc9..5064e09 100644 --- a/finance/src/models/operations/listpets.ts +++ b/finance/src/models/operations/listpets.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import { remap as remap$ } from "../../lib/primitives.js"; @@ -21,66 +21,115 @@ export type ListPetsResponse = { }; /** @internal */ -export namespace ListPetsRequest$ { - export const inboundSchema: z.ZodType = z.object({ +export const ListPetsRequest$inboundSchema: z.ZodType = + z.object({ limit: z.number().int().optional(), }); - export type Outbound = { - limit?: number | undefined; - }; +/** @internal */ +export type ListPetsRequest$Outbound = { + limit?: number | undefined; +}; - export const outboundSchema: z.ZodType = z.object({ - limit: z.number().int().optional(), - }); +/** @internal */ +export const ListPetsRequest$outboundSchema: z.ZodType< + ListPetsRequest$Outbound, + z.ZodTypeDef, + ListPetsRequest +> = z.object({ + limit: 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 ListPetsRequest$ { + /** @deprecated use `ListPetsRequest$inboundSchema` instead. */ + export const inboundSchema = ListPetsRequest$inboundSchema; + /** @deprecated use `ListPetsRequest$outboundSchema` instead. */ + export const outboundSchema = ListPetsRequest$outboundSchema; + /** @deprecated use `ListPetsRequest$Outbound` instead. */ + export type Outbound = ListPetsRequest$Outbound; } /** @internal */ +export const ListPetsResponseResult$inboundSchema: z.ZodType< + ListPetsResponseResult, + z.ZodTypeDef, + unknown +> = z.union([components.ErrorT$inboundSchema, z.array(components.Pet$inboundSchema)]); + +/** @internal */ +export type ListPetsResponseResult$Outbound = + | components.ErrorT$Outbound + | Array; + +/** @internal */ +export const ListPetsResponseResult$outboundSchema: z.ZodType< + ListPetsResponseResult$Outbound, + z.ZodTypeDef, + ListPetsResponseResult +> = z.union([components.ErrorT$outboundSchema, z.array(components.Pet$outboundSchema)]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace ListPetsResponseResult$ { - export const inboundSchema: z.ZodType = z.union([ - components.ErrorT$.inboundSchema, - z.array(components.Pet$.inboundSchema), - ]); - - export type Outbound = components.ErrorT$.Outbound | Array; - export const outboundSchema: z.ZodType = - z.union([components.ErrorT$.outboundSchema, z.array(components.Pet$.outboundSchema)]); + /** @deprecated use `ListPetsResponseResult$inboundSchema` instead. */ + export const inboundSchema = ListPetsResponseResult$inboundSchema; + /** @deprecated use `ListPetsResponseResult$outboundSchema` instead. */ + export const outboundSchema = ListPetsResponseResult$outboundSchema; + /** @deprecated use `ListPetsResponseResult$Outbound` instead. */ + export type Outbound = ListPetsResponseResult$Outbound; } /** @internal */ -export namespace ListPetsResponse$ { - export const inboundSchema: z.ZodType = z - .object({ - Headers: z.record(z.array(z.string())), - Result: z.union([ - components.ErrorT$.inboundSchema, - z.array(components.Pet$.inboundSchema), - ]), - }) - .transform((v) => { - return remap$(v, { - Headers: "headers", - Result: "result", - }); +export const ListPetsResponse$inboundSchema: z.ZodType = z + .object({ + Headers: z.record(z.array(z.string())), + Result: z.union([components.ErrorT$inboundSchema, z.array(components.Pet$inboundSchema)]), + }) + .transform((v) => { + return remap$(v, { + Headers: "headers", + Result: "result", }); + }); - export type Outbound = { - Headers: { [k: string]: Array }; - Result: components.ErrorT$.Outbound | Array; - }; - - export const outboundSchema: z.ZodType = z - .object({ - headers: z.record(z.array(z.string())), - result: z.union([ - components.ErrorT$.outboundSchema, - z.array(components.Pet$.outboundSchema), - ]), - }) - .transform((v) => { - return remap$(v, { - headers: "Headers", - result: "Result", - }); +/** @internal */ +export type ListPetsResponse$Outbound = { + Headers: { [k: string]: Array }; + Result: components.ErrorT$Outbound | Array; +}; + +/** @internal */ +export const ListPetsResponse$outboundSchema: z.ZodType< + ListPetsResponse$Outbound, + z.ZodTypeDef, + ListPetsResponse +> = z + .object({ + headers: z.record(z.array(z.string())), + result: z.union([components.ErrorT$outboundSchema, z.array(components.Pet$outboundSchema)]), + }) + .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 ListPetsResponse$ { + /** @deprecated use `ListPetsResponse$inboundSchema` instead. */ + export const inboundSchema = ListPetsResponse$inboundSchema; + /** @deprecated use `ListPetsResponse$outboundSchema` instead. */ + export const outboundSchema = ListPetsResponse$outboundSchema; + /** @deprecated use `ListPetsResponse$Outbound` instead. */ + export type Outbound = ListPetsResponse$Outbound; } diff --git a/finance/src/models/operations/showpetbyid.ts b/finance/src/models/operations/showpetbyid.ts index faabaef..cb03cff 100644 --- a/finance/src/models/operations/showpetbyid.ts +++ b/finance/src/models/operations/showpetbyid.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as components from "../components/index.js"; @@ -15,30 +15,67 @@ export type ShowPetByIdRequest = { export type ShowPetByIdResponse = components.ErrorT | components.Pet; /** @internal */ -export namespace ShowPetByIdRequest$ { - export const inboundSchema: z.ZodType = z.object({ - petId: z.string(), - }); +export const ShowPetByIdRequest$inboundSchema: z.ZodType< + ShowPetByIdRequest, + z.ZodTypeDef, + unknown +> = z.object({ + petId: z.string(), +}); - export type Outbound = { - petId: string; - }; +/** @internal */ +export type ShowPetByIdRequest$Outbound = { + petId: string; +}; - export const outboundSchema: z.ZodType = z.object({ - petId: z.string(), - }); +/** @internal */ +export const ShowPetByIdRequest$outboundSchema: z.ZodType< + ShowPetByIdRequest$Outbound, + z.ZodTypeDef, + ShowPetByIdRequest +> = z.object({ + petId: 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 ShowPetByIdRequest$ { + /** @deprecated use `ShowPetByIdRequest$inboundSchema` instead. */ + export const inboundSchema = ShowPetByIdRequest$inboundSchema; + /** @deprecated use `ShowPetByIdRequest$outboundSchema` instead. */ + export const outboundSchema = ShowPetByIdRequest$outboundSchema; + /** @deprecated use `ShowPetByIdRequest$Outbound` instead. */ + export type Outbound = ShowPetByIdRequest$Outbound; } /** @internal */ +export const ShowPetByIdResponse$inboundSchema: z.ZodType< + ShowPetByIdResponse, + z.ZodTypeDef, + unknown +> = z.union([components.ErrorT$inboundSchema, components.Pet$inboundSchema]); + +/** @internal */ +export type ShowPetByIdResponse$Outbound = components.ErrorT$Outbound | components.Pet$Outbound; + +/** @internal */ +export const ShowPetByIdResponse$outboundSchema: z.ZodType< + ShowPetByIdResponse$Outbound, + z.ZodTypeDef, + ShowPetByIdResponse +> = z.union([components.ErrorT$outboundSchema, components.Pet$outboundSchema]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace ShowPetByIdResponse$ { - export const inboundSchema: z.ZodType = z.union([ - components.ErrorT$.inboundSchema, - components.Pet$.inboundSchema, - ]); - - export type Outbound = components.ErrorT$.Outbound | components.Pet$.Outbound; - export const outboundSchema: z.ZodType = z.union([ - components.ErrorT$.outboundSchema, - components.Pet$.outboundSchema, - ]); + /** @deprecated use `ShowPetByIdResponse$inboundSchema` instead. */ + export const inboundSchema = ShowPetByIdResponse$inboundSchema; + /** @deprecated use `ShowPetByIdResponse$outboundSchema` instead. */ + export const outboundSchema = ShowPetByIdResponse$outboundSchema; + /** @deprecated use `ShowPetByIdResponse$Outbound` instead. */ + export type Outbound = ShowPetByIdResponse$Outbound; } diff --git a/finance/src/sdk/index.ts b/finance/src/sdk/index.ts index 34a84fc..ecac226 100644 --- a/finance/src/sdk/index.ts +++ b/finance/src/sdk/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export * from "./sdk.js"; diff --git a/finance/src/sdk/pets.ts b/finance/src/sdk/pets.ts index ddd5cc3..3363fc1 100644 --- a/finance/src/sdk/pets.ts +++ b/finance/src/sdk/pets.ts @@ -1,47 +1,16 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { SDKHooks } from "../hooks/hooks.js"; -import { SDK_METADATA, SDKOptions, serverURLFromOptions } from "../lib/config.js"; -import { - encodeFormQuery as encodeFormQuery$, - encodeJSON as encodeJSON$, - encodeSimple as encodeSimple$, -} from "../lib/encodings.js"; -import { HTTPClient } from "../lib/http.js"; -import * as schemas$ from "../lib/schemas.js"; +import { petsCreatePets } from "../funcs/petsCreatePets.js"; +import { petsListPets } from "../funcs/petsListPets.js"; +import { petsShowPetById } from "../funcs/petsShowPetById.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; import * as operations from "../models/operations/index.js"; +import { unwrapAsync } from "../types/fp.js"; export class Pets extends ClientSDK { - private readonly options$: SDKOptions & { hooks?: SDKHooks }; - - constructor(options: SDKOptions = {}) { - const opt = options as unknown; - let hooks: SDKHooks; - if ( - typeof opt === "object" && - opt != null && - "hooks" in opt && - opt.hooks instanceof SDKHooks - ) { - hooks = opt.hooks; - } else { - hooks = new SDKHooks(); - } - - super({ - client: options.httpClient || new HTTPClient(), - baseURL: serverURLFromOptions(options), - hooks, - }); - - this.options$ = { ...options, hooks }; - void this.options$; - } - /** * List all pets */ @@ -49,46 +18,7 @@ export class Pets extends ClientSDK { request: operations.ListPetsRequest, options?: RequestOptions ): Promise { - const input$ = typeof request === "undefined" ? {} : request; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.ListPetsRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const path$ = this.templateURLComponent("/pets")(); - - const query$ = encodeFormQuery$({ - limit: payload$.limit, - }); - - const context = { operationID: "listPets", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "GET", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .json(200, operations.ListPetsResponse$, { hdrs: true, key: "Result" }) - .fail(["4XX", "5XX"]) - .json("default", operations.ListPetsResponse$, { key: "Result" }) - .match(response, { extraFields: responseFields$ }); - - return result$; + return unwrapAsync(petsListPets(this, request, options)); } /** @@ -98,41 +28,7 @@ export class Pets extends ClientSDK { request: components.Pet, options?: RequestOptions ): Promise { - const input$ = request; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Content-Type", "application/json"); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => components.Pet$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$, { explode: true }); - - const path$ = this.templateURLComponent("/pets")(); - - const query$ = ""; - - const context = { operationID: "createPets", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "POST", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .void(201, components.ErrorT$.inboundSchema.optional()) - .fail(["4XX", "5XX"]) - .json("default", components.ErrorT$.inboundSchema.optional()) - .match(response); - - return result$; + return unwrapAsync(petsCreatePets(this, request, options)); } /** @@ -142,45 +38,6 @@ export class Pets extends ClientSDK { request: operations.ShowPetByIdRequest, options?: RequestOptions ): Promise { - const input$ = request; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.ShowPetByIdRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - petId: encodeSimple$("petId", payload$.petId, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/pets/{petId}")(pathParams$); - - const query$ = ""; - - const context = { operationID: "showPetById", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "GET", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .json(200, operations.ShowPetByIdResponse$) - .fail(["4XX", "5XX"]) - .json("default", operations.ShowPetByIdResponse$) - .match(response); - - return result$; + return unwrapAsync(petsShowPetById(this, request, options)); } } diff --git a/finance/src/sdk/sdk.ts b/finance/src/sdk/sdk.ts index 9bdff4b..338f3b3 100644 --- a/finance/src/sdk/sdk.ts +++ b/finance/src/sdk/sdk.ts @@ -1,40 +1,11 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -import { SDKHooks } from "../hooks/hooks.js"; -import { SDKOptions, serverURLFromOptions } from "../lib/config.js"; -import { HTTPClient } from "../lib/http.js"; import { ClientSDK } from "../lib/sdks.js"; import { Pets } from "./pets.js"; export class FinanceSDK extends ClientSDK { - private readonly options$: SDKOptions & { hooks?: SDKHooks }; - - constructor(options: SDKOptions = {}) { - const opt = options as unknown; - let hooks: SDKHooks; - if ( - typeof opt === "object" && - opt != null && - "hooks" in opt && - opt.hooks instanceof SDKHooks - ) { - hooks = opt.hooks; - } else { - hooks = new SDKHooks(); - } - - super({ - client: options.httpClient || new HTTPClient(), - baseURL: serverURLFromOptions(options), - hooks, - }); - - this.options$ = { ...options, hooks }; - void this.options$; - } - private _pets?: Pets; get pets(): Pets { return (this._pets ??= new Pets(this.options$)); diff --git a/finance/src/types/blobs.ts b/finance/src/types/blobs.ts index cbb8a57..4ce8460 100644 --- a/finance/src/types/blobs.ts +++ b/finance/src/types/blobs.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ import * as z from "zod"; diff --git a/finance/src/types/constdatetime.ts b/finance/src/types/constdatetime.ts new file mode 100644 index 0000000..c0a4409 --- /dev/null +++ b/finance/src/types/constdatetime.ts @@ -0,0 +1,15 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; + +export function constDateTime( + val: string, +): z.ZodType { + return z.custom((v) => { + return ( + typeof v === "string" && new Date(v).getTime() === new Date(val).getTime() + ); + }, `Value must be equivelant to ${val}`); +} diff --git a/finance/src/types/enums.ts b/finance/src/types/enums.ts index 4de0142..6fb6d91 100644 --- a/finance/src/types/enums.ts +++ b/finance/src/types/enums.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ declare const __brand: unique symbol; diff --git a/finance/src/types/fp.ts b/finance/src/types/fp.ts new file mode 100644 index 0000000..ccbe51e --- /dev/null +++ b/finance/src/types/fp.ts @@ -0,0 +1,50 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/** + * A monad that captures the result of a function call or an error if it was not + * successful. Railway programming, enabled by this type, can be a nicer + * alternative to traditional exception throwing because it allows functions to + * declare all _known_ errors with static types and then check for them + * exhaustively in application code. Thrown exception have a type of `unknown` + * and break out of regular control flow of programs making them harder to + * inspect and more verbose work with due to try-catch blocks. + */ +export type Result = + | { ok: true; value: T; error?: never } + | { ok: false; value?: never; error: E }; + +export function OK(value: V): Result { + return { ok: true, value }; +} + +export function ERR(error: E): Result { + return { ok: false, error }; +} + +/** + * unwrap is a convenience function for extracting a value from a result or + * throwing if there was an error. + */ +export function unwrap(r: Result): T { + if (!r.ok) { + throw r.error; + } + return r.value; +} + +/** + * unwrapAsync is a convenience function for resolving a value from a Promise + * of a result or rejecting if an error occurred. + */ +export async function unwrapAsync( + pr: Promise>, +): Promise { + const r = await pr; + if (!r.ok) { + throw r.error; + } + + return r.value; +} diff --git a/finance/src/types/index.ts b/finance/src/types/index.ts index 374373e..dbaa5e6 100644 --- a/finance/src/types/index.ts +++ b/finance/src/types/index.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ export { RFCDate } from "./rfcdate.js"; @@ -8,3 +8,4 @@ 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 { Result } from "./fp.js"; diff --git a/finance/src/types/operations.ts b/finance/src/types/operations.ts index 7f83351..0952f6f 100644 --- a/finance/src/types/operations.ts +++ b/finance/src/types/operations.ts @@ -1,25 +1,99 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export type Paginator = () => Promise> | null; +import { Result } from "./fp.js"; -export type PageIterator = Result & { - next: Paginator; - [Symbol.asyncIterator]: () => AsyncIterableIterator; +export type Paginator = () => Promise }> | null; + +export type PageIterator = V & { + next: Paginator; + [Symbol.asyncIterator]: () => AsyncIterableIterator; }; -export function createPageIterator( - page: Result & { next: Paginator }, -): { [Symbol.asyncIterator]: () => AsyncIterableIterator } { +export function createPageIterator( + page: V & { next: Paginator }, + halt: (v: V) => boolean, +): { + [Symbol.asyncIterator]: () => AsyncIterableIterator; +} { return { [Symbol.asyncIterator]: async function* paginator() { yield page; + if (halt(page)) { + return; + } let p: typeof page | null = page; for (p = await p.next(); p != null; p = await p.next()) { yield p; + if (halt(p)) { + return; + } } }, }; } + +/** + * This utility create a special iterator that yields a single value and + * terminates. It is useful in paginated SDK functions that have early return + * paths when things go wrong. + */ +export function haltIterator(v: V): PageIterator { + return { + ...v, + next: () => null, + [Symbol.asyncIterator]: async function* paginator() { + yield v; + }, + }; +} + +/** + * Converts an async iterator of `Result` into an async iterator of `V`. + * When error results occur, the underlying error value is thrown. + */ +export async function unwrapResultIterator( + iteratorPromise: Promise>>, +): Promise> { + const resultIter = await iteratorPromise; + + if (!resultIter.ok) { + throw resultIter.error; + } + + return { + ...resultIter.value, + next: unwrapPaginator(resultIter.next), + [Symbol.asyncIterator]: async function* paginator() { + for await (const page of resultIter) { + if (!page.ok) { + throw page.error; + } + yield page.value; + } + }, + }; +} + +function unwrapPaginator( + paginator: Paginator>, +): Paginator { + return () => { + const nextResult = paginator(); + if (nextResult == null) { + return null; + } + return nextResult.then((res) => { + if (!res.ok) { + throw res.error; + } + const out = { + ...res.value, + next: unwrapPaginator(res.next), + }; + return out; + }); + }; +} diff --git a/finance/src/types/rfcdate.ts b/finance/src/types/rfcdate.ts index e80b693..c79b3f5 100644 --- a/finance/src/types/rfcdate.ts +++ b/finance/src/types/rfcdate.ts @@ -1,5 +1,5 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ const dateRE = /^\d{4}-\d{2}-\d{2}$/;