diff --git a/.gitignore b/.gitignore index cc2681a..5c7dbfa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,12 @@ +/funcs +/react-query +/core.* +/esm +/dist +/.tshy +/.tshy-* +/__tests__ +/.speakeasy/reports /models /models/errors /types diff --git a/.npmignore b/.npmignore index 709e684..abca429 100644 --- a/.npmignore +++ b/.npmignore @@ -1,7 +1,14 @@ **/* +!/FUNCTIONS.md +!/RUNTIMES.md +!/REACT_QUERY.md !/**/*.ts !/**/*.js +!/**/*.json !/**/*.map /.eslintrc.js /cjs +/.tshy +/.tshy-* +/__tests__ diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index 71347e1..afb6581 100755 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -3,10 +3,10 @@ id: 0115721b-c5d5-4598-9754-02eb24f100a8 management: docChecksum: 108d5939aa1f55ecaef7b1e04e7745b6 docVersion: 1.0.0 - speakeasyVersion: 1.309.1 - generationVersion: 2.347.4 - releaseVersion: 0.9.1 - configChecksum: 3144aadae02ffcdbc2bcf9d1a9c2c8c7 + speakeasyVersion: 1.476.1 + generationVersion: 2.495.1 + releaseVersion: 0.10.0 + configChecksum: a6c8cc11a94e9f41f09b9972057ecc3b repoURL: https://github.com/speakeasy-sdks/nango-typescript-sdk.git repoSubDirectory: . installationURL: https://github.com/speakeasy-sdks/nango-typescript-sdk @@ -14,159 +14,435 @@ management: features: typescript: additionalDependencies: 0.1.0 - core: 3.10.0 - flattening: 2.81.1 + core: 3.18.17 + defaultEnabledRetries: 0.1.0 + enumUnions: 0.1.0 + envVarSecurityUsage: 0.1.2 + flattening: 2.82.1 globalSecurityCallbacks: 0.1.0 globalServerURLs: 2.82.4 groups: 2.81.2 nameOverrides: 2.81.2 responseFormat: 0.2.3 - sdkHooks: 0.1.0 + retries: 2.83.0 + sdkHooks: 0.2.0 serverIDs: 2.81.2 generatedFiles: - - src/sdk/integrations.ts - - src/sdk/connections.ts - - src/sdk/records.ts - - src/sdk/sync.ts - - src/sdk/actions.ts - - src/sdk/environment.ts - - src/sdk/proxy.ts - - src/sdk/sdk.ts - .eslintrc.cjs + - .gitattributes - .npmignore + - FUNCTIONS.md - RUNTIMES.md + - USAGE.md + - docs/lib/utils/retryconfig.md + - docs/models/components/config.md + - docs/models/components/createactiontriggerrequest.md + - docs/models/components/createactiontriggerresponse.md + - docs/models/components/createconnectionrequest.md + - docs/models/components/createproxyrequest.md + - docs/models/components/createsyncpauserequest.md + - docs/models/components/createsyncstartrequest.md + - docs/models/components/createsynctriggerrequest.md + - docs/models/components/getconnectionresponse.md + - docs/models/components/getconnectionresponseitems.md + - docs/models/components/getenvironmentvariableresponse.md + - docs/models/components/getintegrationresponse.md + - docs/models/components/getrecordresponse.md + - docs/models/components/getrecordresponselastaction.md + - docs/models/components/getrecordresponsenangometadata.md + - docs/models/components/getsyncrecordresponse.md + - docs/models/components/getsyncstatusresponse.md + - docs/models/components/input.md + - docs/models/components/integrationsresponse200.md + - docs/models/components/items.md + - docs/models/components/lastaction.md + - docs/models/components/latestresult.md + - docs/models/components/listintegrationsrequest.md + - docs/models/components/nangometadata.md + - docs/models/components/patchproxyrequest.md + - docs/models/components/putproxyrequest.md + - docs/models/components/records.md + - docs/models/components/status.md + - docs/models/components/syncs.md + - docs/models/components/type.md + - docs/models/components/updateconnectionfrequencyrequest.md + - docs/models/components/updateconnectionfrequencyresponse.md + - docs/models/components/updateintegrationrequest.md + - docs/models/errors/response400.md + - docs/models/errors/response404.md + - docs/models/operations/createactiontriggerrequest.md + - docs/models/operations/createmetadatarequest.md + - docs/models/operations/createmetadatarequestbody.md + - docs/models/operations/createproxyrequest.md + - docs/models/operations/deleteconnectionsrequest.md + - docs/models/operations/deleteintegrationrequest.md + - docs/models/operations/deleteproxyrequest.md + - docs/models/operations/filter.md + - docs/models/operations/getconnectionsrequest.md + - docs/models/operations/getintegrationrequest.md + - docs/models/operations/getproxyrequest.md + - docs/models/operations/getrecordrequest.md + - docs/models/operations/getsyncrecordrequest.md + - docs/models/operations/getsyncstatusrequest.md + - docs/models/operations/listconnectionsrequest.md + - docs/models/operations/order.md + - docs/models/operations/patchproxyrequest.md + - docs/models/operations/putproxyrequest.md + - docs/models/operations/queryparamfilter.md + - docs/models/operations/sortby.md + - docs/models/operations/updatemetadatarequest.md + - docs/models/operations/updatemetadatarequestbody.md + - docs/models/operations/updatemetadataresponsebody.md + - docs/sdks/actions/README.md + - docs/sdks/connections/README.md + - docs/sdks/environment/README.md + - docs/sdks/integrations/README.md + - docs/sdks/nango/README.md + - docs/sdks/proxy/README.md + - docs/sdks/records/README.md + - docs/sdks/sync/README.md - jsr.json - package.json + - src/core.ts + - src/funcs/actionsCreateTrigger.ts + - src/funcs/connectionsCreate.ts + - src/funcs/connectionsCreateMetadata.ts + - src/funcs/connectionsDelete.ts + - src/funcs/connectionsGet.ts + - src/funcs/connectionsList.ts + - src/funcs/connectionsUpdate.ts + - src/funcs/environmentGet.ts + - src/funcs/integrationsCreate.ts + - src/funcs/integrationsDelete.ts + - src/funcs/integrationsGet.ts + - src/funcs/integrationsList.ts + - src/funcs/integrationsUpdate.ts + - src/funcs/proxyCreate.ts + - src/funcs/proxyDelete.ts + - src/funcs/proxyGet.ts + - src/funcs/proxyModify.ts + - src/funcs/proxyUpdate.ts + - src/funcs/recordsGet.ts + - src/funcs/syncCreateTrigger.ts + - src/funcs/syncGetRecord.ts + - src/funcs/syncGetStatus.ts + - src/funcs/syncPause.ts + - src/funcs/syncStart.ts + - src/funcs/syncUpdateFrequency.ts + - src/hooks/hooks.ts + - src/hooks/index.ts + - src/hooks/types.ts - src/index.ts - src/lib/base64.ts - src/lib/config.ts + - src/lib/dlv.ts - src/lib/encodings.ts + - src/lib/files.ts - src/lib/http.ts - src/lib/is-plain-object.ts + - src/lib/logger.ts + - src/lib/matchers.ts - src/lib/primitives.ts - src/lib/retries.ts - src/lib/schemas.ts - src/lib/sdks.ts - src/lib/security.ts - src/lib/url.ts - - src/sdk/index.ts - - src/models/errors/sdkerror.ts - - src/models/errors/sdkvalidationerror.ts - - src/types/blobs.ts - - src/types/enums.ts - - src/types/index.ts - - src/types/operations.ts - - src/types/rfcdate.ts - - tsconfig.json - - src/models/components/integrationsresponse200.ts - - src/models/components/listintegrationsrequest.ts - - src/models/components/updateintegrationrequest.ts - - src/models/components/getintegrationresponse.ts - - src/models/components/getconnectionresponse.ts + - src/models/components/createactiontriggerrequest.ts + - src/models/components/createactiontriggerresponse.ts - src/models/components/createconnectionrequest.ts + - src/models/components/createproxyrequest.ts + - src/models/components/createsyncpauserequest.ts + - src/models/components/createsyncstartrequest.ts + - src/models/components/createsynctriggerrequest.ts + - src/models/components/getconnectionresponse.ts + - src/models/components/getenvironmentvariableresponse.ts + - src/models/components/getintegrationresponse.ts - src/models/components/getrecordresponse.ts - src/models/components/getsyncrecordresponse.ts - - src/models/components/createsynctriggerrequest.ts - - src/models/components/createsyncstartrequest.ts - - src/models/components/createsyncpauserequest.ts - src/models/components/getsyncstatusresponse.ts - - src/models/components/updateconnectionfrequencyresponse.ts - - src/models/components/updateconnectionfrequencyrequest.ts - - src/models/components/createactiontriggerresponse.ts - - src/models/components/createactiontriggerrequest.ts - - src/models/components/getenvironmentvariableresponse.ts - - src/models/components/createproxyrequest.ts - - src/models/components/putproxyrequest.ts + - src/models/components/index.ts + - src/models/components/integrationsresponse200.ts + - src/models/components/listintegrationsrequest.ts - src/models/components/patchproxyrequest.ts + - src/models/components/putproxyrequest.ts + - src/models/components/updateconnectionfrequencyrequest.ts + - src/models/components/updateconnectionfrequencyresponse.ts + - src/models/components/updateintegrationrequest.ts + - src/models/errors/httpclienterrors.ts + - src/models/errors/index.ts - src/models/errors/response400.ts - src/models/errors/response404.ts - - src/models/operations/getintegration.ts + - src/models/errors/sdkerror.ts + - src/models/errors/sdkvalidationerror.ts + - src/models/operations/createactiontrigger.ts + - src/models/operations/createmetadata.ts + - src/models/operations/createproxy.ts + - src/models/operations/deleteconnections.ts - src/models/operations/deleteintegration.ts - - src/models/operations/listconnections.ts + - src/models/operations/deleteproxy.ts - src/models/operations/getconnections.ts - - src/models/operations/deleteconnections.ts - - src/models/operations/createmetadata.ts - - src/models/operations/updatemetadata.ts + - src/models/operations/getintegration.ts + - src/models/operations/getproxy.ts - src/models/operations/getrecord.ts - src/models/operations/getsyncrecord.ts - src/models/operations/getsyncstatus.ts - - src/models/operations/createactiontrigger.ts - - src/models/operations/getproxy.ts - - src/models/operations/createproxy.ts - - src/models/operations/putproxy.ts - - src/models/operations/patchproxy.ts - - src/models/operations/deleteproxy.ts - - src/models/errors/index.ts - - src/models/components/index.ts - src/models/operations/index.ts - - docs/models/components/items.md - - docs/models/components/integrationsresponse200.md - - docs/models/components/listintegrationsrequest.md - - docs/models/components/updateintegrationrequest.md - - docs/models/components/config.md - - docs/models/components/getintegrationresponse.md - - docs/models/components/getconnectionresponseitems.md - - docs/models/components/getconnectionresponse.md - - docs/models/components/createconnectionrequest.md - - docs/models/components/getrecordresponselastaction.md - - docs/models/components/getrecordresponsenangometadata.md - - docs/models/components/records.md - - docs/models/components/getrecordresponse.md - - docs/models/components/lastaction.md - - docs/models/components/nangometadata.md - - docs/models/components/getsyncrecordresponse.md - - docs/models/components/createsynctriggerrequest.md - - docs/models/components/createsyncstartrequest.md - - docs/models/components/createsyncpauserequest.md - - docs/models/components/status.md - - docs/models/components/type.md - - docs/models/components/latestresult.md - - docs/models/components/syncs.md - - docs/models/components/getsyncstatusresponse.md - - docs/models/components/updateconnectionfrequencyresponse.md - - docs/models/components/updateconnectionfrequencyrequest.md - - docs/models/components/createactiontriggerresponse.md - - docs/models/components/input.md - - docs/models/components/createactiontriggerrequest.md - - docs/models/components/getenvironmentvariableresponse.md - - docs/models/components/createproxyrequest.md - - docs/models/components/putproxyrequest.md - - docs/models/components/patchproxyrequest.md - - docs/models/errors/response400.md - - docs/models/errors/response404.md - - docs/models/operations/getintegrationrequest.md - - docs/models/operations/deleteintegrationrequest.md - - docs/models/operations/listconnectionsrequest.md - - docs/models/operations/getconnectionsrequest.md - - docs/models/operations/deleteconnectionsrequest.md - - docs/models/operations/createmetadatarequestbody.md - - docs/models/operations/createmetadatarequest.md - - docs/models/operations/updatemetadatarequestbody.md - - docs/models/operations/updatemetadatarequest.md - - docs/models/operations/updatemetadataresponsebody.md - - docs/models/operations/filter.md - - docs/models/operations/getrecordrequest.md - - docs/models/operations/sortby.md - - docs/models/operations/order.md - - docs/models/operations/queryparamfilter.md - - docs/models/operations/getsyncrecordrequest.md - - docs/models/operations/getsyncstatusrequest.md - - docs/models/operations/createactiontriggerrequest.md - - docs/models/operations/getproxyrequest.md - - docs/models/operations/createproxyrequest.md - - docs/models/operations/putproxyrequest.md - - docs/models/operations/patchproxyrequest.md - - docs/models/operations/deleteproxyrequest.md - - docs/sdks/nango/README.md - - docs/sdks/integrations/README.md - - docs/sdks/connections/README.md - - docs/sdks/records/README.md - - docs/sdks/sync/README.md - - docs/sdks/actions/README.md - - docs/sdks/environment/README.md - - docs/sdks/proxy/README.md - - USAGE.md - - .gitattributes - - src/hooks/hooks.ts - - src/hooks/types.ts - - src/hooks/index.ts + - src/models/operations/listconnections.ts + - src/models/operations/patchproxy.ts + - src/models/operations/putproxy.ts + - src/models/operations/updatemetadata.ts + - src/sdk/actions.ts + - src/sdk/connections.ts + - src/sdk/environment.ts + - src/sdk/index.ts + - src/sdk/integrations.ts + - src/sdk/proxy.ts + - src/sdk/records.ts + - src/sdk/sdk.ts + - src/sdk/sync.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 + - src/types/streams.ts + - tsconfig.json +examples: + listIntegrations: + speakeasy-default-list-integrations: + responses: + "200": + application/json: {"configs": ["", "", ""]} + createIntegrations: + speakeasy-default-create-integrations: + requestBody: + application/json: {} + responses: + "200": + application/json: {"configs": [""]} + "400": + application/json: {} + updateIntegration: + speakeasy-default-update-integration: + requestBody: + application/json: {} + responses: + "200": + application/json: {"configs": ["", "", ""]} + "400": + application/json: {} + "404": + application/json: {} + getIntegration: + speakeasy-default-get-integration: + parameters: + path: + providerConfigKey: "" + query: {} + responses: + "200": + application/json: {"config": {}} + "400": + application/json: {} + "404": + application/json: {} + deleteIntegration: + speakeasy-default-delete-integration: + parameters: + path: + providerConfigKey: "" + responses: + "400": + application/json: {} + "404": + application/json: {} + listConnections: + speakeasy-default-list-connections: + responses: + "200": + application/json: {"configs": ["", "", ""]} + createConnection: + speakeasy-default-create-connection: + requestBody: + application/json: {} + responses: + "400": + application/json: {} + getConnections: + speakeasy-default-get-connections: + parameters: + path: + connectionId: "" + query: + provider_config_key: "" + responses: + "400": + application/json: {} + "404": + application/json: {} + deleteConnections: + speakeasy-default-delete-connections: + parameters: + path: + connectionId: "" + query: + provider_config_key: "" + responses: + "400": + application/json: {} + "404": + application/json: {} + createMetadata: + speakeasy-default-create-metadata: + parameters: + path: + connectionId: "" + header: + Provider-Config-Key: "" + requestBody: + application/json: {} + responses: + "400": + application/json: {} + updateMetadata: + speakeasy-default-update-metadata: + parameters: + path: + connectionId: "" + header: + Provider-Config-Key: "" + requestBody: + application/json: {} + responses: + "200": + application/json: {} + "400": + application/json: {} + getRecord: + speakeasy-default-get-record: + parameters: + query: + model: "Model S" + header: + Connection-Id: "" + Provider-Config-Key: "" + responses: + "200": + application/json: {"records": [{"your-properties": "Your synced data, in the schema you (or Nango) defined in nango.yaml", "_nango_metadata": {"first_seen_at": "2023-09-18T15:20:35.941305+00:00", "last_modified_at": "2023-09-18T15:20:35.941305+00:00"}}, {"your-properties": "Your synced data, in the schema you (or Nango) defined in nango.yaml", "_nango_metadata": {"first_seen_at": "2023-09-18T15:20:35.941305+00:00", "last_modified_at": "2023-09-18T15:20:35.941305+00:00"}}], "next_cursor": "MjAyMy0xMS0xN1QxMTo0NzoxNC40NDcrMDI6MDB8fDAzZTA1NzIxLWNiZmQtNGYxNS1iYTNhLWFlNjM2Y2MwNmEw=="} + "400": + application/json: {} + getSyncRecord: + speakeasy-default-get-sync-record: + parameters: + query: + model: "ATS" + header: + Connection-Id: "" + Provider-Config-Key: "" + responses: + "200": + application/json: [{"your-properties": "Your synced data, in the schema you (or Nango) defined in nango.yaml", "_nango_metadata": {"first_seen_at": "2023-09-18T15:20:35.941305+00:00", "last_modified_at": "2023-09-18T15:20:35.941305+00:00"}}, {"your-properties": "Your synced data, in the schema you (or Nango) defined in nango.yaml", "_nango_metadata": {"first_seen_at": "2023-09-18T15:20:35.941305+00:00", "last_modified_at": "2023-09-18T15:20:35.941305+00:00"}}, {"your-properties": "Your synced data, in the schema you (or Nango) defined in nango.yaml", "_nango_metadata": {"first_seen_at": "2023-09-18T15:20:35.941305+00:00", "last_modified_at": "2023-09-18T15:20:35.941305+00:00"}}] + "400": + application/json: {} + createSyncTrigger: + speakeasy-default-create-sync-trigger: + responses: + "400": + application/json: {} + createSyncStart: + speakeasy-default-create-sync-start: + responses: + "400": + application/json: {} + createSyncPause: + speakeasy-default-create-sync-pause: + responses: + "400": + application/json: {} + getSyncStatus: + speakeasy-default-get-sync-status: + parameters: + query: + provider_config_key: "" + syncs: "" + responses: + "200": + application/json: {} + "400": + application/json: {} + updateConnectionFrequency: + speakeasy-default-update-connection-frequency: + requestBody: + application/json: {"provider_config_key": "", "connection_id": "", "sync_name": "", "frequency": ""} + responses: + "200": + application/json: {} + "400": + application/json: {} + createActionTrigger: + speakeasy-default-create-action-trigger: + parameters: + header: + Connection-Id: "" + Provider-Config-Key: "" + requestBody: + application/json: {"action_name": ""} + responses: + "200": + application/json: {"your-properties": "The data returned by the action"} + "400": + application/json: {} + getEnvironmentVariable: + speakeasy-default-get-environment-variable: + responses: + "200": + application/json: [{"name": "MY_SECRET_KEY", "value": "SK_373892NSHFNCOWFO..."}, {"name": "MY_SECRET_KEY", "value": "SK_373892NSHFNCOWFO..."}, {"name": "MY_SECRET_KEY", "value": "SK_373892NSHFNCOWFO..."}] + getProxy: + speakeasy-default-get-proxy: + parameters: + path: + anyPath: "" + query: + $ANY_QUERY_PARAMS: "" + header: + Connection-Id: "" + Provider-Config-Key: "" + createProxy: + speakeasy-default-create-proxy: + parameters: + path: + anyPath: "" + header: + Connection-Id: "" + Provider-Config-Key: "" + putProxy: + speakeasy-default-put-proxy: + parameters: + path: + anyPath: "" + header: + Connection-Id: "" + Provider-Config-Key: "" + patchProxy: + speakeasy-default-patch-proxy: + parameters: + path: + anyPath: "" + header: + Connection-Id: "" + Provider-Config-Key: "" + deleteProxy: + speakeasy-default-delete-proxy: + parameters: + path: + anyPath: "" + query: + $ANY_QUERY_PARAMS: "" + header: + Connection-Id: "" + Provider-Config-Key: "" +examplesVersion: 1.0.0 +generatedTests: {} diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock index edb922c..28dc6eb 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -1,18 +1,21 @@ -speakeasyVersion: 1.309.1 +speakeasyVersion: 1.476.1 sources: my-source: sourceNamespace: my-source - sourceRevisionDigest: sha256:28f8ad416a8c616c03f380901b4f45883c023ec04e4d65ae5a811a8168c45108 - sourceBlobDigest: sha256:efa987571d8346ba36b22ab4746cdde4b9470314c134765f1b925c8d4bf07dae + sourceRevisionDigest: sha256:c7348c9491dea5077d20fd82c3a990cee1c5953a01da92a7c3895d3e0b13d768 + sourceBlobDigest: sha256:d9a6e60019f429608e9a352169eebefd6244ac2627027dc88924c9eedd377f5b tags: - latest + - speakeasy-sdk-regen-1719707103 + - 1.0.0 targets: nango-ts: source: my-source sourceNamespace: my-source - sourceRevisionDigest: sha256:28f8ad416a8c616c03f380901b4f45883c023ec04e4d65ae5a811a8168c45108 - sourceBlobDigest: sha256:efa987571d8346ba36b22ab4746cdde4b9470314c134765f1b925c8d4bf07dae - outLocation: /Users/sagar/go/src/Nango-sample-sdk + sourceRevisionDigest: sha256:c7348c9491dea5077d20fd82c3a990cee1c5953a01da92a7c3895d3e0b13d768 + sourceBlobDigest: sha256:d9a6e60019f429608e9a352169eebefd6244ac2627027dc88924c9eedd377f5b + codeSamplesNamespace: my-source-typescript-code-samples + codeSamplesRevisionDigest: sha256:711220be868fee7cef98b5133c025ee80dbe34ce0661dcd3d13b92d97b7b2362 workflow: workflowVersion: 1.0.0 speakeasyVersion: latest @@ -26,3 +29,9 @@ workflow: nango-ts: target: typescript source: my-source + codeSamples: + registry: + location: registry.speakeasyapi.dev/nango/nango/my-source-typescript-code-samples + labelOverride: + fixedValue: Typescript (SDK) + blocking: false diff --git a/.speakeasy/workflow.yaml b/.speakeasy/workflow.yaml index 427de27..94a0a9b 100644 --- a/.speakeasy/workflow.yaml +++ b/.speakeasy/workflow.yaml @@ -10,3 +10,9 @@ targets: nango-ts: target: typescript source: my-source + codeSamples: + registry: + location: registry.speakeasyapi.dev/nango/nango/my-source-typescript-code-samples + labelOverride: + fixedValue: Typescript (SDK) + blocking: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d585717 --- /dev/null +++ b/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/FUNCTIONS.md b/FUNCTIONS.md new file mode 100644 index 0000000..563689a --- /dev/null +++ b/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 { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsList } from "@speakeasy-sdks/nango/funcs/integrationsList.js"; +import { SDKValidationError } from "@speakeasy-sdks/nango/models/errors/sdkvalidationerror.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsList(nango); + + 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/README.md b/README.md index 2968735..c395c55 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,36 @@ The Nango Typescript library provides convenient access to the Nango REST API fr > * TODO: Setup automated package publishing to NPM using `speakeasy configure publishing` > * TODO: Consider adding better error response schemas per 4XX and 5XX type + +## Summary + +Nango API: Nango API specs used to authorize & sync data with external APIs. + + + +## Table of Contents + + * [SDK Installation](#sdk-installation) + * [Requirements](#requirements) + * [SDK Example Usage](#sdk-example-usage) + * [Available Resources and Operations](#available-resources-and-operations) + * [Standalone functions](#standalone-functions) + * [Retries](#retries) + * [Error Handling](#error-handling) + * [Server Selection](#server-selection) + * [Custom HTTP Client](#custom-http-client) + * [Debugging](#debugging) +* [Development](#development) + * [Maturity](#maturity) + * [Contributions](#contributions) + + + ## SDK Installation +The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers. + ### NPM ```bash @@ -62,10 +89,10 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.integrations.list(); + const result = await nango.integrations.list(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -76,13 +103,12 @@ run(); ## Available Resources and Operations -### [integrations](docs/sdks/integrations/README.md) +
+Available methods -* [list](docs/sdks/integrations/README.md#list) - Returns a list of integrations including their unique keys and providers as configured in the Nango API. -* [create](docs/sdks/integrations/README.md#create) - Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. -* [update](docs/sdks/integrations/README.md#update) - Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. -* [get](docs/sdks/integrations/README.md#get) - Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. -* [delete](docs/sdks/integrations/README.md#delete) - Deletes a specific integration identified by its provider configuration key. +### [actions](docs/sdks/actions/README.md) + +* [createTrigger](docs/sdks/actions/README.md#createtrigger) - Triggers an action for a connection. ### [connections](docs/sdks/connections/README.md) @@ -93,6 +119,27 @@ run(); * [createMetadata](docs/sdks/connections/README.md#createmetadata) - Set custom metadata for the specified connection. * [update](docs/sdks/connections/README.md#update) - Update custom metadata for the specified connection. +### [environment](docs/sdks/environment/README.md) + +* [get](docs/sdks/environment/README.md#get) - Retrieve the environment variables as added in the Nango dashboard. + +### [integrations](docs/sdks/integrations/README.md) + +* [list](docs/sdks/integrations/README.md#list) - Returns a list of integrations including their unique keys and providers as configured in the Nango API. +* [create](docs/sdks/integrations/README.md#create) - Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. +* [update](docs/sdks/integrations/README.md#update) - Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. +* [get](docs/sdks/integrations/README.md#get) - Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. +* [delete](docs/sdks/integrations/README.md#delete) - Deletes a specific integration identified by its provider configuration key. + + +### [proxy](docs/sdks/proxy/README.md) + +* [get](docs/sdks/proxy/README.md#get) - Make a GET request with the Proxy. +* [create](docs/sdks/proxy/README.md#create) - Make a POST request with the Proxy. +* [update](docs/sdks/proxy/README.md#update) - Make a PUT request with the Proxy. +* [modify](docs/sdks/proxy/README.md#modify) - Make a PATCH request with the Proxy. +* [delete](docs/sdks/proxy/README.md#delete) - Make a DELETE request with the Proxy. + ### [records](docs/sdks/records/README.md) * [get](docs/sdks/records/README.md#get) - Returns data synced with Nango Sync, filtered by specified parameters. @@ -106,72 +153,181 @@ run(); * [getStatus](docs/sdks/sync/README.md#getstatus) - Get the status of specified sync(s) for a given connection or all applicable connections if no connection is specified. * [updateFrequency](docs/sdks/sync/README.md#updatefrequency) - Override a sync's default frequency for a specific connection or revert to the default frequency. -### [actions](docs/sdks/actions/README.md) +
+ -* [createTrigger](docs/sdks/actions/README.md#createtrigger) - Triggers an action for a connection. + +## 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 + +- [`actionsCreateTrigger`](docs/sdks/actions/README.md#createtrigger) - Triggers an action for a connection. +- [`connectionsCreate`](docs/sdks/connections/README.md#create) - Adds a connection using an existing access token, along with optional OAuth or basic authentication credentials, and additional metadata or configuration. +- [`connectionsCreateMetadata`](docs/sdks/connections/README.md#createmetadata) - Set custom metadata for the specified connection. +- [`connectionsDelete`](docs/sdks/connections/README.md#delete) - Deletes a specific connection identified by its connection ID, associated with the specified integration. +- [`connectionsGet`](docs/sdks/connections/README.md#get) - Returns details of a specific connection identified by its connection ID, associated with the specified integration, with optional parameters for force refresh and returning the refresh token. +- [`connectionsList`](docs/sdks/connections/README.md#list) - Returns a list of connections, optionally filtered by connection ID. +- [`connectionsUpdate`](docs/sdks/connections/README.md#update) - Update custom metadata for the specified connection. +- [`environmentGet`](docs/sdks/environment/README.md#get) - Retrieve the environment variables as added in the Nango dashboard. +- [`integrationsCreate`](docs/sdks/integrations/README.md#create) - Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. +- [`integrationsDelete`](docs/sdks/integrations/README.md#delete) - Deletes a specific integration identified by its provider configuration key. +- [`integrationsGet`](docs/sdks/integrations/README.md#get) - Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. +- [`integrationsList`](docs/sdks/integrations/README.md#list) - Returns a list of integrations including their unique keys and providers as configured in the Nango API. +- [`integrationsUpdate`](docs/sdks/integrations/README.md#update) - Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. +- [`proxyCreate`](docs/sdks/proxy/README.md#create) - Make a POST request with the Proxy. +- [`proxyDelete`](docs/sdks/proxy/README.md#delete) - Make a DELETE request with the Proxy. +- [`proxyGet`](docs/sdks/proxy/README.md#get) - Make a GET request with the Proxy. +- [`proxyModify`](docs/sdks/proxy/README.md#modify) - Make a PATCH request with the Proxy. +- [`proxyUpdate`](docs/sdks/proxy/README.md#update) - Make a PUT request with the Proxy. +- [`recordsGet`](docs/sdks/records/README.md#get) - Returns data synced with Nango Sync, filtered by specified parameters. +- [`syncCreateTrigger`](docs/sdks/sync/README.md#createtrigger) - Triggers an additional, one-off execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. +- [`syncGetRecord`](docs/sdks/sync/README.md#getrecord) - Returns data synced with Nango Sync, allowing for advanced filtering, sorting, and pagination options. +- [`syncGetStatus`](docs/sdks/sync/README.md#getstatus) - Get the status of specified sync(s) for a given connection or all applicable connections if no connection is specified. +- [`syncPause`](docs/sdks/sync/README.md#pause) - Pauses the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. +- [`syncStart`](docs/sdks/sync/README.md#start) - Starts the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. +- [`syncUpdateFrequency`](docs/sdks/sync/README.md#updatefrequency) - Override a sync's default frequency for a specific connection or revert to the default frequency. + +
+ + + +## 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 { Nango } from "@speakeasy-sdks/nango"; -### [environment](docs/sdks/environment/README.md) +const nango = new Nango(); -* [get](docs/sdks/environment/README.md#get) - Retrieve the environment variables as added in the Nango dashboard. +async function run() { + const result = await nango.integrations.list({ + retries: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, + }); -### [proxy](docs/sdks/proxy/README.md) + // Handle the result + console.log(result); +} -* [get](docs/sdks/proxy/README.md#get) - Make a GET request with the Proxy. -* [create](docs/sdks/proxy/README.md#create) - Make a POST request with the Proxy. -* [update](docs/sdks/proxy/README.md#update) - Make a PUT request with the Proxy. -* [modify](docs/sdks/proxy/README.md#modify) - Make a PATCH request with the Proxy. -* [delete](docs/sdks/proxy/README.md#delete) - Make a DELETE request with the Proxy. - +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 { Nango } from "@speakeasy-sdks/nango"; + +const nango = new Nango({ + retryConfig: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, +}); + +async function run() { + const result = await nango.integrations.list(); + + // Handle the result + console.log(result); +} + +run(); + +``` + ## Error Handling -All SDK methods return a response object or throw an error. If Error objects are specified in your OpenAPI Spec, the SDK will throw the appropriate Error type. +Some methods specify known errors which can be thrown. All the known errors are enumerated in the `models/errors/errors.ts` module. The known errors for a method are documented under the *Errors* tables in SDK docs. For example, the `create` method may throw the following errors: -| Error Object | Status Code | Content Type | -| ------------------ | ------------------ | ------------------ | -| errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | - -Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted string since validation errors can list many issues and the plain error string may be difficult read when debugging. +| Error Type | Status Code | Content Type | +| ------------------ | ----------- | ---------------- | +| errors.Response400 | 400 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | +If the method throws an error and it is not captured by the known errors, it will default to throwing a `SDKError`. ```typescript import { Nango } from "@speakeasy-sdks/nango"; -import { SDKValidationError } from "@speakeasy-sdks/nango/models/errors"; +import { + Response400, + SDKValidationError, +} from "@speakeasy-sdks/nango/models/errors"; const nango = new Nango(); async function run() { - let result; - try { - result = await nango.integrations.create({}); - } catch (err) { - switch (true) { - case err instanceof SDKValidationError: { - // Validation errors can be pretty-printed - console.error(err.pretty()); - // Raw value may also be inspected - console.error(err.rawValue); - return; - } - case err instanceof errors.Response400: { - console.error(err); // handle exception - return; - } - default: { - throw err; - } - } - } + let result; + try { + result = await nango.integrations.create({}); // Handle the result console.log(result); + } catch (err) { + switch (true) { + // The server response does not match the expected SDK schema + case (err instanceof SDKValidationError): { + // Pretty-print will provide a human-readable multi-line error message + console.error(err.pretty()); + // Raw value may also be inspected + console.error(err.rawValue); + return; + } + case (err instanceof Response400): { + // Handle err.data$: Response400Data + console.error(err); + return; + } + default: { + // Other errors such as network errors, see HTTPClientErrors for more details + throw err; + } + } + } } run(); ``` + +Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The `SDKValidationError` that is thrown as a result will capture the raw value that failed validation in an attribute called `rawValue`. Additionally, a `pretty()` method is available on this error that can be used to log a nicely formatted multi-line string since validation errors can list many issues and the plain error string may be difficult read when debugging. + +In some rare cases, the SDK can fail to get a response from the server or even make the request due to unexpected circumstances such as network conditions. These types of errors are captured in the `models/errors/httpclienterrors.ts` module: + +| HTTP Client Error | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | +| RequestAbortedError | HTTP request was aborted by the client | +| RequestTimeoutError | HTTP request timed out due to an AbortSignal signal | +| ConnectionError | HTTP client was unable to make a request to a server | +| InvalidRequestError | Any input used to create a request is invalid | +| UnexpectedClientError | Unrecognised or unexpected error | @@ -179,48 +335,48 @@ run(); ### Select Server by Name -You can override the default server globally by passing a server name to the `server` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers: +You can override the default server globally by passing a server name to the `server: keyof typeof ServerList` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers: + +| Name | Server | +| ------- | ----------------------- | +| `prod` | `https://api.nango.dev` | +| `local` | `http://localhost:3003` | -| Name | Server | Variables | -| ----- | ------ | --------- | -| `prod` | `https://api.nango.dev` | None | -| `local` | `http://localhost:3003` | None | +#### Example ```typescript import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango({ - server: "local", + server: "local", }); async function run() { - const result = await nango.integrations.list(); + const result = await nango.integrations.list(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); ``` - ### Override Server URL Per-Client -The default server can also be overridden globally by passing a URL to the `serverURL` optional parameter when initializing the SDK client instance. For example: - +The default server can also be overridden globally by passing a URL to the `serverURL: string` optional parameter when initializing the SDK client instance. For example: ```typescript import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango({ - serverURL: "https://api.nango.dev", + serverURL: "https://api.nango.dev", }); async function run() { - const result = await nango.integrations.list(); + const result = await nango.integrations.list(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); @@ -277,6 +433,23 @@ const sdk = new Nango({ httpClient }); ``` + +## 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 { Nango } from "@speakeasy-sdks/nango"; + +const sdk = new Nango({ debugLogger: console }); +``` + + # Development diff --git a/RELEASES.md b/RELEASES.md index b1b5728..90a4362 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -130,4 +130,12 @@ Based on: ### Generated - [typescript v0.6.0] . ### Releases -- [NPM v0.6.0] https://www.npmjs.com/package/@simplesagar92/nango/v/0.6.0 - . \ No newline at end of file +- [NPM v0.6.0] https://www.npmjs.com/package/@simplesagar92/nango/v/0.6.0 - . + +## 2025-01-26 00:26:52 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.476.1 (2.495.1) https://github.com/speakeasy-api/speakeasy +### Generated +- [typescript v0.10.0] . \ No newline at end of file diff --git a/RUNTIMES.md b/RUNTIMES.md index 71fa3da..db7ea94 100644 --- a/RUNTIMES.md +++ b/RUNTIMES.md @@ -1,9 +1,9 @@ # Supported JavaScript runtimes -This SDK is intended to be used in JavaScript runtimes that support the following features: +This SDK is intended to be used in JavaScript runtimes that support ECMAScript 2020 or newer. The SDK uses 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 @@ -20,3 +20,29 @@ Runtime environments that are explicitly supported are: - Note that Deno does not currently have native support for streaming file uploads backed by the filesystem ([issue link][deno-file-streaming]) [deno-file-streaming]: https://github.com/denoland/deno/issues/11018 + +## Recommended TypeScript compiler options + +The following `tsconfig.json` options are recommended for projects using this +SDK in order to get static type support for features like async iterables, +streams and `fetch`-related APIs ([`for await...of`][for-await-of], +[`AbortSignal`][abort-signal], [`Request`][request], [`Response`][response] and +so on): + +[for-await-of]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of +[abort-signal]: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal +[request]: https://developer.mozilla.org/en-US/docs/Web/API/Request +[response]: https://developer.mozilla.org/en-US/docs/Web/API/Response + +```jsonc +{ + "compilerOptions": { + "target": "es2020", // or higher + "lib": ["es2020", "dom", "dom.iterable"], + } +} +``` + +While `target` can be set to older ECMAScript versions, it may result in extra, +unnecessary compatibility code being generated if you are not targeting old +runtimes. \ No newline at end of file diff --git a/USAGE.md b/USAGE.md index a35a978..1d0f78b 100644 --- a/USAGE.md +++ b/USAGE.md @@ -5,10 +5,10 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.integrations.list(); + const result = await nango.integrations.list(); - // Handle the result - console.log(result); + // Handle the result + console.log(result); } run(); diff --git a/docs/lib/utils/retryconfig.md b/docs/lib/utils/retryconfig.md new file mode 100644 index 0000000..08f95f4 --- /dev/null +++ b/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/docs/models/components/config.md b/docs/models/components/config.md index 36b0c36..e51d6c6 100644 --- a/docs/models/components/config.md +++ b/docs/models/components/config.md @@ -1,5 +1,12 @@ # Config +## Example Usage + +```typescript +import { Config } from "@speakeasy-sdks/nango/models/components"; + +let value: Config = {}; +``` ## Fields diff --git a/docs/models/components/createactiontriggerrequest.md b/docs/models/components/createactiontriggerrequest.md index 0c0c67d..590fcc2 100644 --- a/docs/models/components/createactiontriggerrequest.md +++ b/docs/models/components/createactiontriggerrequest.md @@ -1,5 +1,14 @@ # CreateActionTriggerRequest +## Example Usage + +```typescript +import { CreateActionTriggerRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateActionTriggerRequest = { + actionName: "", +}; +``` ## Fields diff --git a/docs/models/components/createactiontriggerresponse.md b/docs/models/components/createactiontriggerresponse.md index 93622c4..49415b6 100644 --- a/docs/models/components/createactiontriggerresponse.md +++ b/docs/models/components/createactiontriggerresponse.md @@ -1,5 +1,14 @@ # CreateActionTriggerResponse +## Example Usage + +```typescript +import { CreateActionTriggerResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateActionTriggerResponse = { + yourProperties: "The data returned by the action", +}; +``` ## Fields diff --git a/docs/models/components/createconnectionrequest.md b/docs/models/components/createconnectionrequest.md index 128ac9d..541e62d 100644 --- a/docs/models/components/createconnectionrequest.md +++ b/docs/models/components/createconnectionrequest.md @@ -1,5 +1,12 @@ # CreateConnectionRequest +## Example Usage + +```typescript +import { CreateConnectionRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateConnectionRequest = {}; +``` ## Fields diff --git a/docs/models/components/createproxyrequest.md b/docs/models/components/createproxyrequest.md index ce92b53..690493a 100644 --- a/docs/models/components/createproxyrequest.md +++ b/docs/models/components/createproxyrequest.md @@ -1,5 +1,12 @@ # CreateProxyRequest +## Example Usage + +```typescript +import { CreateProxyRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateProxyRequest = {}; +``` ## Fields diff --git a/docs/models/components/createsyncpauserequest.md b/docs/models/components/createsyncpauserequest.md index 7898332..b79cbf1 100644 --- a/docs/models/components/createsyncpauserequest.md +++ b/docs/models/components/createsyncpauserequest.md @@ -1,5 +1,17 @@ # CreateSyncPauseRequest +## Example Usage + +```typescript +import { CreateSyncPauseRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateSyncPauseRequest = { + providerConfigKey: "", + syncs: [ + "", + ], +}; +``` ## Fields diff --git a/docs/models/components/createsyncstartrequest.md b/docs/models/components/createsyncstartrequest.md index 442506c..e82e2bb 100644 --- a/docs/models/components/createsyncstartrequest.md +++ b/docs/models/components/createsyncstartrequest.md @@ -1,5 +1,17 @@ # CreateSyncStartRequest +## Example Usage + +```typescript +import { CreateSyncStartRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateSyncStartRequest = { + providerConfigKey: "", + syncs: [ + "", + ], +}; +``` ## Fields diff --git a/docs/models/components/createsynctriggerrequest.md b/docs/models/components/createsynctriggerrequest.md index 497a5ed..c1a1465 100644 --- a/docs/models/components/createsynctriggerrequest.md +++ b/docs/models/components/createsynctriggerrequest.md @@ -1,5 +1,17 @@ # CreateSyncTriggerRequest +## Example Usage + +```typescript +import { CreateSyncTriggerRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: CreateSyncTriggerRequest = { + providerConfigKey: "", + syncs: [ + "", + ], +}; +``` ## Fields diff --git a/docs/models/components/getconnectionresponse.md b/docs/models/components/getconnectionresponse.md index 70d8a2e..6ed1645 100644 --- a/docs/models/components/getconnectionresponse.md +++ b/docs/models/components/getconnectionresponse.md @@ -1,5 +1,16 @@ # GetConnectionResponse +## Example Usage + +```typescript +import { GetConnectionResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetConnectionResponse = { + configs: [ + "", + ], +}; +``` ## Fields diff --git a/docs/models/components/getconnectionresponseitems.md b/docs/models/components/getconnectionresponseitems.md index b877bdc..e32692b 100644 --- a/docs/models/components/getconnectionresponseitems.md +++ b/docs/models/components/getconnectionresponseitems.md @@ -1,5 +1,12 @@ # GetConnectionResponseItems +## Example Usage + +```typescript +import { GetConnectionResponseItems } from "@speakeasy-sdks/nango/models/components"; + +let value: GetConnectionResponseItems = {}; +``` ## Fields diff --git a/docs/models/components/getenvironmentvariableresponse.md b/docs/models/components/getenvironmentvariableresponse.md index 48267be..1ced7bd 100644 --- a/docs/models/components/getenvironmentvariableresponse.md +++ b/docs/models/components/getenvironmentvariableresponse.md @@ -1,5 +1,15 @@ # GetEnvironmentVariableResponse +## Example Usage + +```typescript +import { GetEnvironmentVariableResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetEnvironmentVariableResponse = { + name: "MY_SECRET_KEY", + value: "SK_373892NSHFNCOWFO...", +}; +``` ## Fields diff --git a/docs/models/components/getintegrationresponse.md b/docs/models/components/getintegrationresponse.md index c0d8c55..cd5c338 100644 --- a/docs/models/components/getintegrationresponse.md +++ b/docs/models/components/getintegrationresponse.md @@ -1,5 +1,14 @@ # GetIntegrationResponse +## Example Usage + +```typescript +import { GetIntegrationResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetIntegrationResponse = { + config: {}, +}; +``` ## Fields diff --git a/docs/models/components/getrecordresponse.md b/docs/models/components/getrecordresponse.md index f729067..ef30467 100644 --- a/docs/models/components/getrecordresponse.md +++ b/docs/models/components/getrecordresponse.md @@ -1,5 +1,25 @@ # GetRecordResponse +## Example Usage + +```typescript +import { GetRecordResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetRecordResponse = { + records: [ + { + yourProperties: + "Your synced data, in the schema you (or Nango) defined in nango.yaml", + nangoMetadata: { + firstSeenAt: "2023-09-18T15:20:35.941305+00:00", + lastModifiedAt: "2023-09-18T15:20:35.941305+00:00", + }, + }, + ], + nextCursor: + "MjAyMy0xMS0xN1QxMTo0NzoxNC40NDcrMDI6MDB8fDAzZTA1NzIxLWNiZmQtNGYxNS1iYTNhLWFlNjM2Y2MwNmEw==", +}; +``` ## Fields diff --git a/docs/models/components/getrecordresponselastaction.md b/docs/models/components/getrecordresponselastaction.md index 151c6b9..adab1d7 100644 --- a/docs/models/components/getrecordresponselastaction.md +++ b/docs/models/components/getrecordresponselastaction.md @@ -2,6 +2,13 @@ The last action seen on this record +## Example Usage + +```typescript +import { GetRecordResponseLastAction } from "@speakeasy-sdks/nango/models/components"; + +let value: GetRecordResponseLastAction = GetRecordResponseLastAction.Updated; +``` ## Values diff --git a/docs/models/components/getrecordresponsenangometadata.md b/docs/models/components/getrecordresponsenangometadata.md index f6b3c0b..ff2e640 100644 --- a/docs/models/components/getrecordresponsenangometadata.md +++ b/docs/models/components/getrecordresponsenangometadata.md @@ -1,5 +1,15 @@ # GetRecordResponseNangoMetadata +## Example Usage + +```typescript +import { GetRecordResponseNangoMetadata } from "@speakeasy-sdks/nango/models/components"; + +let value: GetRecordResponseNangoMetadata = { + firstSeenAt: "2023-09-18T15:20:35.941305+00:00", + lastModifiedAt: "2023-09-18T15:20:35.941305+00:00", +}; +``` ## Fields diff --git a/docs/models/components/getsyncrecordresponse.md b/docs/models/components/getsyncrecordresponse.md index e8ca2b5..f947128 100644 --- a/docs/models/components/getsyncrecordresponse.md +++ b/docs/models/components/getsyncrecordresponse.md @@ -1,5 +1,19 @@ # GetSyncRecordResponse +## Example Usage + +```typescript +import { GetSyncRecordResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetSyncRecordResponse = { + yourProperties: + "Your synced data, in the schema you (or Nango) defined in nango.yaml", + nangoMetadata: { + firstSeenAt: "2023-09-18T15:20:35.941305+00:00", + lastModifiedAt: "2023-09-18T15:20:35.941305+00:00", + }, +}; +``` ## Fields diff --git a/docs/models/components/getsyncstatusresponse.md b/docs/models/components/getsyncstatusresponse.md index 7d42b02..66b4ef7 100644 --- a/docs/models/components/getsyncstatusresponse.md +++ b/docs/models/components/getsyncstatusresponse.md @@ -1,5 +1,12 @@ # GetSyncStatusResponse +## Example Usage + +```typescript +import { GetSyncStatusResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: GetSyncStatusResponse = {}; +``` ## Fields diff --git a/docs/models/components/input.md b/docs/models/components/input.md index cf1e474..1e45f70 100644 --- a/docs/models/components/input.md +++ b/docs/models/components/input.md @@ -2,6 +2,13 @@ The necessary input for your action's 'runAction' function. +## Example Usage + +```typescript +import { Input } from "@speakeasy-sdks/nango/models/components"; + +let value: Input = {}; +``` ## Fields diff --git a/docs/models/components/integrationsresponse200.md b/docs/models/components/integrationsresponse200.md index e75ad2b..68350f8 100644 --- a/docs/models/components/integrationsresponse200.md +++ b/docs/models/components/integrationsresponse200.md @@ -1,5 +1,16 @@ # IntegrationsResponse200 +## Example Usage + +```typescript +import { IntegrationsResponse200 } from "@speakeasy-sdks/nango/models/components"; + +let value: IntegrationsResponse200 = { + configs: [ + "", + ], +}; +``` ## Fields diff --git a/docs/models/components/items.md b/docs/models/components/items.md index 9c34619..6235150 100644 --- a/docs/models/components/items.md +++ b/docs/models/components/items.md @@ -1,5 +1,12 @@ # Items +## Example Usage + +```typescript +import { Items } from "@speakeasy-sdks/nango/models/components"; + +let value: Items = {}; +``` ## Fields diff --git a/docs/models/components/lastaction.md b/docs/models/components/lastaction.md index 58b1636..f8bed0a 100644 --- a/docs/models/components/lastaction.md +++ b/docs/models/components/lastaction.md @@ -2,6 +2,13 @@ The last action seen on this record +## Example Usage + +```typescript +import { LastAction } from "@speakeasy-sdks/nango/models/components"; + +let value: LastAction = LastAction.Deleted; +``` ## Values diff --git a/docs/models/components/latestresult.md b/docs/models/components/latestresult.md index e49938c..dee9fd9 100644 --- a/docs/models/components/latestresult.md +++ b/docs/models/components/latestresult.md @@ -2,6 +2,13 @@ Additional information regarding the latest result of the sync. Contains a model name with added, updated and deleted records +## Example Usage + +```typescript +import { LatestResult } from "@speakeasy-sdks/nango/models/components"; + +let value: LatestResult = {}; +``` ## Fields diff --git a/docs/models/components/listintegrationsrequest.md b/docs/models/components/listintegrationsrequest.md index 13d0797..3506b0f 100644 --- a/docs/models/components/listintegrationsrequest.md +++ b/docs/models/components/listintegrationsrequest.md @@ -1,5 +1,12 @@ # ListIntegrationsRequest +## Example Usage + +```typescript +import { ListIntegrationsRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: ListIntegrationsRequest = {}; +``` ## Fields diff --git a/docs/models/components/nangometadata.md b/docs/models/components/nangometadata.md index 09f90f8..704bb04 100644 --- a/docs/models/components/nangometadata.md +++ b/docs/models/components/nangometadata.md @@ -1,5 +1,15 @@ # NangoMetadata +## Example Usage + +```typescript +import { NangoMetadata } from "@speakeasy-sdks/nango/models/components"; + +let value: NangoMetadata = { + firstSeenAt: "2023-09-18T15:20:35.941305+00:00", + lastModifiedAt: "2023-09-18T15:20:35.941305+00:00", +}; +``` ## Fields diff --git a/docs/models/components/patchproxyrequest.md b/docs/models/components/patchproxyrequest.md index cce8564..68bf29a 100644 --- a/docs/models/components/patchproxyrequest.md +++ b/docs/models/components/patchproxyrequest.md @@ -1,5 +1,12 @@ # PatchProxyRequest +## Example Usage + +```typescript +import { PatchProxyRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: PatchProxyRequest = {}; +``` ## Fields diff --git a/docs/models/components/putproxyrequest.md b/docs/models/components/putproxyrequest.md index 6b8459e..2159c42 100644 --- a/docs/models/components/putproxyrequest.md +++ b/docs/models/components/putproxyrequest.md @@ -1,5 +1,12 @@ # PutProxyRequest +## Example Usage + +```typescript +import { PutProxyRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: PutProxyRequest = {}; +``` ## Fields diff --git a/docs/models/components/records.md b/docs/models/components/records.md index 78d5851..9ab0e6e 100644 --- a/docs/models/components/records.md +++ b/docs/models/components/records.md @@ -1,5 +1,19 @@ # Records +## Example Usage + +```typescript +import { Records } from "@speakeasy-sdks/nango/models/components"; + +let value: Records = { + yourProperties: + "Your synced data, in the schema you (or Nango) defined in nango.yaml", + nangoMetadata: { + firstSeenAt: "2023-09-18T15:20:35.941305+00:00", + lastModifiedAt: "2023-09-18T15:20:35.941305+00:00", + }, +}; +``` ## Fields diff --git a/docs/models/components/status.md b/docs/models/components/status.md index bcc1171..6a17dfc 100644 --- a/docs/models/components/status.md +++ b/docs/models/components/status.md @@ -2,6 +2,13 @@ The current status of the sync. +## Example Usage + +```typescript +import { Status } from "@speakeasy-sdks/nango/models/components"; + +let value: Status = Status.Success; +``` ## Values diff --git a/docs/models/components/syncs.md b/docs/models/components/syncs.md index 5c46d9e..55f62c0 100644 --- a/docs/models/components/syncs.md +++ b/docs/models/components/syncs.md @@ -1,5 +1,12 @@ # Syncs +## Example Usage + +```typescript +import { Syncs } from "@speakeasy-sdks/nango/models/components"; + +let value: Syncs = {}; +``` ## Fields diff --git a/docs/models/components/type.md b/docs/models/components/type.md index f56b043..8f7d1fa 100644 --- a/docs/models/components/type.md +++ b/docs/models/components/type.md @@ -2,6 +2,13 @@ The most recent sync type completed +## Example Usage + +```typescript +import { Type } from "@speakeasy-sdks/nango/models/components"; + +let value: Type = Type.Initial; +``` ## Values diff --git a/docs/models/components/updateconnectionfrequencyrequest.md b/docs/models/components/updateconnectionfrequencyrequest.md index a2b3666..6c22af5 100644 --- a/docs/models/components/updateconnectionfrequencyrequest.md +++ b/docs/models/components/updateconnectionfrequencyrequest.md @@ -1,5 +1,17 @@ # UpdateConnectionFrequencyRequest +## Example Usage + +```typescript +import { UpdateConnectionFrequencyRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: UpdateConnectionFrequencyRequest = { + providerConfigKey: "", + connectionId: "", + syncName: "", + frequency: "", +}; +``` ## Fields diff --git a/docs/models/components/updateconnectionfrequencyresponse.md b/docs/models/components/updateconnectionfrequencyresponse.md index 9712d9d..8131b40 100644 --- a/docs/models/components/updateconnectionfrequencyresponse.md +++ b/docs/models/components/updateconnectionfrequencyresponse.md @@ -1,5 +1,12 @@ # UpdateConnectionFrequencyResponse +## Example Usage + +```typescript +import { UpdateConnectionFrequencyResponse } from "@speakeasy-sdks/nango/models/components"; + +let value: UpdateConnectionFrequencyResponse = {}; +``` ## Fields diff --git a/docs/models/components/updateintegrationrequest.md b/docs/models/components/updateintegrationrequest.md index cd9b214..c70a5d0 100644 --- a/docs/models/components/updateintegrationrequest.md +++ b/docs/models/components/updateintegrationrequest.md @@ -1,5 +1,12 @@ # UpdateIntegrationRequest +## Example Usage + +```typescript +import { UpdateIntegrationRequest } from "@speakeasy-sdks/nango/models/components"; + +let value: UpdateIntegrationRequest = {}; +``` ## Fields diff --git a/docs/models/errors/response400.md b/docs/models/errors/response400.md index b95d24a..55c26d7 100644 --- a/docs/models/errors/response400.md +++ b/docs/models/errors/response400.md @@ -1,7 +1,12 @@ # Response400 -Invalid request +## Example Usage +```typescript +import { Response400 } from "@speakeasy-sdks/nango/models/errors"; + +// No examples available for this model +``` ## Fields diff --git a/docs/models/errors/response404.md b/docs/models/errors/response404.md index d0b77f6..12c9696 100644 --- a/docs/models/errors/response404.md +++ b/docs/models/errors/response404.md @@ -1,7 +1,12 @@ # Response404 -Unknown integration +## Example Usage +```typescript +import { Response404 } from "@speakeasy-sdks/nango/models/errors"; + +// No examples available for this model +``` ## Fields diff --git a/docs/models/operations/createactiontriggerrequest.md b/docs/models/operations/createactiontriggerrequest.md index bc1e0fc..00aadce 100644 --- a/docs/models/operations/createactiontriggerrequest.md +++ b/docs/models/operations/createactiontriggerrequest.md @@ -1,5 +1,18 @@ # CreateActionTriggerRequest +## Example Usage + +```typescript +import { CreateActionTriggerRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: CreateActionTriggerRequest = { + connectionId: "", + providerConfigKey: "", + createActionTriggerRequest: { + actionName: "", + }, +}; +``` ## Fields diff --git a/docs/models/operations/createmetadatarequest.md b/docs/models/operations/createmetadatarequest.md index 8ee0651..73f855a 100644 --- a/docs/models/operations/createmetadatarequest.md +++ b/docs/models/operations/createmetadatarequest.md @@ -1,5 +1,16 @@ # CreateMetadataRequest +## Example Usage + +```typescript +import { CreateMetadataRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: CreateMetadataRequest = { + connectionId: "", + providerConfigKey: "", + requestBody: {}, +}; +``` ## Fields diff --git a/docs/models/operations/createmetadatarequestbody.md b/docs/models/operations/createmetadatarequestbody.md index ac65dac..c73e96e 100644 --- a/docs/models/operations/createmetadatarequestbody.md +++ b/docs/models/operations/createmetadatarequestbody.md @@ -1,5 +1,12 @@ # CreateMetadataRequestBody +## Example Usage + +```typescript +import { CreateMetadataRequestBody } from "@speakeasy-sdks/nango/models/operations"; + +let value: CreateMetadataRequestBody = {}; +``` ## Fields diff --git a/docs/models/operations/createproxyrequest.md b/docs/models/operations/createproxyrequest.md index cba968f..3f05834 100644 --- a/docs/models/operations/createproxyrequest.md +++ b/docs/models/operations/createproxyrequest.md @@ -1,5 +1,16 @@ # CreateProxyRequest +## Example Usage + +```typescript +import { CreateProxyRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: CreateProxyRequest = { + anyPath: "", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/deleteconnectionsrequest.md b/docs/models/operations/deleteconnectionsrequest.md index d8d9e67..74ecd4d 100644 --- a/docs/models/operations/deleteconnectionsrequest.md +++ b/docs/models/operations/deleteconnectionsrequest.md @@ -1,5 +1,15 @@ # DeleteConnectionsRequest +## Example Usage + +```typescript +import { DeleteConnectionsRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: DeleteConnectionsRequest = { + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/deleteintegrationrequest.md b/docs/models/operations/deleteintegrationrequest.md index 7f4bcc4..1579196 100644 --- a/docs/models/operations/deleteintegrationrequest.md +++ b/docs/models/operations/deleteintegrationrequest.md @@ -1,5 +1,14 @@ # DeleteIntegrationRequest +## Example Usage + +```typescript +import { DeleteIntegrationRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: DeleteIntegrationRequest = { + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/deleteproxyrequest.md b/docs/models/operations/deleteproxyrequest.md index 35281a2..7617c8f 100644 --- a/docs/models/operations/deleteproxyrequest.md +++ b/docs/models/operations/deleteproxyrequest.md @@ -1,5 +1,17 @@ # DeleteProxyRequest +## Example Usage + +```typescript +import { DeleteProxyRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: DeleteProxyRequest = { + anyPath: "", + dollarANYQUERYPARAMS: "", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/filter.md b/docs/models/operations/filter.md index 0746bb9..3fecb2c 100644 --- a/docs/models/operations/filter.md +++ b/docs/models/operations/filter.md @@ -2,6 +2,13 @@ Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. +## Example Usage + +```typescript +import { Filter } from "@speakeasy-sdks/nango/models/operations"; + +let value: Filter = Filter.Updated; +``` ## Values diff --git a/docs/models/operations/getconnectionsrequest.md b/docs/models/operations/getconnectionsrequest.md index fcd5ff7..25a8c5e 100644 --- a/docs/models/operations/getconnectionsrequest.md +++ b/docs/models/operations/getconnectionsrequest.md @@ -1,5 +1,15 @@ # GetConnectionsRequest +## Example Usage + +```typescript +import { GetConnectionsRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetConnectionsRequest = { + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/getintegrationrequest.md b/docs/models/operations/getintegrationrequest.md index f695725..ee5d712 100644 --- a/docs/models/operations/getintegrationrequest.md +++ b/docs/models/operations/getintegrationrequest.md @@ -1,5 +1,14 @@ # GetIntegrationRequest +## Example Usage + +```typescript +import { GetIntegrationRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetIntegrationRequest = { + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/getproxyrequest.md b/docs/models/operations/getproxyrequest.md index 2d872f9..680b4fa 100644 --- a/docs/models/operations/getproxyrequest.md +++ b/docs/models/operations/getproxyrequest.md @@ -1,5 +1,17 @@ # GetProxyRequest +## Example Usage + +```typescript +import { GetProxyRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetProxyRequest = { + anyPath: "", + dollarANYQUERYPARAMS: "", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/getrecordrequest.md b/docs/models/operations/getrecordrequest.md index 4be8872..fd9ceb0 100644 --- a/docs/models/operations/getrecordrequest.md +++ b/docs/models/operations/getrecordrequest.md @@ -1,5 +1,16 @@ # GetRecordRequest +## Example Usage + +```typescript +import { GetRecordRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetRecordRequest = { + model: "LeBaron", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/getsyncrecordrequest.md b/docs/models/operations/getsyncrecordrequest.md index f5c9278..0ad951d 100644 --- a/docs/models/operations/getsyncrecordrequest.md +++ b/docs/models/operations/getsyncrecordrequest.md @@ -1,5 +1,16 @@ # GetSyncRecordRequest +## Example Usage + +```typescript +import { GetSyncRecordRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetSyncRecordRequest = { + model: "El Camino", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/getsyncstatusrequest.md b/docs/models/operations/getsyncstatusrequest.md index d37ffd2..0bc4fc6 100644 --- a/docs/models/operations/getsyncstatusrequest.md +++ b/docs/models/operations/getsyncstatusrequest.md @@ -1,5 +1,15 @@ # GetSyncStatusRequest +## Example Usage + +```typescript +import { GetSyncStatusRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: GetSyncStatusRequest = { + providerConfigKey: "", + syncs: "", +}; +``` ## Fields diff --git a/docs/models/operations/listconnectionsrequest.md b/docs/models/operations/listconnectionsrequest.md index 6a21108..85bc49e 100644 --- a/docs/models/operations/listconnectionsrequest.md +++ b/docs/models/operations/listconnectionsrequest.md @@ -1,5 +1,12 @@ # ListConnectionsRequest +## Example Usage + +```typescript +import { ListConnectionsRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: ListConnectionsRequest = {}; +``` ## Fields diff --git a/docs/models/operations/order.md b/docs/models/operations/order.md index 999fded..fd0fb15 100644 --- a/docs/models/operations/order.md +++ b/docs/models/operations/order.md @@ -2,6 +2,13 @@ Set the order of results. The default is 'desc'. The options are 'desc' or 'asc'. +## Example Usage + +```typescript +import { Order } from "@speakeasy-sdks/nango/models/operations"; + +let value: Order = Order.Asc; +``` ## Values diff --git a/docs/models/operations/patchproxyrequest.md b/docs/models/operations/patchproxyrequest.md index 34dd2eb..f5bd181 100644 --- a/docs/models/operations/patchproxyrequest.md +++ b/docs/models/operations/patchproxyrequest.md @@ -1,5 +1,16 @@ # PatchProxyRequest +## Example Usage + +```typescript +import { PatchProxyRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: PatchProxyRequest = { + anyPath: "", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/putproxyrequest.md b/docs/models/operations/putproxyrequest.md index 33ff0b4..8493693 100644 --- a/docs/models/operations/putproxyrequest.md +++ b/docs/models/operations/putproxyrequest.md @@ -1,5 +1,16 @@ # PutProxyRequest +## Example Usage + +```typescript +import { PutProxyRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: PutProxyRequest = { + anyPath: "", + connectionId: "", + providerConfigKey: "", +}; +``` ## Fields diff --git a/docs/models/operations/queryparamfilter.md b/docs/models/operations/queryparamfilter.md index c769518..6c429c5 100644 --- a/docs/models/operations/queryparamfilter.md +++ b/docs/models/operations/queryparamfilter.md @@ -2,6 +2,13 @@ Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. +## Example Usage + +```typescript +import { QueryParamFilter } from "@speakeasy-sdks/nango/models/operations"; + +let value: QueryParamFilter = QueryParamFilter.Deleted; +``` ## Values diff --git a/docs/models/operations/sortby.md b/docs/models/operations/sortby.md index bfcc06c..4fbc683 100644 --- a/docs/models/operations/sortby.md +++ b/docs/models/operations/sortby.md @@ -2,6 +2,13 @@ Set how the records are sorted. The default is id. The options are 'created_at', 'updated_at', 'id'. +## Example Usage + +```typescript +import { SortBy } from "@speakeasy-sdks/nango/models/operations"; + +let value: SortBy = SortBy.UpdatedAt; +``` ## Values diff --git a/docs/models/operations/updatemetadatarequest.md b/docs/models/operations/updatemetadatarequest.md index 67df012..4063dc5 100644 --- a/docs/models/operations/updatemetadatarequest.md +++ b/docs/models/operations/updatemetadatarequest.md @@ -1,5 +1,16 @@ # UpdateMetadataRequest +## Example Usage + +```typescript +import { UpdateMetadataRequest } from "@speakeasy-sdks/nango/models/operations"; + +let value: UpdateMetadataRequest = { + connectionId: "", + providerConfigKey: "", + requestBody: {}, +}; +``` ## Fields diff --git a/docs/models/operations/updatemetadatarequestbody.md b/docs/models/operations/updatemetadatarequestbody.md index f61a2b5..ba2a890 100644 --- a/docs/models/operations/updatemetadatarequestbody.md +++ b/docs/models/operations/updatemetadatarequestbody.md @@ -1,5 +1,12 @@ # UpdateMetadataRequestBody +## Example Usage + +```typescript +import { UpdateMetadataRequestBody } from "@speakeasy-sdks/nango/models/operations"; + +let value: UpdateMetadataRequestBody = {}; +``` ## Fields diff --git a/docs/models/operations/updatemetadataresponsebody.md b/docs/models/operations/updatemetadataresponsebody.md index e2320f2..9d14cb7 100644 --- a/docs/models/operations/updatemetadataresponsebody.md +++ b/docs/models/operations/updatemetadataresponsebody.md @@ -2,6 +2,13 @@ Successfully updated the metadata +## Example Usage + +```typescript +import { UpdateMetadataResponseBody } from "@speakeasy-sdks/nango/models/operations"; + +let value: UpdateMetadataResponseBody = {}; +``` ## Fields diff --git a/docs/sdks/actions/README.md b/docs/sdks/actions/README.md index 74ba993..3664d4c 100644 --- a/docs/sdks/actions/README.md +++ b/docs/sdks/actions/README.md @@ -1,6 +1,8 @@ # Actions (*actions*) +## Overview + ### Available Operations * [createTrigger](#createtrigger) - Triggers an action for a connection. @@ -17,12 +19,42 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.actions.createTrigger("", "", { + const result = await nango.actions.createTrigger("", "", { + actionName: "", + }); + + // Handle the result + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { actionsCreateTrigger } from "@speakeasy-sdks/nango/funcs/actionsCreateTrigger.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await actionsCreateTrigger(nango, "", "", { actionName: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + // Handle the result - console.log(result) + console.log(result); } run(); @@ -37,14 +69,15 @@ run(); | `createActionTriggerRequest` | [components.CreateActionTriggerRequest](../../models/components/createactiontriggerrequest.md) | :heavy_check_mark: | N/A | | `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.CreateActionTriggerResponse](../../models/components/createactiontriggerresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/connections/README.md b/docs/sdks/connections/README.md index 6936ada..718746b 100644 --- a/docs/sdks/connections/README.md +++ b/docs/sdks/connections/README.md @@ -1,6 +1,8 @@ # Connections (*connections*) +## Overview + ### Available Operations * [list](#list) - Returns a list of connections, optionally filtered by connection ID. @@ -22,10 +24,38 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.connections.list(""); + const result = await nango.connections.list(); + + // Handle the result + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsList } from "@speakeasy-sdks/nango/funcs/connectionsList.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsList(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; // Handle the result - console.log(result) + console.log(result); } run(); @@ -38,16 +68,17 @@ run(); | `connectionId` | *string* | :heavy_minus_sign: | Filter the list of connections based on this connection ID. | | `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.GetConnectionResponse](../../models/components/getconnectionresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## create @@ -63,6 +94,33 @@ const nango = new Nango(); async function run() { await nango.connections.create({}); + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsCreate } from "@speakeasy-sdks/nango/funcs/connectionsCreate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsCreate(nango, {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -76,17 +134,18 @@ run(); | `request` | [components.CreateConnectionRequest](../../models/components/createconnectionrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## get @@ -100,7 +159,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.connections.get("", "", false, false); + await nango.connections.get("", ""); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsGet } from "@speakeasy-sdks/nango/funcs/connectionsGet.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsGet(nango, "", ""); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -118,18 +204,19 @@ run(); | `refreshToken` | *boolean* | :heavy_minus_sign: | If true, return the refresh token as part of the response (false by default). | | `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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | | errors.Response404 | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## delete @@ -143,7 +230,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.connections.delete("", ""); + await nango.connections.delete("", ""); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsDelete } from "@speakeasy-sdks/nango/funcs/connectionsDelete.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsDelete(nango, "", ""); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -159,18 +273,19 @@ run(); | `providerConfigKey` | *string* | :heavy_check_mark: | The integration ID used to create the connection (aka Unique Key). | | `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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | | errors.Response404 | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## createMetadata @@ -184,7 +299,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.connections.createMetadata("", "", {}); + await nango.connections.createMetadata("", "", {}); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsCreateMetadata } from "@speakeasy-sdks/nango/funcs/connectionsCreateMetadata.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsCreateMetadata(nango, "", "", {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -201,17 +343,18 @@ run(); | `requestBody` | [operations.CreateMetadataRequestBody](../../models/operations/createmetadatarequestbody.md) | :heavy_check_mark: | N/A | | `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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## update @@ -225,10 +368,38 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.connections.update("", "", {}); + const result = await nango.connections.update("", "", {}); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { connectionsUpdate } from "@speakeasy-sdks/nango/funcs/connectionsUpdate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await connectionsUpdate(nango, "", "", {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -243,14 +414,15 @@ run(); | `requestBody` | [operations.UpdateMetadataRequestBody](../../models/operations/updatemetadatarequestbody.md) | :heavy_check_mark: | N/A | | `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.UpdateMetadataResponseBody](../../models/operations/updatemetadataresponsebody.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/environment/README.md b/docs/sdks/environment/README.md index 695e4d3..51911ea 100644 --- a/docs/sdks/environment/README.md +++ b/docs/sdks/environment/README.md @@ -1,6 +1,8 @@ # Environment (*environment*) +## Overview + ### Available Operations * [get](#get) - Retrieve the environment variables as added in the Nango dashboard. @@ -20,7 +22,35 @@ async function run() { const result = await nango.environment.get(); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { environmentGet } from "@speakeasy-sdks/nango/funcs/environmentGet.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await environmentGet(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -32,13 +62,14 @@ run(); | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `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.GetEnvironmentVariableResponse[]](../../models/.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/integrations/README.md b/docs/sdks/integrations/README.md index 125154f..3f408a9 100644 --- a/docs/sdks/integrations/README.md +++ b/docs/sdks/integrations/README.md @@ -1,6 +1,8 @@ # Integrations (*integrations*) +## Overview + ### Available Operations * [list](#list) - Returns a list of integrations including their unique keys and providers as configured in the Nango API. @@ -24,7 +26,35 @@ async function run() { const result = await nango.integrations.list(); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsList } from "@speakeasy-sdks/nango/funcs/integrationsList.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsList(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -36,16 +66,17 @@ run(); | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `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.IntegrationsResponse200](../../models/components/integrationsresponse200.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## create @@ -62,7 +93,35 @@ async function run() { const result = await nango.integrations.create({}); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsCreate } from "@speakeasy-sdks/nango/funcs/integrationsCreate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsCreate(nango, {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -75,17 +134,18 @@ run(); | `request` | [components.ListIntegrationsRequest](../../models/components/listintegrationsrequest.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.IntegrationsResponse200](../../models/components/integrationsresponse200.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## update @@ -102,7 +162,35 @@ async function run() { const result = await nango.integrations.update({}); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsUpdate } from "@speakeasy-sdks/nango/funcs/integrationsUpdate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsUpdate(nango, {}); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -115,18 +203,19 @@ run(); | `request` | [components.UpdateIntegrationRequest](../../models/components/updateintegrationrequest.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.IntegrationsResponse200](../../models/components/integrationsresponse200.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | | errors.Response404 | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## get @@ -140,10 +229,38 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.integrations.get("", false); + const result = await nango.integrations.get(""); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsGet } from "@speakeasy-sdks/nango/funcs/integrationsGet.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsGet(nango, ""); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -157,18 +274,19 @@ run(); | `includeCreds` | *boolean* | :heavy_minus_sign: | If true, the response will contain the client ID, secret, scopes, auth_mode and app link - if applicable. include_creds is false by default. | | `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.GetIntegrationResponse](../../models/components/getintegrationresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | | errors.Response404 | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## delete @@ -184,6 +302,33 @@ const nango = new Nango(); async function run() { await nango.integrations.delete(""); + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { integrationsDelete } from "@speakeasy-sdks/nango/funcs/integrationsDelete.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await integrationsDelete(nango, ""); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -197,15 +342,16 @@ run(); | `providerConfigKey` | *string* | :heavy_check_mark: | The integration ID that you created in Nango. | | `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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | | errors.Response404 | 404 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/nango/README.md b/docs/sdks/nango/README.md index 124207e..78babf7 100644 --- a/docs/sdks/nango/README.md +++ b/docs/sdks/nango/README.md @@ -1,9 +1,7 @@ # Nango SDK - ## Overview Nango API: Nango API specs used to authorize & sync data with external APIs. ### Available Operations - diff --git a/docs/sdks/proxy/README.md b/docs/sdks/proxy/README.md index 5a06883..e339374 100644 --- a/docs/sdks/proxy/README.md +++ b/docs/sdks/proxy/README.md @@ -1,6 +1,8 @@ # Proxy (*proxy*) +## Overview + ### Available Operations * [get](#get) - Make a GET request with the Proxy. @@ -24,10 +26,42 @@ async function run() { await nango.proxy.get({ anyPath: "", dollarANYQUERYPARAMS: "", - connectionId: "", + connectionId: "", + providerConfigKey: "", + }); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { proxyGet } from "@speakeasy-sdks/nango/funcs/proxyGet.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await proxyGet(nango, { + anyPath: "", + dollarANYQUERYPARAMS: "", + connectionId: "", providerConfigKey: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -41,16 +75,17 @@ run(); | `request` | [operations.GetProxyRequest](../../models/operations/getproxyrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## create @@ -66,10 +101,41 @@ const nango = new Nango(); async function run() { await nango.proxy.create({ anyPath: "", - connectionId: "", + connectionId: "", + providerConfigKey: "", + }); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { proxyCreate } from "@speakeasy-sdks/nango/funcs/proxyCreate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await proxyCreate(nango, { + anyPath: "", + connectionId: "", providerConfigKey: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -83,16 +149,17 @@ run(); | `request` | [operations.CreateProxyRequest](../../models/operations/createproxyrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## update @@ -108,10 +175,41 @@ const nango = new Nango(); async function run() { await nango.proxy.update({ anyPath: "", - connectionId: "", + connectionId: "", providerConfigKey: "", }); + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { proxyUpdate } from "@speakeasy-sdks/nango/funcs/proxyUpdate.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await proxyUpdate(nango, { + anyPath: "", + connectionId: "", + providerConfigKey: "", + }); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -125,16 +223,17 @@ run(); | `request` | [operations.PutProxyRequest](../../models/operations/putproxyrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## modify @@ -150,10 +249,41 @@ const nango = new Nango(); async function run() { await nango.proxy.modify({ anyPath: "", - connectionId: "", + connectionId: "", + providerConfigKey: "", + }); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { proxyModify } from "@speakeasy-sdks/nango/funcs/proxyModify.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await proxyModify(nango, { + anyPath: "", + connectionId: "", providerConfigKey: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -167,16 +297,17 @@ run(); | `request` | [operations.PatchProxyRequest](../../models/operations/patchproxyrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## delete @@ -193,10 +324,42 @@ async function run() { await nango.proxy.delete({ anyPath: "", dollarANYQUERYPARAMS: "", - connectionId: "", + connectionId: "", providerConfigKey: "", }); + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { proxyDelete } from "@speakeasy-sdks/nango/funcs/proxyDelete.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await proxyDelete(nango, { + anyPath: "", + dollarANYQUERYPARAMS: "", + connectionId: "", + providerConfigKey: "", + }); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + } @@ -210,13 +373,14 @@ run(); | `request` | [operations.DeleteProxyRequest](../../models/operations/deleteproxyrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | --------------- | --------------- | --------------- | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/records/README.md b/docs/sdks/records/README.md index 0731b82..f469d59 100644 --- a/docs/sdks/records/README.md +++ b/docs/sdks/records/README.md @@ -1,6 +1,8 @@ # Records (*records*) +## Overview + ### Available Operations * [get](#get) - Returns data synced with Nango Sync, filtered by specified parameters. @@ -18,13 +20,45 @@ const nango = new Nango(); async function run() { const result = await nango.records.get({ - model: "Sentra", - connectionId: "", + model: "Model S", + connectionId: "", + providerConfigKey: "", + }); + + // Handle the result + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { recordsGet } from "@speakeasy-sdks/nango/funcs/recordsGet.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await recordsGet(nango, { + model: "Model S", + connectionId: "", providerConfigKey: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + // Handle the result - console.log(result) + console.log(result); } run(); @@ -37,14 +71,15 @@ run(); | `request` | [operations.GetRecordRequest](../../models/operations/getrecordrequest.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.GetRecordResponse](../../models/components/getrecordresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/sync/README.md b/docs/sdks/sync/README.md index 2543d8d..01c559e 100644 --- a/docs/sdks/sync/README.md +++ b/docs/sdks/sync/README.md @@ -1,6 +1,8 @@ # Sync (*sync*) +## Overview + ### Available Operations * [getRecord](#getrecord) - Returns data synced with Nango Sync, allowing for advanced filtering, sorting, and pagination options. @@ -23,13 +25,45 @@ const nango = new Nango(); async function run() { const result = await nango.sync.getRecord({ - model: "Expedition", - connectionId: "", + model: "ATS", + connectionId: "", providerConfigKey: "", }); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncGetRecord } from "@speakeasy-sdks/nango/funcs/syncGetRecord.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncGetRecord(nango, { + model: "ATS", + connectionId: "", + providerConfigKey: "", + }); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -42,17 +76,18 @@ run(); | `request` | [operations.GetSyncRecordRequest](../../models/operations/getsyncrecordrequest.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.GetSyncRecordResponse[]](../../models/.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## createTrigger @@ -66,12 +101,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.sync.createTrigger({ - providerConfigKey: "", - syncs: [ - "", - ], - }); + await nango.sync.createTrigger(); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncCreateTrigger } from "@speakeasy-sdks/nango/funcs/syncCreateTrigger.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncCreateTrigger(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -86,17 +143,18 @@ run(); | `request` | [components.CreateSyncTriggerRequest](../../models/components/createsynctriggerrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## start @@ -110,12 +168,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.sync.start({ - providerConfigKey: "", - syncs: [ - "", - ], - }); + await nango.sync.start(); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncStart } from "@speakeasy-sdks/nango/funcs/syncStart.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncStart(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -130,17 +210,18 @@ run(); | `request` | [components.CreateSyncStartRequest](../../models/components/createsyncstartrequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## pause @@ -154,12 +235,34 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - await nango.sync.pause({ - providerConfigKey: "", - syncs: [ - "", - ], - }); + await nango.sync.pause(); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncPause } from "@speakeasy-sdks/nango/funcs/syncPause.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncPause(nango); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; } @@ -174,17 +277,18 @@ run(); | `request` | [components.CreateSyncPauseRequest](../../models/components/createsyncpauserequest.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\** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## getStatus @@ -198,10 +302,38 @@ import { Nango } from "@speakeasy-sdks/nango"; const nango = new Nango(); async function run() { - const result = await nango.sync.getStatus("", "", ""); + const result = await nango.sync.getStatus("", ""); // Handle the result - console.log(result) + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncGetStatus } from "@speakeasy-sdks/nango/funcs/syncGetStatus.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncGetStatus(nango, "", ""); + + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + + // Handle the result + console.log(result); } run(); @@ -216,17 +348,18 @@ run(); | `connectionId` | *string* | :heavy_minus_sign: | The ID of the connection. If omitted, all connections will be surfaced. | | `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.GetSyncStatusResponse](../../models/components/getsyncstatusresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | ## updateFrequency @@ -242,13 +375,46 @@ const nango = new Nango(); async function run() { const result = await nango.sync.updateFrequency({ providerConfigKey: "", - connectionId: "", + connectionId: "", + syncName: "", + frequency: "", + }); + + // Handle the result + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { NangoCore } from "@speakeasy-sdks/nango/core.js"; +import { syncUpdateFrequency } from "@speakeasy-sdks/nango/funcs/syncUpdateFrequency.js"; + +// Use `NangoCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const nango = new NangoCore(); + +async function run() { + const res = await syncUpdateFrequency(nango, { + providerConfigKey: "", + connectionId: "", syncName: "", frequency: "", }); + if (!res.ok) { + throw res.error; + } + + const { value: result } = res; + // Handle the result - console.log(result) + console.log(result); } run(); @@ -261,14 +427,15 @@ run(); | `request` | [components.UpdateConnectionFrequencyRequest](../../models/components/updateconnectionfrequencyrequest.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.UpdateConnectionFrequencyResponse](../../models/components/updateconnectionfrequencyresponse.md)\>** + ### Errors -| Error Object | Status Code | Content Type | +| Error Type | Status Code | Content Type | | ------------------ | ------------------ | ------------------ | | errors.Response400 | 400 | application/json | -| errors.SDKError | 4xx-5xx | */* | +| errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/gen.yaml b/gen.yaml index b4534d4..15fded4 100644 --- a/gen.yaml +++ b/gen.yaml @@ -11,8 +11,9 @@ generation: requestResponseComponentNamesFeb2024: false auth: oAuth2ClientCredentialsEnabled: false + oAuth2PasswordEnabled: false typescript: - version: 0.9.1 + version: 0.10.0 additionalDependencies: dependencies: {} devDependencies: {} @@ -20,8 +21,12 @@ typescript: additionalPackageJSON: {} author: Speakeasy clientServerStatusCodesAsErrors: true + defaultErrorName: SDKError + enableCustomCodeRegions: false + enableReactQuery: false enumFormat: enum flattenGlobalSecurity: true + flatteningOrder: parameters-first imports: option: openapi paths: @@ -33,6 +38,7 @@ typescript: inputModelSuffix: input maxMethodParams: 4 methodArguments: require-security-and-request + moduleFormat: commonjs outputModelSuffix: output packageName: '@speakeasy-sdks/nango' responseFormat: flat diff --git a/jsr.json b/jsr.json index c951952..7a3422c 100644 --- a/jsr.json +++ b/jsr.json @@ -2,7 +2,7 @@ { "name": "@speakeasy-sdks/nango", - "version": "0.9.1", + "version": "0.10.0", "exports": { ".": "./src/index.ts", "./models/errors": "./src/models/errors/index.ts", diff --git a/package-lock.json b/package-lock.json index 498899b..91566d5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,14 +1,13 @@ { - "name": "@simplesagar92/nango", - "version": "0.6.0", + "name": "@speakeasy-sdks/nango", + "version": "0.10.0", "lockfileVersion": 2, "requires": true, "packages": { "": { - "name": "@simplesagar92/nango", - "version": "0.6.0", + "name": "@speakeasy-sdks/nango", + "version": "0.10.0", "devDependencies": { - "@types/jsonpath": "^0.2.4", "@typescript-eslint/eslint-plugin": "^7.7.1", "@typescript-eslint/parser": "^7.7.1", "eslint": "^8.57.0", @@ -204,12 +203,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.13.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.13.0.tgz", @@ -3144,12 +3137,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.13.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.13.0.tgz", diff --git a/package.json b/package.json index 89b9414..9471f8e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@speakeasy-sdks/nango", - "version": "0.9.1", - "author": "Speakeasy", + "version": "0.10.0", + "author": "Speakeasy", "main": "./index.js", "sideEffects": false, "repository": { @@ -12,13 +12,12 @@ "scripts": { "lint": "eslint --max-warnings=0 src", "build": "tsc", - "prepare": "npm run build" + "prepublishOnly": "npm run build" }, "peerDependencies": { "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/src/core.ts b/src/core.ts new file mode 100644 index 0000000..ce9a178 --- /dev/null +++ b/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 NangoCore extends ClientSDK {} diff --git a/src/funcs/actionsCreateTrigger.ts b/src/funcs/actionsCreateTrigger.ts new file mode 100644 index 0000000..723ca41 --- /dev/null +++ b/src/funcs/actionsCreateTrigger.ts @@ -0,0 +1,149 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Triggers an action for a connection. + * + * @remarks + * Triggers an action for a connection + */ +export async function actionsCreateTrigger( + client: NangoCore, + connectionId: string, + providerConfigKey: string, + createActionTriggerRequest: components.CreateActionTriggerRequest, + options?: RequestOptions, +): Promise< + Result< + components.CreateActionTriggerResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.CreateActionTriggerRequest = { + connectionId: connectionId, + providerConfigKey: providerConfigKey, + createActionTriggerRequest: createActionTriggerRequest, + }; + + const parsed = safeParse( + input, + (value) => + operations.CreateActionTriggerRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.CreateActionTriggerRequest, { + explode: true, + }); + + const path = pathToFunc("/action/trigger")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "createActionTrigger", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.CreateActionTriggerResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.CreateActionTriggerResponse$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsCreate.ts b/src/funcs/connectionsCreate.ts new file mode 100644 index 0000000..5f2f7bf --- /dev/null +++ b/src/funcs/connectionsCreate.ts @@ -0,0 +1,115 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Adds a connection using an existing access token, along with optional OAuth or basic authentication credentials, and additional metadata or configuration. + * + * @remarks + * Adds a connection for which you already have an access token + */ +export async function connectionsCreate( + client: NangoCore, + _request: components.CreateConnectionRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const path = pathToFunc("/connection")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "createConnection", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsCreateMetadata.ts b/src/funcs/connectionsCreateMetadata.ts new file mode 100644 index 0000000..3a3752e --- /dev/null +++ b/src/funcs/connectionsCreateMetadata.ts @@ -0,0 +1,149 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Set custom metadata for the specified connection. + * + * @remarks + * Set custom metadata for the connection. + */ +export async function connectionsCreateMetadata( + client: NangoCore, + connectionId: string, + providerConfigKey: string, + requestBody: operations.CreateMetadataRequestBody, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.CreateMetadataRequest = { + connectionId: connectionId, + providerConfigKey: providerConfigKey, + requestBody: requestBody, + }; + + const parsed = safeParse( + input, + (value) => operations.CreateMetadataRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.RequestBody, { explode: true }); + + const pathParams = { + connectionId: encodeSimple("connectionId", payload.connectionId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/connection/{connectionId}/metadata")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "createMetadata", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(201, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsDelete.ts b/src/funcs/connectionsDelete.ts new file mode 100644 index 0000000..51d558b --- /dev/null +++ b/src/funcs/connectionsDelete.ts @@ -0,0 +1,149 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Deletes a specific connection identified by its connection ID, associated with the specified integration. + * + * @remarks + * Deletes a specific connection + */ +export async function connectionsDelete( + client: NangoCore, + connectionId: string, + providerConfigKey: string, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.DeleteConnectionsRequest = { + connectionId: connectionId, + providerConfigKey: providerConfigKey, + }; + + const parsed = safeParse( + input, + (value) => operations.DeleteConnectionsRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + connectionId: encodeSimple("connectionId", payload.connectionId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/connection/{connectionId}")(pathParams); + + const query = encodeFormQuery({ + "provider_config_key": payload.provider_config_key, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "deleteConnections", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "DELETE", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(204, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.jsonErr(404, errors.Response404$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsGet.ts b/src/funcs/connectionsGet.ts new file mode 100644 index 0000000..d5617a4 --- /dev/null +++ b/src/funcs/connectionsGet.ts @@ -0,0 +1,155 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Returns details of a specific connection identified by its connection ID, associated with the specified integration, with optional parameters for force refresh and returning the refresh token. + * + * @remarks + * Returns a specific connection + */ +export async function connectionsGet( + client: NangoCore, + connectionId: string, + providerConfigKey: string, + forceRefresh?: boolean | undefined, + refreshToken?: boolean | undefined, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.GetConnectionsRequest = { + connectionId: connectionId, + providerConfigKey: providerConfigKey, + forceRefresh: forceRefresh, + refreshToken: refreshToken, + }; + + const parsed = safeParse( + input, + (value) => operations.GetConnectionsRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + connectionId: encodeSimple("connectionId", payload.connectionId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/connection/{connectionId}")(pathParams); + + const query = encodeFormQuery({ + "force_refresh": payload.force_refresh, + "provider_config_key": payload.provider_config_key, + "refresh_token": payload.refresh_token, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "getConnections", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.jsonErr(404, errors.Response404$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsList.ts b/src/funcs/connectionsList.ts new file mode 100644 index 0000000..fa32923 --- /dev/null +++ b/src/funcs/connectionsList.ts @@ -0,0 +1,129 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Returns a list of connections, optionally filtered by connection ID. + * + * @remarks + * Returns a list of connections + */ +export async function connectionsList( + client: NangoCore, + connectionId?: string | undefined, + options?: RequestOptions, +): Promise< + Result< + components.GetConnectionResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.ListConnectionsRequest = { + connectionId: connectionId, + }; + + const parsed = safeParse( + input, + (value) => operations.ListConnectionsRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const path = pathToFunc("/connection")(); + + const query = encodeFormQuery({ + "connectionId": payload.connectionId, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "listConnections", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + components.GetConnectionResponse, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.GetConnectionResponse$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/connectionsUpdate.ts b/src/funcs/connectionsUpdate.ts new file mode 100644 index 0000000..efbda7b --- /dev/null +++ b/src/funcs/connectionsUpdate.ts @@ -0,0 +1,148 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Update custom metadata for the specified connection. + * + * @remarks + * Update custom metadata for the connection. + */ +export async function connectionsUpdate( + client: NangoCore, + connectionId: string, + providerConfigKey: string, + requestBody: operations.UpdateMetadataRequestBody, + options?: RequestOptions, +): Promise< + Result< + operations.UpdateMetadataResponseBody, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.UpdateMetadataRequest = { + connectionId: connectionId, + providerConfigKey: providerConfigKey, + requestBody: requestBody, + }; + + const parsed = safeParse( + input, + (value) => operations.UpdateMetadataRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.RequestBody, { explode: true }); + + const pathParams = { + connectionId: encodeSimple("connectionId", payload.connectionId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/connection/{connectionId}/metadata")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "updateMetadata", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "PATCH", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + operations.UpdateMetadataResponseBody, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, operations.UpdateMetadataResponseBody$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/environmentGet.ts b/src/funcs/environmentGet.ts new file mode 100644 index 0000000..f08e823 --- /dev/null +++ b/src/funcs/environmentGet.ts @@ -0,0 +1,108 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.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"; + +/** + * Retrieve the environment variables as added in the Nango dashboard. + * + * @remarks + * Retrieve the environment variables as added in the Nango dashboard + */ +export async function environmentGet( + client: NangoCore, + options?: RequestOptions, +): Promise< + Result< + Array, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const path = pathToFunc("/environment-variables")(); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "getEnvironmentVariable", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + Array, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json( + 200, + z.array(components.GetEnvironmentVariableResponse$inboundSchema), + ), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/integrationsCreate.ts b/src/funcs/integrationsCreate.ts new file mode 100644 index 0000000..f48b8d3 --- /dev/null +++ b/src/funcs/integrationsCreate.ts @@ -0,0 +1,114 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. + * + * @remarks + * Create a new integration + */ +export async function integrationsCreate( + client: NangoCore, + _request: components.ListIntegrationsRequest, + options?: RequestOptions, +): Promise< + Result< + components.IntegrationsResponse200, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const path = pathToFunc("/config")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "createIntegrations", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.IntegrationsResponse200, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.IntegrationsResponse200$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/integrationsDelete.ts b/src/funcs/integrationsDelete.ts new file mode 100644 index 0000000..0881979 --- /dev/null +++ b/src/funcs/integrationsDelete.ts @@ -0,0 +1,143 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Deletes a specific integration identified by its provider configuration key. + * + * @remarks + * Deletes a specific integration + */ +export async function integrationsDelete( + client: NangoCore, + providerConfigKey: string, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.DeleteIntegrationRequest = { + providerConfigKey: providerConfigKey, + }; + + const parsed = safeParse( + input, + (value) => operations.DeleteIntegrationRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + providerConfigKey: encodeSimple( + "providerConfigKey", + payload.providerConfigKey, + { explode: false, charEncoding: "percent" }, + ), + }; + + const path = pathToFunc("/config/{providerConfigKey}")(pathParams); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "deleteIntegration", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "DELETE", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(204, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.jsonErr(404, errors.Response404$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/integrationsGet.ts b/src/funcs/integrationsGet.ts new file mode 100644 index 0000000..15b09d1 --- /dev/null +++ b/src/funcs/integrationsGet.ts @@ -0,0 +1,150 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. + * + * @remarks + * Returns a specific integration + */ +export async function integrationsGet( + client: NangoCore, + providerConfigKey: string, + includeCreds?: boolean | undefined, + options?: RequestOptions, +): Promise< + Result< + components.GetIntegrationResponse, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.GetIntegrationRequest = { + providerConfigKey: providerConfigKey, + includeCreds: includeCreds, + }; + + const parsed = safeParse( + input, + (value) => operations.GetIntegrationRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + providerConfigKey: encodeSimple( + "providerConfigKey", + payload.providerConfigKey, + { explode: false, charEncoding: "percent" }, + ), + }; + + const path = pathToFunc("/config/{providerConfigKey}")(pathParams); + + const query = encodeFormQuery({ + "include_creds": payload.include_creds, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "getIntegration", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.GetIntegrationResponse, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.GetIntegrationResponse$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.jsonErr(404, errors.Response404$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/integrationsList.ts b/src/funcs/integrationsList.ts new file mode 100644 index 0000000..4597b6e --- /dev/null +++ b/src/funcs/integrationsList.ts @@ -0,0 +1,104 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.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"; + +/** + * Returns a list of integrations including their unique keys and providers as configured in the Nango API. + * + * @remarks + * Returns a list of integrations + */ +export async function integrationsList( + client: NangoCore, + options?: RequestOptions, +): Promise< + Result< + components.IntegrationsResponse200, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const path = pathToFunc("/config")(); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "listIntegrations", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + components.IntegrationsResponse200, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.IntegrationsResponse200$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/integrationsUpdate.ts b/src/funcs/integrationsUpdate.ts new file mode 100644 index 0000000..ccb9342 --- /dev/null +++ b/src/funcs/integrationsUpdate.ts @@ -0,0 +1,117 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. + * + * @remarks + * Edit an integration (only for OAuth APIs) + */ +export async function integrationsUpdate( + client: NangoCore, + _request: components.UpdateIntegrationRequest, + options?: RequestOptions, +): Promise< + Result< + components.IntegrationsResponse200, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const path = pathToFunc("/config")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "updateIntegration", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "PUT", + baseURL: options?.serverURL, + path: path, + headers: headers, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.IntegrationsResponse200, + | errors.Response400 + | errors.Response404 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.IntegrationsResponse200$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.jsonErr(404, errors.Response404$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/proxyCreate.ts b/src/funcs/proxyCreate.ts new file mode 100644 index 0000000..713a178 --- /dev/null +++ b/src/funcs/proxyCreate.ts @@ -0,0 +1,157 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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"; + +/** + * Make a POST request with the Proxy. + * + * @remarks + * Make a POST request with the Proxy. + */ +export async function proxyCreate( + client: NangoCore, + request: operations.CreateProxyRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.CreateProxyRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.CreateProxyRequest, { + explode: true, + }); + + const pathParams = { + anyPath: encodeSimple("anyPath", payload.anyPath, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/proxy/{anyPath}")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "*/*", + "Base-Url-Override": encodeSimple( + "Base-Url-Override", + payload["Base-Url-Override"], + { explode: false, charEncoding: "none" }, + ), + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Decompress": encodeSimple("Decompress", payload.Decompress, { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + "Retries": encodeSimple("Retries", payload.Retries, { + explode: false, + charEncoding: "none", + }), + "nango-proxy-$ANY_HEADER": encodeSimple( + "nango-proxy-$ANY_HEADER", + payload["nango-proxy-$ANY_HEADER"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "createProxy", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/proxyDelete.ts b/src/funcs/proxyDelete.ts new file mode 100644 index 0000000..f1944a1 --- /dev/null +++ b/src/funcs/proxyDelete.ts @@ -0,0 +1,159 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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"; + +/** + * Make a DELETE request with the Proxy. + * + * @remarks + * Make a DELETE request with the Proxy. + */ +export async function proxyDelete( + client: NangoCore, + request: operations.DeleteProxyRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.DeleteProxyRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + anyPath: encodeSimple("anyPath", payload.anyPath, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/proxy/{anyPath}")(pathParams); + + const query = encodeFormQuery({ + "$ANY_QUERY_PARAMS": payload.$ANY_QUERY_PARAMS, + }); + + const headers = new Headers(compactMap({ + Accept: "*/*", + "Base-Url-Override": encodeSimple( + "Base-Url-Override", + payload["Base-Url-Override"], + { explode: false, charEncoding: "none" }, + ), + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Decompress": encodeSimple("Decompress", payload.Decompress, { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + "Retries": encodeSimple("Retries", payload.Retries, { + explode: false, + charEncoding: "none", + }), + "nango-proxy-$ANY_HEADER": encodeSimple( + "nango-proxy-$ANY_HEADER", + payload["nango-proxy-$ANY_HEADER"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "deleteProxy", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "DELETE", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/proxyGet.ts b/src/funcs/proxyGet.ts new file mode 100644 index 0000000..4bdee52 --- /dev/null +++ b/src/funcs/proxyGet.ts @@ -0,0 +1,159 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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"; + +/** + * Make a GET request with the Proxy. + * + * @remarks + * Make a GET request with the Proxy. + */ +export async function proxyGet( + client: NangoCore, + request: operations.GetProxyRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.GetProxyRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + anyPath: encodeSimple("anyPath", payload.anyPath, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/proxy/{anyPath}")(pathParams); + + const query = encodeFormQuery({ + "$ANY_QUERY_PARAMS": payload.$ANY_QUERY_PARAMS, + }); + + const headers = new Headers(compactMap({ + Accept: "*/*", + "Base-Url-Override": encodeSimple( + "Base-Url-Override", + payload["Base-Url-Override"], + { explode: false, charEncoding: "none" }, + ), + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Decompress": encodeSimple("Decompress", payload.Decompress, { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + "Retries": encodeSimple("Retries", payload.Retries, { + explode: false, + charEncoding: "none", + }), + "nango-proxy-$ANY_HEADER": encodeSimple( + "nango-proxy-$ANY_HEADER", + payload["nango-proxy-$ANY_HEADER"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "getProxy", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/proxyModify.ts b/src/funcs/proxyModify.ts new file mode 100644 index 0000000..fd7ea58 --- /dev/null +++ b/src/funcs/proxyModify.ts @@ -0,0 +1,155 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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"; + +/** + * Make a PATCH request with the Proxy. + * + * @remarks + * Make a PATCH request with the Proxy. + */ +export async function proxyModify( + client: NangoCore, + request: operations.PatchProxyRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.PatchProxyRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.PatchProxyRequest, { explode: true }); + + const pathParams = { + anyPath: encodeSimple("anyPath", payload.anyPath, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/proxy/{anyPath}")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "*/*", + "Base-Url-Override": encodeSimple( + "Base-Url-Override", + payload["Base-Url-Override"], + { explode: false, charEncoding: "none" }, + ), + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Decompress": encodeSimple("Decompress", payload.Decompress, { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + "Retries": encodeSimple("Retries", payload.Retries, { + explode: false, + charEncoding: "none", + }), + "nango-proxy-$ANY_HEADER": encodeSimple( + "nango-proxy-$ANY_HEADER", + payload["nango-proxy-$ANY_HEADER"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "patchProxy", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "PATCH", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/proxyUpdate.ts b/src/funcs/proxyUpdate.ts new file mode 100644 index 0000000..fac2e39 --- /dev/null +++ b/src/funcs/proxyUpdate.ts @@ -0,0 +1,155 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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"; + +/** + * Make a PUT request with the Proxy. + * + * @remarks + * Make a PUT request with the Proxy. + */ +export async function proxyUpdate( + client: NangoCore, + request: operations.PutProxyRequest, + options?: RequestOptions, +): Promise< + Result< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.PutProxyRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.PutProxyRequest, { explode: true }); + + const pathParams = { + anyPath: encodeSimple("anyPath", payload.anyPath, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/proxy/{anyPath}")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "*/*", + "Base-Url-Override": encodeSimple( + "Base-Url-Override", + payload["Base-Url-Override"], + { explode: false, charEncoding: "none" }, + ), + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Decompress": encodeSimple("Decompress", payload.Decompress, { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + "Retries": encodeSimple("Retries", payload.Retries, { + explode: false, + charEncoding: "none", + }), + "nango-proxy-$ANY_HEADER": encodeSimple( + "nango-proxy-$ANY_HEADER", + payload["nango-proxy-$ANY_HEADER"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "putProxy", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "PUT", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.fail("4XX"), + M.fail("5XX"), + )(response); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/recordsGet.ts b/src/funcs/recordsGet.ts new file mode 100644 index 0000000..7e934bf --- /dev/null +++ b/src/funcs/recordsGet.ts @@ -0,0 +1,146 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Returns data synced with Nango Sync, filtered by specified parameters. + * + * @remarks + * Returns data synced with Nango Sync + */ +export async function recordsGet( + client: NangoCore, + request: operations.GetRecordRequest, + options?: RequestOptions, +): Promise< + Result< + components.GetRecordResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.GetRecordRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const path = pathToFunc("/records")(); + + const query = encodeFormQuery({ + "cursor": payload.cursor, + "delta": payload.delta, + "filter": payload.filter, + "limit": payload.limit, + "model": payload.model, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "getRecord", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.GetRecordResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.GetRecordResponse$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncCreateTrigger.ts b/src/funcs/syncCreateTrigger.ts new file mode 100644 index 0000000..0533cd6 --- /dev/null +++ b/src/funcs/syncCreateTrigger.ts @@ -0,0 +1,134 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Triggers an additional, one-off execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Triggers an additional, one-off execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ +export async function syncCreateTrigger( + client: NangoCore, + request?: components.CreateSyncTriggerRequest | undefined, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => + components.CreateSyncTriggerRequest$outboundSchema.optional().parse( + value, + ), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/sync/trigger")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "createSyncTrigger", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncGetRecord.ts b/src/funcs/syncGetRecord.ts new file mode 100644 index 0000000..69d37d5 --- /dev/null +++ b/src/funcs/syncGetRecord.ts @@ -0,0 +1,149 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Returns data synced with Nango Sync, allowing for advanced filtering, sorting, and pagination options. + * + * @remarks + * Returns data synced with Nango Sync + */ +export async function syncGetRecord( + client: NangoCore, + request: operations.GetSyncRecordRequest, + options?: RequestOptions, +): Promise< + Result< + Array, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => operations.GetSyncRecordRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const path = pathToFunc("/sync/records")(); + + const query = encodeFormQuery({ + "delta": payload.delta, + "filter": payload.filter, + "limit": payload.limit, + "model": payload.model, + "offset": payload.offset, + "order": payload.order, + "sort_by": payload.sort_by, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + "Connection-Id": encodeSimple("Connection-Id", payload["Connection-Id"], { + explode: false, + charEncoding: "none", + }), + "Provider-Config-Key": encodeSimple( + "Provider-Config-Key", + payload["Provider-Config-Key"], + { explode: false, charEncoding: "none" }, + ), + })); + + const context = { + operationID: "getSyncRecord", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + Array, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, z.array(components.GetSyncRecordResponse$inboundSchema)), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncGetStatus.ts b/src/funcs/syncGetStatus.ts new file mode 100644 index 0000000..ab7ae94 --- /dev/null +++ b/src/funcs/syncGetStatus.ts @@ -0,0 +1,143 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeFormQuery } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { Result } from "../types/fp.js"; + +/** + * Get the status of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Get the status of specified sync(s) (for a given connection or all applicable connections if no connection is specified) + */ +export async function syncGetStatus( + client: NangoCore, + providerConfigKey: string, + syncs: string, + connectionId?: string | undefined, + options?: RequestOptions, +): Promise< + Result< + components.GetSyncStatusResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const input: operations.GetSyncStatusRequest = { + providerConfigKey: providerConfigKey, + syncs: syncs, + connectionId: connectionId, + }; + + const parsed = safeParse( + input, + (value) => operations.GetSyncStatusRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = null; + + const path = pathToFunc("/sync/status")(); + + const query = encodeFormQuery({ + "connection_id": payload.connection_id, + "provider_config_key": payload.provider_config_key, + "syncs": payload.syncs, + }); + + const headers = new Headers(compactMap({ + Accept: "application/json", + })); + + const context = { + operationID: "getSyncStatus", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.GetSyncStatusResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.GetSyncStatusResponse$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncPause.ts b/src/funcs/syncPause.ts new file mode 100644 index 0000000..a651a4d --- /dev/null +++ b/src/funcs/syncPause.ts @@ -0,0 +1,132 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Pauses the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Pauses the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ +export async function syncPause( + client: NangoCore, + request?: components.CreateSyncPauseRequest | undefined, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => + components.CreateSyncPauseRequest$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/sync/pause")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "createSyncPause", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncStart.ts b/src/funcs/syncStart.ts new file mode 100644 index 0000000..aed2f67 --- /dev/null +++ b/src/funcs/syncStart.ts @@ -0,0 +1,132 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { NangoCore } from "../core.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Starts the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Starts the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ +export async function syncStart( + client: NangoCore, + request?: components.CreateSyncStartRequest | undefined, + options?: RequestOptions, +): Promise< + Result< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => + components.CreateSyncStartRequest$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return parsed; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/sync/start")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "createSyncStart", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + void, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.nil(200, z.void()), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/funcs/syncUpdateFrequency.ts b/src/funcs/syncUpdateFrequency.ts new file mode 100644 index 0000000..8bda055 --- /dev/null +++ b/src/funcs/syncUpdateFrequency.ts @@ -0,0 +1,129 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { NangoCore } from "../core.js"; +import { encodeJSON } from "../lib/encodings.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } 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 * as errors from "../models/errors/index.js"; +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; + +/** + * Override a sync's default frequency for a specific connection or revert to the default frequency. + * + * @remarks + * Override a sync's default frequency for a specific connection, or revert to the default frequency. + */ +export async function syncUpdateFrequency( + client: NangoCore, + request: components.UpdateConnectionFrequencyRequest, + options?: RequestOptions, +): Promise< + Result< + components.UpdateConnectionFrequencyResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + > +> { + const parsed = safeParse( + request, + (value) => + components.UpdateConnectionFrequencyRequest$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("/sync/update-connection-frequency")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: "application/json", + })); + + const context = { + operationID: "updateConnectionFrequency", + oAuth2Scopes: [], + + resolvedSecurity: null, + + securitySource: null, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + method: "PUT", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return requestRes; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return doResult; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + components.UpdateConnectionFrequencyResponse, + | errors.Response400 + | SDKError + | SDKValidationError + | UnexpectedClientError + | InvalidRequestError + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + >( + M.json(200, components.UpdateConnectionFrequencyResponse$inboundSchema), + M.jsonErr(400, errors.Response400$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, { extraFields: responseFields }); + if (!result.ok) { + return result; + } + + return result; +} diff --git a/src/hooks/hooks.ts b/src/hooks/hooks.ts index 37ee8cd..fc9b13b 100644 --- a/src/hooks/hooks.ts +++ b/src/hooks/hooks.ts @@ -1,99 +1,129 @@ /* - * 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"; import { - AfterErrorContext, - AfterErrorHook, - AfterSuccessContext, - AfterSuccessHook, - BeforeRequestContext, - BeforeRequestHook, - BeforeCreateRequestHook, - BeforeCreateRequestContext, - Hooks, - SDKInitHook, - SDKInitOptions, + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeCreateRequestContext, + BeforeCreateRequestHook, + BeforeRequestContext, + BeforeRequestHook, + Hook, + Hooks, + SDKInitHook, + SDKInitOptions, } from "./types.js"; export class SDKHooks implements Hooks { - sdkInitHooks: SDKInitHook[] = []; - beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; - beforeRequestHooks: BeforeRequestHook[] = []; - afterSuccessHooks: AfterSuccessHook[] = []; - afterErrorHooks: AfterErrorHook[] = []; - - constructor() {} - - registerSDKInitHook(hook: SDKInitHook) { - this.sdkInitHooks.push(hook); + sdkInitHooks: SDKInitHook[] = []; + beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; + beforeRequestHooks: BeforeRequestHook[] = []; + afterSuccessHooks: AfterSuccessHook[] = []; + afterErrorHooks: AfterErrorHook[] = []; + + constructor() { + const presetHooks: Array = []; + + for (const hook of presetHooks) { + if ("sdkInit" in hook) { + this.registerSDKInitHook(hook); + } + if ("beforeCreateRequest" in hook) { + this.registerBeforeCreateRequestHook(hook); + } + if ("beforeRequest" in hook) { + this.registerBeforeRequestHook(hook); + } + if ("afterSuccess" in hook) { + this.registerAfterSuccessHook(hook); + } + if ("afterError" in hook) { + this.registerAfterErrorHook(hook); + } } + } - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { - this.beforeCreateRequestHooks.push(hook); - } + registerSDKInitHook(hook: SDKInitHook) { + this.sdkInitHooks.push(hook); + } - registerBeforeRequestHook(hook: BeforeRequestHook) { - this.beforeRequestHooks.push(hook); - } + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { + this.beforeCreateRequestHooks.push(hook); + } - registerAfterSuccessHook(hook: AfterSuccessHook) { - this.afterSuccessHooks.push(hook); - } + registerBeforeRequestHook(hook: BeforeRequestHook) { + this.beforeRequestHooks.push(hook); + } - registerAfterErrorHook(hook: AfterErrorHook) { - this.afterErrorHooks.push(hook); - } + registerAfterSuccessHook(hook: AfterSuccessHook) { + this.afterSuccessHooks.push(hook); + } - sdkInit(opts: SDKInitOptions): SDKInitOptions { - return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); - } + registerAfterErrorHook(hook: AfterErrorHook) { + this.afterErrorHooks.push(hook); + } - beforeCreateRequest(hookCtx: BeforeCreateRequestContext, input: RequestInput): RequestInput { - let inp = input; + sdkInit(opts: SDKInitOptions): SDKInitOptions { + return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + } - for (const hook of this.beforeCreateRequestHooks) { - inp = hook.beforeCreateRequest(hookCtx, inp); - } + beforeCreateRequest( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ): RequestInput { + let inp = input; - return inp; + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); } - async beforeRequest(hookCtx: BeforeRequestContext, request: Request): Promise { - let req = request; + return inp; + } - for (const hook of this.beforeRequestHooks) { - req = await hook.beforeRequest(hookCtx, req); - } + async beforeRequest( + hookCtx: BeforeRequestContext, + request: Request, + ): Promise { + let req = request; - return req; + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); } - async afterSuccess(hookCtx: AfterSuccessContext, response: Response): Promise { - let res = response; + return req; + } - for (const hook of this.afterSuccessHooks) { - res = await hook.afterSuccess(hookCtx, res); - } + async afterSuccess( + hookCtx: AfterSuccessContext, + response: Response, + ): Promise { + let res = response; - return res; + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); } - async afterError( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ): Promise<{ response: Response | null; error: unknown }> { - let res = response; - let err = error; - - for (const hook of this.afterErrorHooks) { - const result = await hook.afterError(hookCtx, res, err); - res = result.response; - err = result.error; - } - - return { response: res, error: err }; + return res; + } + + async afterError( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ): Promise<{ response: Response | null; error: unknown }> { + let res = response; + let err = error; + + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; } + + return { response: res, error: err }; + } } diff --git a/src/hooks/index.ts b/src/hooks/index.ts index d5fdd74..f60ec7a 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,6 +1,6 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ -export * from "./types.js"; export * from "./hooks.js"; +export * from "./types.js"; diff --git a/src/hooks/types.ts b/src/hooks/types.ts index dd23b02..8a27c65 100644 --- a/src/hooks/types.ts +++ b/src/hooks/types.ts @@ -1,20 +1,24 @@ /* - * 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"; +import { RetryConfig } from "../lib/retries.js"; +import { SecurityState } from "../lib/security.js"; export type HookContext = { - operationID: string; - oAuth2Scopes?: string[]; - securitySource?: any | (() => Promise); + operationID: string; + oAuth2Scopes?: string[]; + securitySource?: any | (() => Promise); + retryConfig: RetryConfig; + resolvedSecurity: SecurityState | null; }; export type Awaitable = T | Promise; export type SDKInitOptions = { - baseURL: URL | null; - client: HTTPClient; + baseURL: URL | null; + client: HTTPClient; }; export type BeforeCreateRequestContext = HookContext & {}; @@ -27,63 +31,79 @@ export type AfterErrorContext = HookContext & {}; * hook can return a new baseURL and HTTP client to be used by the SDK. */ export interface SDKInitHook { - sdkInit: (opts: SDKInitOptions) => SDKInitOptions; + sdkInit: (opts: SDKInitOptions) => SDKInitOptions; } export interface BeforeCreateRequestHook { - /** - * A hook that is called before the SDK creates a `Request` object. The hook - * can modify how a request is constructed since certain modifications, like - * changing the request URL, cannot be done on a request object directly. - */ - beforeCreateRequest: (hookCtx: BeforeCreateRequestContext, input: RequestInput) => RequestInput; + /** + * A hook that is called before the SDK creates a `Request` object. The hook + * can modify how a request is constructed since certain modifications, like + * changing the request URL, cannot be done on a request object directly. + */ + beforeCreateRequest: ( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ) => RequestInput; } export interface BeforeRequestHook { - /** - * A hook that is called before the SDK sends a request. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * replace the request before it is sent or throw an error to stop the - * request from being sent. - */ - beforeRequest: (hookCtx: BeforeRequestContext, request: Request) => Awaitable; + /** + * A hook that is called before the SDK sends a request. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * replace the request before it is sent or throw an error to stop the + * request from being sent. + */ + beforeRequest: ( + hookCtx: BeforeRequestContext, + request: Request, + ) => Awaitable; } export interface AfterSuccessHook { - /** - * A hook that is called after the SDK receives a response. The hook can - * introduce instrumentation code such as logging, tracing and metrics or - * modify the response before it is handled or throw an error to stop the - * response from being handled. - */ - afterSuccess: (hookCtx: AfterSuccessContext, response: Response) => Awaitable; + /** + * A hook that is called after the SDK receives a response. The hook can + * introduce instrumentation code such as logging, tracing and metrics or + * modify the response before it is handled or throw an error to stop the + * response from being handled. + */ + afterSuccess: ( + hookCtx: AfterSuccessContext, + response: Response, + ) => Awaitable; } export interface AfterErrorHook { - /** - * A hook that is called after the SDK encounters an error, or a - * non-successful response. The hook can introduce instrumentation code such - * as logging, tracing and metrics or modify the response or error values. - */ - afterError: ( - hookCtx: AfterErrorContext, - response: Response | null, - error: unknown - ) => Awaitable<{ - response: Response | null; - error: unknown; - }>; + /** + * A hook that is called after the SDK encounters an error, or a + * non-successful response. The hook can introduce instrumentation code such + * as logging, tracing and metrics or modify the response or error values. + */ + afterError: ( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ) => Awaitable<{ + response: Response | null; + error: unknown; + }>; } export interface Hooks { - /** Registers a hook to be used by the SDK for initialization event. */ - registerSDKInitHook(hook: SDKInitHook): void; - /** Registers a hook to be used by the SDK for to modify `Request` construction. */ - registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; - /** Registers a hook to be used by the SDK for the before request event. */ - registerBeforeRequestHook(hook: BeforeRequestHook): void; - /** Registers a hook to be used by the SDK for the after success event. */ - registerAfterSuccessHook(hook: AfterSuccessHook): void; - /** Registers a hook to be used by the SDK for the after error event. */ - registerAfterErrorHook(hook: AfterErrorHook): void; + /** Registers a hook to be used by the SDK for initialization event. */ + registerSDKInitHook(hook: SDKInitHook): void; + /** Registers a hook to be used by the SDK for to modify `Request` construction. */ + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook): void; + /** Registers a hook to be used by the SDK for the before request event. */ + registerBeforeRequestHook(hook: BeforeRequestHook): void; + /** Registers a hook to be used by the SDK for the after success event. */ + registerAfterSuccessHook(hook: AfterSuccessHook): void; + /** Registers a hook to be used by the SDK for the after error event. */ + registerAfterErrorHook(hook: AfterErrorHook): void; } + +export type Hook = + | SDKInitHook + | BeforeCreateRequestHook + | BeforeRequestHook + | AfterSuccessHook + | AfterErrorHook; diff --git a/src/index.ts b/src/index.ts index 8bc6ae3..5ddc765 100644 --- a/src/index.ts +++ b/src/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 "./sdk/sdk.js"; export * from "./lib/config.js"; +export * as files from "./lib/files.js"; +export * from "./sdk/sdk.js"; diff --git a/src/lib/base64.ts b/src/lib/base64.ts index cda0764..c2d5b38 100644 --- a/src/lib/base64.ts +++ b/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/src/lib/config.ts b/src/lib/config.ts index bd4816e..8a5852c 100644 --- a/src/lib/config.ts +++ b/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"; @@ -18,44 +19,47 @@ export const ServerLocal = "local"; * Contains the list of servers available to the SDK */ export const ServerList = { - [ServerProd]: "https://api.nango.dev", - [ServerLocal]: "http://localhost:3003", + [ServerProd]: "https://api.nango.dev", + [ServerLocal]: "http://localhost:3003", } as const; export type SDKOptions = { - httpClient?: HTTPClient; - /** - * Allows overriding the default server used by the SDK - */ - server?: keyof typeof ServerList; - /** - * Allows overriding the default server URL used by the SDK - */ - serverURL?: string; - /** - * Allows overriding the default retry config used by the SDK - */ - retryConfig?: RetryConfig; + httpClient?: HTTPClient; + /** + * Allows overriding the default server used by the SDK + */ + server?: keyof typeof ServerList; + /** + * Allows overriding the default server URL used by the SDK + */ + serverURL?: string; + /** + * Allows overriding the default retry config used by the SDK + */ + retryConfig?: RetryConfig; + timeoutMs?: number; + debugLogger?: Logger; }; export function serverURLFromOptions(options: SDKOptions): URL | null { - let serverURL = options.serverURL; + let serverURL = options.serverURL; - const params: Params = {}; + const params: Params = {}; - if (!serverURL) { - const server = options.server ?? ServerProd; - serverURL = ServerList[server] || ""; - } + if (!serverURL) { + const server = options.server ?? ServerProd; + serverURL = ServerList[server] || ""; + } - const u = pathToFunc(serverURL)(params); - return new URL(u); + const u = pathToFunc(serverURL)(params); + return new URL(u); } export const SDK_METADATA = { - language: "typescript", - openapiDocVersion: "1.0.0", - sdkVersion: "0.9.1", - genVersion: "2.347.4", - userAgent: "speakeasy-sdk/typescript 0.9.1 2.347.4 1.0.0 @speakeasy-sdks/nango", + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "0.10.0", + genVersion: "2.495.1", + userAgent: + "speakeasy-sdk/typescript 0.10.0 2.495.1 1.0.0 @speakeasy-sdks/nango", } as const; diff --git a/src/lib/dlv.ts b/src/lib/dlv.ts new file mode 100644 index 0000000..e81091f --- /dev/null +++ b/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/src/lib/encodings.ts b/src/lib/encodings.ts index 49f536b..25c9dcb 100644 --- a/src/lib/encodings.ts +++ b/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"; @@ -16,12 +16,16 @@ export function encodeMatrix( key: string, value: unknown, options?: { explode?: boolean; charEncoding?: "percent" | "none" }, -): string { +): string | undefined { let out = ""; const pairs: [string, unknown][] = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v: string) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; @@ -29,21 +33,25 @@ export function encodeMatrix( pairs.forEach(([pk, pv]) => { let tmp = ""; - let encValue = ""; + let encValue: string | null | undefined = null; - if (pv === undefined) { + if (pv == null) { return; } else if (Array.isArray(pv)) { - encValue = mapDefined(pv, (v) => `${encodeValue(v)}`).join(","); + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); } else if (isPlainObject(pv)) { - encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `,${encodeString(k)},${encodeValue(v)}`; - }).join(""); - encValue = encValue.slice(1); + }); + encValue = mapped?.join("").slice(1); } else { encValue = `${encodeValue(pv)}`; } + if (encValue == null) { + return; + } + const keyPrefix = encodeString(pk); tmp = `${keyPrefix}=${encValue}`; // trim trailing '=' if value was empty @@ -66,36 +74,40 @@ export function encodeLabel( key: string, value: unknown, options?: { explode?: boolean; charEncoding?: "percent" | "none" }, -): string { +): string | undefined { let out = ""; const pairs: [string, unknown][] = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v: string) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let encValue = ""; + let encValue: string | null | undefined = ""; - if (pv === undefined) { + if (pv == null) { return; } else if (Array.isArray(pv)) { - encValue = mapDefined(pv, (v) => `${encodeValue(v)}`).join("."); + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join("."); } else if (isPlainObject(pv)) { - encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `.${encodeString(k)}.${encodeValue(v)}`; - }).join(""); - encValue = encValue.slice(1); + }); + encValue = mapped?.join("").slice(1); } else { const k = options?.explode && isPlainObject(value) ? `${encodeString(pk)}=` : ""; encValue = `${k}${encodeValue(pv)}`; } - out += `.${encValue}`; + out += encValue == null ? "" : `.${encValue}`; }); return out; @@ -105,7 +117,7 @@ type FormEncoder = ( key: string, value: unknown, options?: { explode?: boolean; charEncoding?: "percent" | "none" }, -) => string; +) => string | undefined; function formEncoder(sep: string): FormEncoder { return ( @@ -118,6 +130,10 @@ function formEncoder(sep: string): FormEncoder { ? explode(key, value) : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v: string) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; @@ -128,20 +144,24 @@ function formEncoder(sep: string): FormEncoder { pairs.forEach(([pk, pv]) => { let tmp = ""; - let encValue = ""; + let encValue: string | null | undefined = null; - if (pv === undefined) { + if (pv == null) { return; } else if (Array.isArray(pv)) { - encValue = mapDefined(pv, (v) => `${encodeValue(v)}`).join(encodedSep); + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(encodedSep); } else if (isPlainObject(pv)) { encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `${encodeString(k)}${encodedSep}${encodeValue(v)}`; - }).join(encodedSep); + })?.join(encodedSep); } else { encValue = `${encodeValue(pv)}`; } + if (encValue == null) { + return; + } + tmp = `${encodeString(pk)}=${encValue}`; // If we end up with the nothing then skip forward @@ -180,7 +200,7 @@ export function encodeBodyForm( let tmp = ""; let encValue = ""; - if (pv === undefined) { + if (pv == null) { return; } else if (Array.isArray(pv)) { encValue = JSON.stringify(pv, jsonReplacer); @@ -207,9 +227,27 @@ export function encodeDeepObject( key: string, value: unknown, options?: { charEncoding?: "percent" | "none" }, -): string { +): string | undefined { if (value == null) { - return ""; + return; + } + + if (!isPlainObject(value)) { + throw new EncodingError( + `Value of parameter '${key}' which uses deepObject encoding must be an object or null`, + ); + } + + return encodeDeepObjectObject(key, value, options); +} + +export function encodeDeepObjectObject( + key: string, + value: unknown, + options?: { charEncoding?: "percent" | "none" }, +): string | undefined { + if (value == null) { + return; } let out = ""; @@ -219,32 +257,30 @@ 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]) => { - if (cv === undefined) { + if (cv == null) { return; } 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 == null ? "" : `&${objOut}`; + + return; } const pairs: unknown[] = Array.isArray(cv) ? cv : [cv]; - let encoded = ""; - - encoded = mapDefined(pairs, (v) => { + const encoded = mapDefined(pairs, (v) => { return `${encodeString(pk)}=${encodeString(serializeValue(v))}`; - }).join("&"); + })?.join("&"); - out += `&${encoded}`; + out += encoded == null ? "" : `&${encoded}`; }); return out.slice(1); @@ -254,9 +290,9 @@ export function encodeJSON( key: string, value: unknown, options?: { explode?: boolean; charEncoding?: "percent" | "none" }, -): string { +): string | undefined { if (typeof value === "undefined") { - return ""; + return; } const encodeString = (v: string) => { @@ -272,40 +308,39 @@ export const encodeSimple = ( key: string, value: unknown, options?: { explode?: boolean; charEncoding?: "percent" | "none" }, -): string => { +): string | undefined => { let out = ""; const pairs: [string, unknown][] = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_, v]) => v == null)) { + return; + } + const encodeString = (v: string) => { return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; }; const encodeValue = (v: unknown) => encodeString(serializeValue(v)); pairs.forEach(([pk, pv]) => { - let tmp = ""; + let tmp: string | null | undefined = ""; - if (pv === undefined) { + if (pv == null) { return; } else if (Array.isArray(pv)) { - tmp = mapDefined(pv, (v) => `${encodeValue(v)}`).join(","); + tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); } else if (isPlainObject(pv)) { - tmp = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { return `,${encodeString(k)},${encodeValue(v)}`; - }).join(""); - tmp = tmp.slice(1); + }); + tmp = mapped?.join("").slice(1); } else { const k = options?.explode && isPlainObject(value) ? `${pk}=` : ""; tmp = `${k}${encodeValue(pv)}`; } - // If we end up with the nothing then skip forward - if (!tmp) { - return; - } - - out += `,${tmp}`; + out += tmp ? `,${tmp}` : ""; }); return out.slice(1); @@ -323,9 +358,7 @@ function explode(key: string, value: unknown): [string, unknown][] { } function serializeValue(value: unknown): string { - if (value === null) { - return "null"; - } else if (typeof value === "undefined") { + if (value == null) { return ""; } else if (value instanceof Date) { return value.toISOString(); @@ -346,14 +379,14 @@ function jsonReplacer(_: string, value: unknown): unknown { } } -function mapDefined(inp: T[], mapper: (v: T) => R): R[] { - return inp.reduce((acc, v) => { - if (v === undefined) { +function mapDefined(inp: T[], mapper: (v: T) => R): R[] | null { + const res = inp.reduce((acc, v) => { + if (v == null) { return acc; } const m = mapper(v); - if (m === undefined) { + if (m == null) { return acc; } @@ -361,30 +394,32 @@ function mapDefined(inp: T[], mapper: (v: T) => R): R[] { return acc; }, []); + + return res.length ? res : null; } function mapDefinedEntries( inp: Iterable<[K, V]>, mapper: (v: [K, V]) => R, -): R[] { +): R[] | null { const acc: R[] = []; for (const [k, v] of inp) { - if (v === undefined) { + if (v == null) { continue; } const m = mapper([k, v]); - if (m === undefined) { + if (m == null) { continue; } acc.push(m); } - return acc; + return acc.length ? acc : null; } -export function queryJoin(...args: string[]): string { +export function queryJoin(...args: (string | undefined)[]): string { return args.filter(Boolean).join("&"); } @@ -397,7 +432,7 @@ type QueryEncoder = ( key: string, value: unknown, options?: QueryEncoderOptions, -) => string; +) => string | undefined; type BulkQueryEncoder = ( values: Record, @@ -429,3 +464,20 @@ export const encodeFormQuery = queryEncoder(encodeForm); export const encodeSpaceDelimitedQuery = queryEncoder(encodeSpaceDelimited); export const encodePipeDelimitedQuery = queryEncoder(encodePipeDelimited); export const encodeDeepObjectQuery = queryEncoder(encodeDeepObject); + +export function appendForm( + fd: FormData, + key: string, + value: unknown, + fileName?: string, +): void { + if (value == null) { + return; + } else if (value instanceof Blob && fileName) { + fd.append(key, value, fileName); + } else if (value instanceof Blob) { + fd.append(key, value); + } else { + fd.append(key, String(value)); + } +} diff --git a/src/lib/files.ts b/src/lib/files.ts new file mode 100644 index 0000000..19e0804 --- /dev/null +++ b/src/lib/files.ts @@ -0,0 +1,40 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/** + * Consumes a stream and returns a concatenated array buffer. Useful in + * situations where we need to read the whole file because it forms part of a + * larger payload containing other fields, and we can't modify the underlying + * request structure. + */ +export async function readableStreamToArrayBuffer( + readable: ReadableStream, +): Promise { + const reader = readable.getReader(); + const chunks: Uint8Array[] = []; + + let totalLength = 0; + let done = false; + + while (!done) { + const { value, done: doneReading } = await reader.read(); + + if (doneReading) { + done = true; + } else { + chunks.push(value); + totalLength += value.length; + } + } + + const concatenatedChunks = new Uint8Array(totalLength); + let offset = 0; + + for (const chunk of chunks) { + concatenatedChunks.set(chunk, offset); + offset += chunk.length; + } + + return concatenatedChunks.buffer; +} diff --git a/src/lib/http.ts b/src/lib/http.ts index 7c5107a..13cf1fd 100644 --- a/src/lib/http.ts +++ b/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/src/lib/is-plain-object.ts b/src/lib/is-plain-object.ts index af0d6e7..61070d3 100644 --- a/src/lib/is-plain-object.ts +++ b/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/src/lib/logger.ts b/src/lib/logger.ts new file mode 100644 index 0000000..d181f29 --- /dev/null +++ b/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/src/lib/matchers.ts b/src/lib/matchers.ts new file mode 100644 index 0000000..19b46b3 --- /dev/null +++ b/src/lib/matchers.ts @@ -0,0 +1,322 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { SDKError } from "../models/errors/sdkerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { Result } from "../types/fp.js"; +import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js"; +import { isPlainObject } from "./is-plain-object.js"; +import { safeParse } from "./schemas.js"; + +export type Encoding = + | "json" + | "text" + | "bytes" + | "stream" + | "sse" + | "nil" + | "fail"; + +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 = new Uint8Array(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/src/lib/primitives.ts b/src/lib/primitives.ts index d3aae30..ce50b98 100644 --- a/src/lib/primitives.ts +++ b/src/lib/primitives.ts @@ -1,7 +1,27 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +class InvariantError extends Error { + constructor(message: string) { + super(message); + this.name = "InvariantError"; + } +} + +export function invariant( + condition: unknown, + message: string, +): asserts condition { + if (!condition) { + throw new InvariantError(message); + } +} + +export type ExactPartial = { + [P in keyof T]?: T[P] | undefined; +}; + export type Remap = { [k in keyof Inp as Mapping[k] extends string /* if we have a string mapping for this key then use it */ ? Mapping[k] @@ -38,3 +58,79 @@ export function remap< return out; } + +export function combineSignals( + ...signals: Array +): AbortSignal | null { + const filtered: AbortSignal[] = []; + for (const signal of signals) { + if (signal) { + filtered.push(signal); + } + } + + switch (filtered.length) { + case 0: + case 1: + return filtered[0] || null; + default: + if ("any" in AbortSignal && typeof AbortSignal.any === "function") { + return AbortSignal.any(filtered); + } + return abortSignalAny(filtered); + } +} + +export function abortSignalAny(signals: AbortSignal[]): AbortSignal { + const controller = new AbortController(); + const result = controller.signal; + if (!signals.length) { + return controller.signal; + } + + if (signals.length === 1) { + return signals[0] || controller.signal; + } + + for (const signal of signals) { + if (signal.aborted) { + return signal; + } + } + + function abort(this: AbortSignal) { + controller.abort(this.reason); + clean(); + } + + const signalRefs: WeakRef[] = []; + function clean() { + for (const signalRef of signalRefs) { + const signal = signalRef.deref(); + if (signal) { + signal.removeEventListener("abort", abort); + } + } + } + + for (const signal of signals) { + signalRefs.push(new WeakRef(signal)); + signal.addEventListener("abort", abort); + } + + return result; +} + +export function compactMap( + values: Record, +): Record { + const out: Record = {}; + + for (const [k, v] of Object.entries(values)) { + if (typeof v !== "undefined") { + out[k] = v; + } + } + + return out; +} diff --git a/src/lib/retries.ts b/src/lib/retries.ts index ed9b495..93ebc8d 100644 --- a/src/lib/retries.ts +++ b/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; @@ -24,23 +26,44 @@ export type RetryConfig = retryConnectionErrors?: boolean; }; -class PermanentError extends Error { - inner: unknown; +/** + * PermanentError is an error that is not recoverable. Throwing this error will + * cause a retry loop to terminate. + */ +export class PermanentError extends Error { + /** The underlying cause of the error. */ + override readonly cause: unknown; + + constructor(message: string, options?: { cause?: unknown }) { + let msg = message; + if (options?.cause) { + msg += `: ${options.cause}`; + } - constructor(inner: unknown) { - super("Permanent error"); - this.inner = inner; + super(msg, options); + this.name = "PermanentError"; + // In older runtimes, the cause field would not have been assigned through + // the super() call. + if (typeof this.cause === "undefined") { + this.cause = options?.cause; + } Object.setPrototypeOf(this, PermanentError.prototype); } } -class TemporaryError extends Error { - res: Response; +/** + * TemporaryError is an error is used to signal that an HTTP request can be + * retried as part of a retry loop. If retry attempts are exhausted and this + * error is thrown, the response will be returned to the caller. + */ +export class TemporaryError extends Error { + response: Response; - constructor(res: Response) { - super("Temporary error"); - this.res = res; + constructor(message: string, response: Response) { + super(message); + this.response = response; + this.name = "TemporaryError"; Object.setPrototypeOf(this, TemporaryError.prototype); } @@ -78,11 +101,14 @@ function wrapFetcher( try { const res = await fn(); if (isRetryableResponse(res, options.statusCodes)) { - throw new TemporaryError(res); + throw new TemporaryError( + "Response failed with retryable status code", + res, + ); } return res; - } catch (err) { + } catch (err: unknown) { if (err instanceof TemporaryError) { throw err; } @@ -94,52 +120,11 @@ function wrapFetcher( throw err; } - throw new PermanentError(err); + throw new PermanentError("Permanent error", { cause: err }); } }; } -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 { @@ -178,37 +163,25 @@ async function retryBackoff( try { const res = await fn(); return res; - } catch (err) { + } catch (err: unknown) { if (err instanceof PermanentError) { - throw err.inner; + throw err.cause; } const elapsed = Date.now() - start; if (elapsed > maxElapsedTime) { if (err instanceof TemporaryError) { - return err.res; + return err.response; } throw err; } let retryInterval = 0; - if (err instanceof TemporaryError && err.res && err.res.headers) { - const retryVal = err.res.headers.get("retry-after") || ""; - if (retryVal != "") { - const parsedNumber = Number(retryVal); - if (!isNaN(parsedNumber) && Number.isInteger(parsedNumber)) { - retryInterval = parsedNumber * 1000; - } else { - const parsedDate = Date.parse(retryVal); - if (!isNaN(parsedDate)) { - const deltaMS = parsedDate - Date.now(); - retryInterval = deltaMS > 0 ? Math.ceil(deltaMS) : 0; - } - } - } + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); } - if (retryInterval == 0) { + if (retryInterval <= 0) { retryInterval = initialInterval * Math.pow(x, exponent) + Math.random() * 1000; } @@ -221,6 +194,26 @@ async function retryBackoff( } } +function retryIntervalFromResponse(res: Response): number { + const retryVal = res.headers.get("retry-after") || ""; + if (!retryVal) { + return 0; + } + + const parsedNumber = Number(retryVal); + if (Number.isInteger(parsedNumber)) { + return parsedNumber * 1000; + } + + const parsedDate = Date.parse(retryVal); + if (Number.isInteger(parsedDate)) { + const deltaMS = parsedDate - Date.now(); + return deltaMS > 0 ? Math.ceil(deltaMS) : 0; + } + + return 0; +} + async function delay(delay: number): Promise { return new Promise((resolve) => setTimeout(resolve, delay)); } diff --git a/src/lib/schemas.ts b/src/lib/schemas.ts index 94b0535..0e340b7 100644 --- a/src/lib/schemas.ts +++ b/src/lib/schemas.ts @@ -1,56 +1,91 @@ /* - * 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 { + 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 * intercepts this error and converts it to an SDKValidationError so as to not * leak Zod implementation details to user code. */ -export function parse(rawValue: Inp, fn: (value: Inp) => Out, errorMessage: string): Out { - try { - return fn(rawValue); - } catch (err) { - if (err instanceof ZodError) { - throw new SDKValidationError(errorMessage, err, rawValue); - } - throw err; +export function parse( + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, +): Out { + try { + return fn(rawValue); + } catch (err) { + if (err instanceof ZodError) { + throw new SDKValidationError(errorMessage, err, rawValue); } + throw err; + } +} + +/** + * 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, - K extends string + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + K extends string, >( - obj: ZodObject, - extrasKey: K + obj: ZodObject, + extrasKey: K, + optional: boolean, ): ZodEffects< - typeof obj, - output> & { - [k in K]: Record>; - } + typeof obj, + & output> + & { + [k in K]: Record>; + } > { - return obj.transform((val) => { - const extras: Record> = {}; - const { shape } = obj; - for (const [key] of Object.entries(val)) { - if (key in shape) { - continue; - } - - const v = val[key]; - if (typeof v === "undefined") { - continue; - } - - extras[key] = v; - delete val[key]; - } - - return { ...val, [extrasKey]: extras }; - }); + return obj.transform((val) => { + const extras: Record> = {}; + const { shape } = obj; + for (const [key] of Object.entries(val)) { + if (key in shape) { + continue; + } + + const v = val[key]; + if (typeof v === "undefined") { + continue; + } + + extras[key] = v; + delete val[key]; + } + + if (optional && Object.keys(extras).length === 0) { + return val; + } + + return { ...val, [extrasKey]: extras }; + }); } diff --git a/src/lib/sdks.ts b/src/lib/sdks.ts index cbda9d8..e57eedb 100644 --- a/src/lib/sdks.ts +++ b/src/lib/sdks.ts @@ -1,147 +1,396 @@ /* - * 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 { encodeForm } from "./encodings.js"; -import { stringToBase64 } from "./base64.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"; +import { stringToBase64 } from "./base64.js"; +import { SDK_METADATA, SDKOptions, serverURLFromOptions } from "./config.js"; +import { encodeForm } from "./encodings.js"; +import { + HTTPClient, + isAbortError, + isConnectionError, + isTimeoutError, + matchContentType, + matchStatusCode, +} from "./http.js"; +import { Logger } from "./logger.js"; +import { retry, RetryConfig } from "./retries.js"; +import { SecurityState } from "./security.js"; export type RequestOptions = { - fetchOptions?: Omit; + /** + * Sets a timeout, in milliseconds, on HTTP requests made by an SDK method. If + * `fetchOptions.signal` is set then it will take precedence over this option. + */ + timeoutMs?: number; + /** + * Set or override a retry policy on HTTP calls. + */ + retries?: RetryConfig; + /** + * Specifies the status codes which should be retried using the given retry policy. + */ + retryCodes?: string[]; + /** + * Overrides the base server URL that will be used by an operation. + */ + serverURL?: string | URL; + /** + * Sets various request options on the `fetch` call made by an SDK method. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options|Request} + */ + fetchOptions?: Omit; }; type RequestConfig = { - method: string; - path: string; - baseURL?: string | URL; - query?: string; - body?: RequestInit["body"]; - headers?: HeadersInit; - security?: SecurityState | null; + method: string; + path: string; + baseURL?: string | URL | undefined; + query?: string; + body?: RequestInit["body"]; + headers?: HeadersInit; + security?: SecurityState | null; + uaHeader?: string; + timeoutMs?: number; }; +const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; +const webWorkerLike = typeof gt === "object" + && gt != null + && "importScripts" in gt + && typeof gt["importScripts"] === "function"; +const isBrowserLike = webWorkerLike + || (typeof navigator !== "undefined" && "serviceWorker" in navigator) + || (typeof window === "object" && typeof window.document !== "undefined"); + export class ClientSDK { - private readonly client: HTTPClient; - protected readonly baseURL: URL | null; - protected readonly hooks$: SDKHooks; - - constructor(init: { client: HTTPClient; baseURL: URL | null; hooks: SDKHooks }) { - const url = init.baseURL; - if (url) { - url.pathname = url.pathname.replace(/\/+$/, "") + "/"; - } + readonly #httpClient: HTTPClient; + readonly #hooks: SDKHooks; + readonly #logger?: Logger | undefined; + protected readonly _baseURL: URL | null; + public readonly _options: SDKOptions & { hooks?: SDKHooks }; - this.hooks$ = init.hooks; - const { baseURL, client } = this.hooks$.sdkInit({ baseURL: url, client: init.client }); - this.baseURL = baseURL; - this.client = client; + 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 }; - protected createRequest$( - context: HookContext, - conf: RequestConfig, - options?: RequestOptions - ): Request { - const { method, path, query, headers: opHeaders, security } = conf; + const url = serverURLFromOptions(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + const { baseURL, client } = this.#hooks.sdkInit({ + baseURL: url, + client: options.httpClient || new HTTPClient(), + }); + this._baseURL = baseURL; + this.#httpClient = client; + this.#logger = options.debugLogger; + } - const base = conf.baseURL ?? this.baseURL; - if (!base) { - throw new TypeError("No base URL provided for operation"); - } - const reqURL = new URL(base); - const inputURL = new URL(path, reqURL); + public _createRequest( + context: HookContext, + conf: RequestConfig, + options?: RequestOptions, + ): Result { + const { method, path, query, headers: opHeaders, security } = conf; - if (path) { - reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); - } + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return ERR(new InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path, reqURL); - let finalQuery = query || ""; + if (path) { + reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/"; + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } - const secQuery: string[] = []; - for (const [k, v] of Object.entries(security?.queryParams || {})) { - secQuery.push(encodeForm(k, v, { charEncoding: "percent" })); - } - if (secQuery.length) { - finalQuery += `&${secQuery.join("&")}`; - } + let finalQuery = query || ""; - if (finalQuery) { - const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; - reqURL.search = `?${q}`; - } + const secQuery: string[] = []; + for (const [k, v] of Object.entries(security?.queryParams || {})) { + const q = encodeForm(k, v, { charEncoding: "percent" }); + if (typeof q !== "undefined") { + secQuery.push(q); + } + } + if (secQuery.length) { + finalQuery += `&${secQuery.join("&")}`; + } - const headers = new Headers(opHeaders); + if (finalQuery) { + const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q}`; + } - const username = security?.basic.username; - const password = security?.basic.password; - if (username != null || password != null) { - const encoded = stringToBase64([username || "", password || ""].join(":")); - headers.set("Authorization", `Basic ${encoded}`); - } + const headers = new Headers(opHeaders); - const securityHeaders = new Headers(security?.headers || {}); - for (const [k, v] of securityHeaders) { - headers.set(k, v); - } + const username = security?.basic.username; + const password = security?.basic.password; + if (username != null || password != null) { + const encoded = stringToBase64( + [username || "", password || ""].join(":"), + ); + headers.set("Authorization", `Basic ${encoded}`); + } - let cookie = headers.get("cookie") || ""; - for (const [k, v] of Object.entries(security?.cookies || {})) { - cookie += `; ${k}=${v}`; - } - cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; - headers.set("cookie", cookie); + const securityHeaders = new Headers(security?.headers || {}); + for (const [k, v] of securityHeaders) { + headers.set(k, v); + } - const userHeaders = new Headers(options?.fetchOptions?.headers); - for (const [k, v] of userHeaders) { - headers.set(k, v); - } + let cookie = headers.get("cookie") || ""; + for (const [k, v] of Object.entries(security?.cookies || {})) { + cookie += `; ${k}=${v}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); - const input = this.hooks$.beforeCreateRequest(context, { - url: reqURL, - options: { - ...options?.fetchOptions, - body: conf.body ?? null, - headers, - method, - }, - }); + const userHeaders = new Headers(options?.fetchOptions?.headers); + for (const [k, v] of userHeaders) { + headers.set(k, v); + } + + // Only set user agent header in non-browser-like environments since CORS + // policy disallows setting it in browsers e.g. Chrome throws an error. + if (!isBrowserLike) { + headers.set(conf.uaHeader ?? "user-agent", SDK_METADATA.userAgent); + } - 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; + } } - protected async do$( - req: Request, + if (conf.body instanceof ReadableStream) { + if (!fetchOptions) { + fetchOptions = { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + duplex: "half", + }; + } else { + // @ts-expect-error see https://github.com/node-fetch/node-fetch/issues/1769 + fetchOptions.duplex = "half"; + } + } + + let input; + try { + input = this.#hooks.beforeCreateRequest(context, { + url: reqURL, options: { - context: HookContext; - errorCodes: number | string | (number | string)[]; - } - ): Promise { - const { context, errorCodes } = 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)); + } + + public async _do( + request: Request, + options: { + context: HookContext; + errorCodes: number | string | (number | string)[]; + retryConfig: RetryConfig; + retryCodes: string[]; + }, + ): Promise< + Result< + Response, + | RequestAbortedError + | RequestTimeoutError + | ConnectionError + | UnexpectedClientError + > + > { + const { context, errorCodes } = options; - let response = await this.client.request(await this.hooks$.beforeRequest(context, req)); + 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) + ); - if (matchStatusCode(response, errorCodes)) { - const result = await this.hooks$.afterError(context, response, null); + let response = await this.#httpClient.request(req); + + try { + if (matchStatusCode(response, errorCodes)) { + const result = await this.#hooks.afterError( + context, + response, + null, + ); if (result.error) { - throw result.error; + throw result.error; } response = result.response || response; - } else { - response = await this.hooks$.afterSuccess(context, response); + } else { + response = await this.#hooks.afterSuccess(context, response); + } + } finally { + await logResponse(this.#logger, response, req) + .catch(e => this.#logger?.log("Failed to log response:", e)); } return response; - } + }, + { config: options.retryConfig, statusCodes: options.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, + }), + ); + } + }, + ); + } +} + +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] || ""; - protected matcher(): ResponseMatcher { - return new ResponseMatcher(); + 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(); + + logger.groupEnd(); +} + +async function logResponse( + logger: Logger | undefined, + res: Response, + req: Request, +) { + if (!logger) { + return; + } + + const contentType = res.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; - protected templateURLComponent = pathToFunc; + logger.group(`< Response: ${req.method} ${req.url}`); + logger.log("Status Code:", res.status, res.statusText); + + logger.group("Headers:"); + for (const [k, v] of res.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case matchContentType(res, "application/json") + || jsonLikeContentTypeRE.test(ct): + logger.log(await res.clone().json()); + break; + case matchContentType(res, "text/event-stream"): + logger.log(`<${contentType}>`); + break; + case matchContentType(res, "text/*"): + logger.log(await res.clone().text()); + break; + case matchContentType(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; + } + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); - protected resolveSecurity = resolveSecurity; + logger.groupEnd(); } diff --git a/src/lib/security.ts b/src/lib/security.ts index 560cb62..8c3627f 100644 --- a/src/lib/security.ts +++ b/src/lib/security.ts @@ -1,170 +1,227 @@ /* - * Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT. + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +type OAuth2PasswordFlow = { + username: string; + password?: string | undefined; + clientID: string; + clientSecret?: string | undefined; + tokenURL: string; +}; + export enum SecurityErrorCode { - Incomplete = "incomplete", - UnrecognisedSecurityType = "unrecognized_security_type", + Incomplete = "incomplete", + UnrecognisedSecurityType = "unrecognized_security_type", } export class SecurityError extends Error { - constructor(public code: SecurityErrorCode, message: string) { - super(message); - this.name = "SecurityError"; - } - - static incomplete(): SecurityError { - return new SecurityError( - SecurityErrorCode.Incomplete, - "Security requirements not met in order to perform the operation" - ); - } - static unrecognizedType(type: string): SecurityError { - return new SecurityError( - SecurityErrorCode.UnrecognisedSecurityType, - `Unrecognised security type: ${type}` - ); - } + constructor( + public code: SecurityErrorCode, + message: string, + ) { + super(message); + this.name = "SecurityError"; + } + + static incomplete(): SecurityError { + return new SecurityError( + SecurityErrorCode.Incomplete, + "Security requirements not met in order to perform the operation", + ); + } + static unrecognizedType(type: string): SecurityError { + return new SecurityError( + SecurityErrorCode.UnrecognisedSecurityType, + `Unrecognised security type: ${type}`, + ); + } } export type SecurityState = { - basic: { username?: string | undefined; password?: string | undefined }; - headers: Record; - queryParams: Record; - cookies: Record; + basic: { username?: string | undefined; password?: string | undefined }; + headers: Record; + queryParams: Record; + cookies: Record; + oauth2: ({ type: "password" } & OAuth2PasswordFlow) | { type: "none" }; }; type SecurityInputBasic = { - type: "http:basic"; - value: { username?: string | undefined; password?: string | undefined } | null | undefined; + type: "http:basic"; + value: + | { username?: string | undefined; password?: string | undefined } + | null + | undefined; }; type SecurityInputBearer = { - type: "http:bearer"; - value: string | null | undefined; - fieldName: string; + type: "http:bearer"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputAPIKey = { - type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; - value: string | null | undefined; - fieldName: string; + type: "apiKey:header" | "apiKey:query" | "apiKey:cookie"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOIDC = { - type: "openIdConnect"; - value: string | null | undefined; - fieldName: string; + type: "openIdConnect"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2 = { - type: "oauth2"; - value: string | null | undefined; - fieldName: string; + type: "oauth2"; + value: string | null | undefined; + fieldName: string; }; type SecurityInputOAuth2ClientCredentials = { - type: "oauth2:client_credentials"; - value: { clientID?: string | undefined; clientSecret?: string | undefined } | null | undefined; + type: "oauth2:client_credentials"; + value: + | { clientID?: string | undefined; clientSecret?: string | undefined } + | null + | undefined; +}; + +type SecurityInputOAuth2PasswordCredentials = { + type: "oauth2:password"; + value: + | string + | null + | undefined; + fieldName: string; +}; + +type SecurityInputCustom = { + type: "http:custom"; + value: any | null | undefined; + fieldName: string; }; export type SecurityInput = - | SecurityInputBasic - | SecurityInputBearer - | SecurityInputAPIKey - | SecurityInputOAuth2 - | SecurityInputOAuth2ClientCredentials - | SecurityInputOIDC; - -export function resolveSecurity(...options: SecurityInput[][]): SecurityState | null { - const state: SecurityState = { - basic: { username: "", password: "" }, - headers: {}, - queryParams: {}, - cookies: {}, - }; - - const option = options.find((opts) => { - return opts.every((o) => { - if (o.value == null) { - return false; - } else if (o.type === "http:basic") { - return o.value.username != null || o.value.password != null; - } else if (o.type === "oauth2:client_credentials") { - return o.value.clientID != null || o.value.clientSecret != null; - } else if (typeof o.value === "string") { - return !!o.value; - } else { - throw new Error( - `Unrecognized security type: ${o.type} (value type: ${typeof o.value})` - ); - } - }); - }); - if (option == null) { + | SecurityInputBasic + | SecurityInputBearer + | SecurityInputAPIKey + | SecurityInputOAuth2 + | SecurityInputOAuth2ClientCredentials + | SecurityInputOAuth2PasswordCredentials + | SecurityInputOIDC + | SecurityInputCustom; + +export function resolveSecurity( + ...options: SecurityInput[][] +): SecurityState | null { + const state: SecurityState = { + basic: {}, + headers: {}, + queryParams: {}, + cookies: {}, + oauth2: { type: "none" }, + }; + + const option = options.find((opts) => { + return opts.every((o) => { + if (o.value == null) { + return false; + } else if (o.type === "http:basic") { + return o.value.username != null || o.value.password != null; + } else if (o.type === "http:custom") { return null; + } else if (o.type === "oauth2:password") { + return ( + typeof o.value === "string" && !!o.value + ); + } else if (o.type === "oauth2:client_credentials") { + return o.value.clientID != null || o.value.clientSecret != null; + } else if (typeof o.value === "string") { + return !!o.value; + } else { + throw new Error( + `Unrecognized security type: ${o.type} (value type: ${typeof o + .value})`, + ); + } + }); + }); + if (option == null) { + return null; + } + + option.forEach((spec) => { + if (spec.value == null) { + return; } - option.forEach((spec) => { - if (spec.value == null) { - return; - } - - const { type } = spec; - - switch (type) { - case "apiKey:header": - state.headers[spec.fieldName] = spec.value; - break; - case "apiKey:query": - state.queryParams[spec.fieldName] = spec.value; - break; - case "apiKey:cookie": - state.cookies[spec.fieldName] = spec.value; - break; - case "http:basic": - applyBasic(state, spec); - break; - case "http:bearer": - applyBearer(state, spec); - break; - case "oauth2": - applyBearer(state, spec); - break; - case "oauth2:client_credentials": - break; - case "openIdConnect": - applyBearer(state, spec); - break; - default: - spec satisfies never; - throw SecurityError.unrecognizedType(type); - } - }); + const { type } = spec; + + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:password": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + spec satisfies never; + throw SecurityError.unrecognizedType(type); + } + }); - return state; + return state; } -function applyBasic(state: SecurityState, spec: SecurityInputBasic) { - if (spec.value == null) { - return; - } +function applyBasic( + state: SecurityState, + spec: SecurityInputBasic, +) { + if (spec.value == null) { + return; + } - state.basic = spec.value; + state.basic = spec.value; } function applyBearer( - state: SecurityState, - spec: SecurityInputBearer | SecurityInputOAuth2 | SecurityInputOIDC + state: SecurityState, + spec: + | SecurityInputBearer + | SecurityInputOAuth2 + | SecurityInputOIDC + | SecurityInputOAuth2PasswordCredentials, ) { - if (spec.value == null) { - return; - } + if (typeof spec.value !== "string" || !spec.value) { + return; + } - let value = spec.value; - if (value.slice(0, 7).toLowerCase() !== "bearer ") { - value = `Bearer ${value}`; - } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } - state.headers[spec.fieldName] = value; + state.headers[spec.fieldName] = value; } diff --git a/src/lib/url.ts b/src/lib/url.ts index df58acb..6bc6356 100644 --- a/src/lib/url.ts +++ b/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/src/models/components/createactiontriggerrequest.ts b/src/models/components/createactiontriggerrequest.ts index a358836..0e42115 100644 --- a/src/models/components/createactiontriggerrequest.ts +++ b/src/models/components/createactiontriggerrequest.ts @@ -1,9 +1,12 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * The necessary input for your action's 'runAction' function. @@ -11,51 +14,118 @@ import * as z from "zod"; export type Input = {}; export type CreateActionTriggerRequest = { - /** - * The name of the action to trigger. - */ - actionName: string; - /** - * The necessary input for your action's 'runAction' function. - */ - input?: Input | undefined; + /** + * The name of the action to trigger. + */ + actionName: string; + /** + * The necessary input for your action's 'runAction' function. + */ + input?: Input | undefined; }; /** @internal */ +export const Input$inboundSchema: z.ZodType = z + .object({}); + +/** @internal */ +export type Input$Outbound = {}; + +/** @internal */ +export const Input$outboundSchema: z.ZodType< + Input$Outbound, + z.ZodTypeDef, + Input +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Input$ { - export const inboundSchema: z.ZodType = z.object({}); + /** @deprecated use `Input$inboundSchema` instead. */ + export const inboundSchema = Input$inboundSchema; + /** @deprecated use `Input$outboundSchema` instead. */ + export const outboundSchema = Input$outboundSchema; + /** @deprecated use `Input$Outbound` instead. */ + export type Outbound = Input$Outbound; +} - export type Outbound = {}; +export function inputToJSON(input: Input): string { + return JSON.stringify(Input$outboundSchema.parse(input)); +} - export const outboundSchema: z.ZodType = z.object({}); +export function inputFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Input$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Input' from JSON`, + ); } /** @internal */ +export const CreateActionTriggerRequest$inboundSchema: z.ZodType< + CreateActionTriggerRequest, + z.ZodTypeDef, + unknown +> = z.object({ + action_name: z.string(), + input: z.lazy(() => Input$inboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + "action_name": "actionName", + }); +}); + +/** @internal */ +export type CreateActionTriggerRequest$Outbound = { + action_name: string; + input?: Input$Outbound | undefined; +}; + +/** @internal */ +export const CreateActionTriggerRequest$outboundSchema: z.ZodType< + CreateActionTriggerRequest$Outbound, + z.ZodTypeDef, + CreateActionTriggerRequest +> = z.object({ + actionName: z.string(), + input: z.lazy(() => Input$outboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + actionName: "action_name", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateActionTriggerRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - action_name: z.string(), - input: z.lazy(() => Input$.inboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - action_name: "actionName", - }); - }); - - export type Outbound = { - action_name: string; - input?: Input$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - actionName: z.string(), - input: z.lazy(() => Input$.outboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - actionName: "action_name", - }); - }); + /** @deprecated use `CreateActionTriggerRequest$inboundSchema` instead. */ + export const inboundSchema = CreateActionTriggerRequest$inboundSchema; + /** @deprecated use `CreateActionTriggerRequest$outboundSchema` instead. */ + export const outboundSchema = CreateActionTriggerRequest$outboundSchema; + /** @deprecated use `CreateActionTriggerRequest$Outbound` instead. */ + export type Outbound = CreateActionTriggerRequest$Outbound; +} + +export function createActionTriggerRequestToJSON( + createActionTriggerRequest: CreateActionTriggerRequest, +): string { + return JSON.stringify( + CreateActionTriggerRequest$outboundSchema.parse(createActionTriggerRequest), + ); +} + +export function createActionTriggerRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateActionTriggerRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateActionTriggerRequest' from JSON`, + ); } diff --git a/src/models/components/createactiontriggerresponse.ts b/src/models/components/createactiontriggerresponse.ts index 17013d3..077a8ef 100644 --- a/src/models/components/createactiontriggerresponse.ts +++ b/src/models/components/createactiontriggerresponse.ts @@ -1,40 +1,80 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateActionTriggerResponse = { - /** - * The data returned by the action - */ - yourProperties?: string | undefined; + /** + * The data returned by the action + */ + yourProperties?: string | undefined; +}; + +/** @internal */ +export const CreateActionTriggerResponse$inboundSchema: z.ZodType< + CreateActionTriggerResponse, + z.ZodTypeDef, + unknown +> = z.object({ + "your-properties": z.string().optional(), +}).transform((v) => { + return remap$(v, { + "your-properties": "yourProperties", + }); +}); + +/** @internal */ +export type CreateActionTriggerResponse$Outbound = { + "your-properties"?: string | undefined; }; /** @internal */ +export const CreateActionTriggerResponse$outboundSchema: z.ZodType< + CreateActionTriggerResponse$Outbound, + z.ZodTypeDef, + CreateActionTriggerResponse +> = z.object({ + yourProperties: z.string().optional(), +}).transform((v) => { + return remap$(v, { + yourProperties: "your-properties", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateActionTriggerResponse$ { - export const inboundSchema: z.ZodType = z - .object({ - "your-properties": z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - "your-properties": "yourProperties", - }); - }); - - export type Outbound = { - "your-properties"?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - yourProperties: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - yourProperties: "your-properties", - }); - }); + /** @deprecated use `CreateActionTriggerResponse$inboundSchema` instead. */ + export const inboundSchema = CreateActionTriggerResponse$inboundSchema; + /** @deprecated use `CreateActionTriggerResponse$outboundSchema` instead. */ + export const outboundSchema = CreateActionTriggerResponse$outboundSchema; + /** @deprecated use `CreateActionTriggerResponse$Outbound` instead. */ + export type Outbound = CreateActionTriggerResponse$Outbound; +} + +export function createActionTriggerResponseToJSON( + createActionTriggerResponse: CreateActionTriggerResponse, +): string { + return JSON.stringify( + CreateActionTriggerResponse$outboundSchema.parse( + createActionTriggerResponse, + ), + ); +} + +export function createActionTriggerResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateActionTriggerResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateActionTriggerResponse' from JSON`, + ); } diff --git a/src/models/components/createconnectionrequest.ts b/src/models/components/createconnectionrequest.ts index 5f11280..c94846c 100644 --- a/src/models/components/createconnectionrequest.ts +++ b/src/models/components/createconnectionrequest.ts @@ -1,18 +1,58 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateConnectionRequest = {}; /** @internal */ +export const CreateConnectionRequest$inboundSchema: z.ZodType< + CreateConnectionRequest, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type CreateConnectionRequest$Outbound = {}; + +/** @internal */ +export const CreateConnectionRequest$outboundSchema: z.ZodType< + CreateConnectionRequest$Outbound, + z.ZodTypeDef, + CreateConnectionRequest +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateConnectionRequest$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `CreateConnectionRequest$inboundSchema` instead. */ + export const inboundSchema = CreateConnectionRequest$inboundSchema; + /** @deprecated use `CreateConnectionRequest$outboundSchema` instead. */ + export const outboundSchema = CreateConnectionRequest$outboundSchema; + /** @deprecated use `CreateConnectionRequest$Outbound` instead. */ + export type Outbound = CreateConnectionRequest$Outbound; +} - export type Outbound = {}; +export function createConnectionRequestToJSON( + createConnectionRequest: CreateConnectionRequest, +): string { + return JSON.stringify( + CreateConnectionRequest$outboundSchema.parse(createConnectionRequest), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function createConnectionRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateConnectionRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateConnectionRequest' from JSON`, + ); } diff --git a/src/models/components/createproxyrequest.ts b/src/models/components/createproxyrequest.ts index 0714b95..cee8e40 100644 --- a/src/models/components/createproxyrequest.ts +++ b/src/models/components/createproxyrequest.ts @@ -1,37 +1,75 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateProxyRequest = { - dollarANYBODYPARAMS?: string | undefined; + dollarANYBODYPARAMS?: string | undefined; +}; + +/** @internal */ +export const CreateProxyRequest$inboundSchema: z.ZodType< + CreateProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + $ANY_BODY_PARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "$ANY_BODY_PARAMS": "dollarANYBODYPARAMS", + }); +}); + +/** @internal */ +export type CreateProxyRequest$Outbound = { + $ANY_BODY_PARAMS?: string | undefined; }; /** @internal */ +export const CreateProxyRequest$outboundSchema: z.ZodType< + CreateProxyRequest$Outbound, + z.ZodTypeDef, + CreateProxyRequest +> = z.object({ + dollarANYBODYPARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - $ANY_BODY_PARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - $ANY_BODY_PARAMS: "dollarANYBODYPARAMS", - }); - }); - - export type Outbound = { - $ANY_BODY_PARAMS?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - dollarANYBODYPARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", - }); - }); + /** @deprecated use `CreateProxyRequest$inboundSchema` instead. */ + export const inboundSchema = CreateProxyRequest$inboundSchema; + /** @deprecated use `CreateProxyRequest$outboundSchema` instead. */ + export const outboundSchema = CreateProxyRequest$outboundSchema; + /** @deprecated use `CreateProxyRequest$Outbound` instead. */ + export type Outbound = CreateProxyRequest$Outbound; +} + +export function createProxyRequestToJSON( + createProxyRequest: CreateProxyRequest, +): string { + return JSON.stringify( + CreateProxyRequest$outboundSchema.parse(createProxyRequest), + ); +} + +export function createProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateProxyRequest' from JSON`, + ); } diff --git a/src/models/components/createsyncpauserequest.ts b/src/models/components/createsyncpauserequest.ts index 5ab77b0..c4baa2a 100644 --- a/src/models/components/createsyncpauserequest.ts +++ b/src/models/components/createsyncpauserequest.ts @@ -1,56 +1,94 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateSyncPauseRequest = { - /** - * The ID of the integration that you established within Nango. - */ - providerConfigKey: string; - /** - * The ID of the connection. If omitted, the syncs will be paused for all relevant connections. - */ - connectionId?: string | undefined; - /** - * A list of sync names that you wish to pause. - */ - syncs: Array; + /** + * The ID of the integration that you established within Nango. + */ + providerConfigKey: string; + /** + * The ID of the connection. If omitted, the syncs will be paused for all relevant connections. + */ + connectionId?: string | undefined; + /** + * A list of sync names that you wish to pause. + */ + syncs: Array; +}; + +/** @internal */ +export const CreateSyncPauseRequest$inboundSchema: z.ZodType< + CreateSyncPauseRequest, + z.ZodTypeDef, + unknown +> = z.object({ + provider_config_key: z.string(), + connection_id: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "connection_id": "connectionId", + }); +}); + +/** @internal */ +export type CreateSyncPauseRequest$Outbound = { + provider_config_key: string; + connection_id?: string | undefined; + syncs: Array; }; /** @internal */ +export const CreateSyncPauseRequest$outboundSchema: z.ZodType< + CreateSyncPauseRequest$Outbound, + z.ZodTypeDef, + CreateSyncPauseRequest +> = z.object({ + providerConfigKey: z.string(), + connectionId: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + connectionId: "connection_id", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateSyncPauseRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - provider_config_key: z.string(), - connection_id: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - connection_id: "connectionId", - }); - }); - - export type Outbound = { - provider_config_key: string; - connection_id?: string | undefined; - syncs: Array; - }; - - export const outboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - connectionId: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - connectionId: "connection_id", - }); - }); + /** @deprecated use `CreateSyncPauseRequest$inboundSchema` instead. */ + export const inboundSchema = CreateSyncPauseRequest$inboundSchema; + /** @deprecated use `CreateSyncPauseRequest$outboundSchema` instead. */ + export const outboundSchema = CreateSyncPauseRequest$outboundSchema; + /** @deprecated use `CreateSyncPauseRequest$Outbound` instead. */ + export type Outbound = CreateSyncPauseRequest$Outbound; +} + +export function createSyncPauseRequestToJSON( + createSyncPauseRequest: CreateSyncPauseRequest, +): string { + return JSON.stringify( + CreateSyncPauseRequest$outboundSchema.parse(createSyncPauseRequest), + ); +} + +export function createSyncPauseRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateSyncPauseRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateSyncPauseRequest' from JSON`, + ); } diff --git a/src/models/components/createsyncstartrequest.ts b/src/models/components/createsyncstartrequest.ts index ac52cfa..19fb311 100644 --- a/src/models/components/createsyncstartrequest.ts +++ b/src/models/components/createsyncstartrequest.ts @@ -1,56 +1,94 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateSyncStartRequest = { - /** - * The ID of the integration that you established within Nango. - */ - providerConfigKey: string; - /** - * The ID of the connection. If omitted, the syncs will be started for all relevant connections. - */ - connectionId?: string | undefined; - /** - * A list of sync names that you wish to start. - */ - syncs: Array; + /** + * The ID of the integration that you established within Nango. + */ + providerConfigKey: string; + /** + * The ID of the connection. If omitted, the syncs will be started for all relevant connections. + */ + connectionId?: string | undefined; + /** + * A list of sync names that you wish to start. + */ + syncs: Array; +}; + +/** @internal */ +export const CreateSyncStartRequest$inboundSchema: z.ZodType< + CreateSyncStartRequest, + z.ZodTypeDef, + unknown +> = z.object({ + provider_config_key: z.string(), + connection_id: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "connection_id": "connectionId", + }); +}); + +/** @internal */ +export type CreateSyncStartRequest$Outbound = { + provider_config_key: string; + connection_id?: string | undefined; + syncs: Array; }; /** @internal */ +export const CreateSyncStartRequest$outboundSchema: z.ZodType< + CreateSyncStartRequest$Outbound, + z.ZodTypeDef, + CreateSyncStartRequest +> = z.object({ + providerConfigKey: z.string(), + connectionId: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + connectionId: "connection_id", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateSyncStartRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - provider_config_key: z.string(), - connection_id: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - connection_id: "connectionId", - }); - }); - - export type Outbound = { - provider_config_key: string; - connection_id?: string | undefined; - syncs: Array; - }; - - export const outboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - connectionId: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - connectionId: "connection_id", - }); - }); + /** @deprecated use `CreateSyncStartRequest$inboundSchema` instead. */ + export const inboundSchema = CreateSyncStartRequest$inboundSchema; + /** @deprecated use `CreateSyncStartRequest$outboundSchema` instead. */ + export const outboundSchema = CreateSyncStartRequest$outboundSchema; + /** @deprecated use `CreateSyncStartRequest$Outbound` instead. */ + export type Outbound = CreateSyncStartRequest$Outbound; +} + +export function createSyncStartRequestToJSON( + createSyncStartRequest: CreateSyncStartRequest, +): string { + return JSON.stringify( + CreateSyncStartRequest$outboundSchema.parse(createSyncStartRequest), + ); +} + +export function createSyncStartRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateSyncStartRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateSyncStartRequest' from JSON`, + ); } diff --git a/src/models/components/createsynctriggerrequest.ts b/src/models/components/createsynctriggerrequest.ts index 7b841dd..2219935 100644 --- a/src/models/components/createsynctriggerrequest.ts +++ b/src/models/components/createsynctriggerrequest.ts @@ -1,56 +1,94 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateSyncTriggerRequest = { - /** - * The ID of the integration that you established within Nango. - */ - providerConfigKey: string; - /** - * The ID of the connection. If omitted, the syncs will be triggered for all relevant connections. - */ - connectionId?: string | undefined; - /** - * A list of sync names that you wish to trigger. - */ - syncs: Array; + /** + * The ID of the integration that you established within Nango. + */ + providerConfigKey: string; + /** + * The ID of the connection. If omitted, the syncs will be triggered for all relevant connections. + */ + connectionId?: string | undefined; + /** + * A list of sync names that you wish to trigger. + */ + syncs: Array; +}; + +/** @internal */ +export const CreateSyncTriggerRequest$inboundSchema: z.ZodType< + CreateSyncTriggerRequest, + z.ZodTypeDef, + unknown +> = z.object({ + provider_config_key: z.string(), + connection_id: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "connection_id": "connectionId", + }); +}); + +/** @internal */ +export type CreateSyncTriggerRequest$Outbound = { + provider_config_key: string; + connection_id?: string | undefined; + syncs: Array; }; /** @internal */ +export const CreateSyncTriggerRequest$outboundSchema: z.ZodType< + CreateSyncTriggerRequest$Outbound, + z.ZodTypeDef, + CreateSyncTriggerRequest +> = z.object({ + providerConfigKey: z.string(), + connectionId: z.string().optional(), + syncs: z.array(z.string()), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + connectionId: "connection_id", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateSyncTriggerRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - provider_config_key: z.string(), - connection_id: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - connection_id: "connectionId", - }); - }); - - export type Outbound = { - provider_config_key: string; - connection_id?: string | undefined; - syncs: Array; - }; - - export const outboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - connectionId: z.string().optional(), - syncs: z.array(z.string()), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - connectionId: "connection_id", - }); - }); + /** @deprecated use `CreateSyncTriggerRequest$inboundSchema` instead. */ + export const inboundSchema = CreateSyncTriggerRequest$inboundSchema; + /** @deprecated use `CreateSyncTriggerRequest$outboundSchema` instead. */ + export const outboundSchema = CreateSyncTriggerRequest$outboundSchema; + /** @deprecated use `CreateSyncTriggerRequest$Outbound` instead. */ + export type Outbound = CreateSyncTriggerRequest$Outbound; +} + +export function createSyncTriggerRequestToJSON( + createSyncTriggerRequest: CreateSyncTriggerRequest, +): string { + return JSON.stringify( + CreateSyncTriggerRequest$outboundSchema.parse(createSyncTriggerRequest), + ); +} + +export function createSyncTriggerRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateSyncTriggerRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateSyncTriggerRequest' from JSON`, + ); } diff --git a/src/models/components/getconnectionresponse.ts b/src/models/components/getconnectionresponse.ts index 766043a..0124a61 100644 --- a/src/models/components/getconnectionresponse.ts +++ b/src/models/components/getconnectionresponse.ts @@ -1,42 +1,120 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetConnectionResponseItems = {}; export type GetConnectionResponse = { - configs: Array; - items?: GetConnectionResponseItems | undefined; + configs: Array; + items?: GetConnectionResponseItems | undefined; }; /** @internal */ +export const GetConnectionResponseItems$inboundSchema: z.ZodType< + GetConnectionResponseItems, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type GetConnectionResponseItems$Outbound = {}; + +/** @internal */ +export const GetConnectionResponseItems$outboundSchema: z.ZodType< + GetConnectionResponseItems$Outbound, + z.ZodTypeDef, + GetConnectionResponseItems +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetConnectionResponseItems$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `GetConnectionResponseItems$inboundSchema` instead. */ + export const inboundSchema = GetConnectionResponseItems$inboundSchema; + /** @deprecated use `GetConnectionResponseItems$outboundSchema` instead. */ + export const outboundSchema = GetConnectionResponseItems$outboundSchema; + /** @deprecated use `GetConnectionResponseItems$Outbound` instead. */ + export type Outbound = GetConnectionResponseItems$Outbound; +} - export type Outbound = {}; +export function getConnectionResponseItemsToJSON( + getConnectionResponseItems: GetConnectionResponseItems, +): string { + return JSON.stringify( + GetConnectionResponseItems$outboundSchema.parse(getConnectionResponseItems), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function getConnectionResponseItemsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetConnectionResponseItems$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetConnectionResponseItems' from JSON`, + ); } /** @internal */ +export const GetConnectionResponse$inboundSchema: z.ZodType< + GetConnectionResponse, + z.ZodTypeDef, + unknown +> = z.object({ + configs: z.array(z.any()), + items: z.lazy(() => GetConnectionResponseItems$inboundSchema).optional(), +}); + +/** @internal */ +export type GetConnectionResponse$Outbound = { + configs: Array; + items?: GetConnectionResponseItems$Outbound | undefined; +}; + +/** @internal */ +export const GetConnectionResponse$outboundSchema: z.ZodType< + GetConnectionResponse$Outbound, + z.ZodTypeDef, + GetConnectionResponse +> = z.object({ + configs: z.array(z.any()), + items: z.lazy(() => GetConnectionResponseItems$outboundSchema).optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetConnectionResponse$ { - export const inboundSchema: z.ZodType = z.object({ - configs: z.array(z.any()), - items: z.lazy(() => GetConnectionResponseItems$.inboundSchema).optional(), - }); - - export type Outbound = { - configs: Array; - items?: GetConnectionResponseItems$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - configs: z.array(z.any()), - items: z.lazy(() => GetConnectionResponseItems$.outboundSchema).optional(), - }); + /** @deprecated use `GetConnectionResponse$inboundSchema` instead. */ + export const inboundSchema = GetConnectionResponse$inboundSchema; + /** @deprecated use `GetConnectionResponse$outboundSchema` instead. */ + export const outboundSchema = GetConnectionResponse$outboundSchema; + /** @deprecated use `GetConnectionResponse$Outbound` instead. */ + export type Outbound = GetConnectionResponse$Outbound; +} + +export function getConnectionResponseToJSON( + getConnectionResponse: GetConnectionResponse, +): string { + return JSON.stringify( + GetConnectionResponse$outboundSchema.parse(getConnectionResponse), + ); +} + +export function getConnectionResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetConnectionResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetConnectionResponse' from JSON`, + ); } diff --git a/src/models/components/getenvironmentvariableresponse.ts b/src/models/components/getenvironmentvariableresponse.ts index 6f4a003..ac10eab 100644 --- a/src/models/components/getenvironmentvariableresponse.ts +++ b/src/models/components/getenvironmentvariableresponse.ts @@ -1,36 +1,78 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetEnvironmentVariableResponse = { - /** - * The name of the environment variable - */ - name?: string | undefined; - /** - * The value of the environment variable - */ - value?: string | undefined; + /** + * The name of the environment variable + */ + name?: string | undefined; + /** + * The value of the environment variable + */ + value?: string | undefined; }; /** @internal */ +export const GetEnvironmentVariableResponse$inboundSchema: z.ZodType< + GetEnvironmentVariableResponse, + z.ZodTypeDef, + unknown +> = z.object({ + name: z.string().optional(), + value: z.string().optional(), +}); + +/** @internal */ +export type GetEnvironmentVariableResponse$Outbound = { + name?: string | undefined; + value?: string | undefined; +}; + +/** @internal */ +export const GetEnvironmentVariableResponse$outboundSchema: z.ZodType< + GetEnvironmentVariableResponse$Outbound, + z.ZodTypeDef, + GetEnvironmentVariableResponse +> = z.object({ + name: z.string().optional(), + value: 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 GetEnvironmentVariableResponse$ { - export const inboundSchema: z.ZodType = - z.object({ - name: z.string().optional(), - value: z.string().optional(), - }); - - export type Outbound = { - name?: string | undefined; - value?: string | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - name: z.string().optional(), - value: z.string().optional(), - }); + /** @deprecated use `GetEnvironmentVariableResponse$inboundSchema` instead. */ + export const inboundSchema = GetEnvironmentVariableResponse$inboundSchema; + /** @deprecated use `GetEnvironmentVariableResponse$outboundSchema` instead. */ + export const outboundSchema = GetEnvironmentVariableResponse$outboundSchema; + /** @deprecated use `GetEnvironmentVariableResponse$Outbound` instead. */ + export type Outbound = GetEnvironmentVariableResponse$Outbound; +} + +export function getEnvironmentVariableResponseToJSON( + getEnvironmentVariableResponse: GetEnvironmentVariableResponse, +): string { + return JSON.stringify( + GetEnvironmentVariableResponse$outboundSchema.parse( + getEnvironmentVariableResponse, + ), + ); +} + +export function getEnvironmentVariableResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetEnvironmentVariableResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetEnvironmentVariableResponse' from JSON`, + ); } diff --git a/src/models/components/getintegrationresponse.ts b/src/models/components/getintegrationresponse.ts index a9942df..d789a80 100644 --- a/src/models/components/getintegrationresponse.ts +++ b/src/models/components/getintegrationresponse.ts @@ -1,42 +1,113 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type Config = {}; export type GetIntegrationResponse = { - config: Config; - properties?: any | undefined; + config: Config; + properties?: any | undefined; }; /** @internal */ +export const Config$inboundSchema: z.ZodType = z + .object({}); + +/** @internal */ +export type Config$Outbound = {}; + +/** @internal */ +export const Config$outboundSchema: z.ZodType< + Config$Outbound, + z.ZodTypeDef, + Config +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Config$ { - export const inboundSchema: z.ZodType = z.object({}); + /** @deprecated use `Config$inboundSchema` instead. */ + export const inboundSchema = Config$inboundSchema; + /** @deprecated use `Config$outboundSchema` instead. */ + export const outboundSchema = Config$outboundSchema; + /** @deprecated use `Config$Outbound` instead. */ + export type Outbound = Config$Outbound; +} - export type Outbound = {}; +export function configToJSON(config: Config): string { + return JSON.stringify(Config$outboundSchema.parse(config)); +} - export const outboundSchema: z.ZodType = z.object({}); +export function configFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Config$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Config' from JSON`, + ); } /** @internal */ +export const GetIntegrationResponse$inboundSchema: z.ZodType< + GetIntegrationResponse, + z.ZodTypeDef, + unknown +> = z.object({ + config: z.lazy(() => Config$inboundSchema), + properties: z.any().optional(), +}); + +/** @internal */ +export type GetIntegrationResponse$Outbound = { + config: Config$Outbound; + properties?: any | undefined; +}; + +/** @internal */ +export const GetIntegrationResponse$outboundSchema: z.ZodType< + GetIntegrationResponse$Outbound, + z.ZodTypeDef, + GetIntegrationResponse +> = z.object({ + config: z.lazy(() => Config$outboundSchema), + properties: z.any().optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetIntegrationResponse$ { - export const inboundSchema: z.ZodType = z.object( - { - config: z.lazy(() => Config$.inboundSchema), - properties: z.any().optional(), - } - ); - - export type Outbound = { - config: Config$.Outbound; - properties?: any | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - config: z.lazy(() => Config$.outboundSchema), - properties: z.any().optional(), - }); + /** @deprecated use `GetIntegrationResponse$inboundSchema` instead. */ + export const inboundSchema = GetIntegrationResponse$inboundSchema; + /** @deprecated use `GetIntegrationResponse$outboundSchema` instead. */ + export const outboundSchema = GetIntegrationResponse$outboundSchema; + /** @deprecated use `GetIntegrationResponse$Outbound` instead. */ + export type Outbound = GetIntegrationResponse$Outbound; +} + +export function getIntegrationResponseToJSON( + getIntegrationResponse: GetIntegrationResponse, +): string { + return JSON.stringify( + GetIntegrationResponse$outboundSchema.parse(getIntegrationResponse), + ); +} + +export function getIntegrationResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetIntegrationResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetIntegrationResponse' from JSON`, + ); } diff --git a/src/models/components/getrecordresponse.ts b/src/models/components/getrecordresponse.ts index 30fbc48..d8e4b43 100644 --- a/src/models/components/getrecordresponse.ts +++ b/src/models/components/getrecordresponse.ts @@ -1,164 +1,280 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * The last action seen on this record */ export enum GetRecordResponseLastAction { - Added = "ADDED", - Updated = "UPDATED", - Deleted = "DELETED", + Added = "ADDED", + Updated = "UPDATED", + Deleted = "DELETED", } export type GetRecordResponseNangoMetadata = { - /** - * The timestamp at which Nango detected the record as deleted - */ - deletedAt?: string | undefined; - /** - * The last action seen on this record - */ - lastAction?: GetRecordResponseLastAction | undefined; - /** - * The timestamp at which Nango first saw this record - */ - firstSeenAt?: string | undefined; - /** - * The timestamp at which Nango last detected a change to this record - */ - lastModifiedAt?: string | undefined; + /** + * The timestamp at which Nango detected the record as deleted + */ + deletedAt?: string | undefined; + /** + * The last action seen on this record + */ + lastAction?: GetRecordResponseLastAction | undefined; + /** + * The timestamp at which Nango first saw this record + */ + firstSeenAt?: string | undefined; + /** + * The timestamp at which Nango last detected a change to this record + */ + lastModifiedAt?: string | undefined; }; export type Records = { - /** - * The data Nango synced in for you - */ - yourProperties?: string | undefined; - nangoMetadata?: GetRecordResponseNangoMetadata | undefined; + /** + * The data Nango synced in for you + */ + yourProperties?: string | undefined; + nangoMetadata?: GetRecordResponseNangoMetadata | undefined; }; export type GetRecordResponse = { - records?: Array | undefined; - /** - * The base64-encoded cursor for pagination - */ - nextCursor?: string | undefined; + records?: Array | undefined; + /** + * The base64-encoded cursor for pagination + */ + nextCursor?: string | undefined; }; /** @internal */ +export const GetRecordResponseLastAction$inboundSchema: z.ZodNativeEnum< + typeof GetRecordResponseLastAction +> = z.nativeEnum(GetRecordResponseLastAction); + +/** @internal */ +export const GetRecordResponseLastAction$outboundSchema: z.ZodNativeEnum< + typeof GetRecordResponseLastAction +> = GetRecordResponseLastAction$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetRecordResponseLastAction$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum( - GetRecordResponseLastAction - ); - export const outboundSchema: z.ZodNativeEnum = - inboundSchema; + /** @deprecated use `GetRecordResponseLastAction$inboundSchema` instead. */ + export const inboundSchema = GetRecordResponseLastAction$inboundSchema; + /** @deprecated use `GetRecordResponseLastAction$outboundSchema` instead. */ + export const outboundSchema = GetRecordResponseLastAction$outboundSchema; } /** @internal */ +export const GetRecordResponseNangoMetadata$inboundSchema: z.ZodType< + GetRecordResponseNangoMetadata, + z.ZodTypeDef, + unknown +> = z.object({ + deleted_at: z.string().optional(), + last_action: GetRecordResponseLastAction$inboundSchema.optional(), + first_seen_at: z.string().optional(), + last_modified_at: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "deleted_at": "deletedAt", + "last_action": "lastAction", + "first_seen_at": "firstSeenAt", + "last_modified_at": "lastModifiedAt", + }); +}); + +/** @internal */ +export type GetRecordResponseNangoMetadata$Outbound = { + deleted_at?: string | undefined; + last_action?: string | undefined; + first_seen_at?: string | undefined; + last_modified_at?: string | undefined; +}; + +/** @internal */ +export const GetRecordResponseNangoMetadata$outboundSchema: z.ZodType< + GetRecordResponseNangoMetadata$Outbound, + z.ZodTypeDef, + GetRecordResponseNangoMetadata +> = z.object({ + deletedAt: z.string().optional(), + lastAction: GetRecordResponseLastAction$outboundSchema.optional(), + firstSeenAt: z.string().optional(), + lastModifiedAt: z.string().optional(), +}).transform((v) => { + return remap$(v, { + deletedAt: "deleted_at", + lastAction: "last_action", + firstSeenAt: "first_seen_at", + lastModifiedAt: "last_modified_at", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetRecordResponseNangoMetadata$ { - export const inboundSchema: z.ZodType = z - .object({ - deleted_at: z.string().optional(), - last_action: GetRecordResponseLastAction$.inboundSchema.optional(), - first_seen_at: z.string().optional(), - last_modified_at: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - deleted_at: "deletedAt", - last_action: "lastAction", - first_seen_at: "firstSeenAt", - last_modified_at: "lastModifiedAt", - }); - }); - - export type Outbound = { - deleted_at?: string | undefined; - last_action?: string | undefined; - first_seen_at?: string | undefined; - last_modified_at?: string | undefined; - }; - - export const outboundSchema: z.ZodType = - z - .object({ - deletedAt: z.string().optional(), - lastAction: GetRecordResponseLastAction$.outboundSchema.optional(), - firstSeenAt: z.string().optional(), - lastModifiedAt: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - deletedAt: "deleted_at", - lastAction: "last_action", - firstSeenAt: "first_seen_at", - lastModifiedAt: "last_modified_at", - }); - }); + /** @deprecated use `GetRecordResponseNangoMetadata$inboundSchema` instead. */ + export const inboundSchema = GetRecordResponseNangoMetadata$inboundSchema; + /** @deprecated use `GetRecordResponseNangoMetadata$outboundSchema` instead. */ + export const outboundSchema = GetRecordResponseNangoMetadata$outboundSchema; + /** @deprecated use `GetRecordResponseNangoMetadata$Outbound` instead. */ + export type Outbound = GetRecordResponseNangoMetadata$Outbound; +} + +export function getRecordResponseNangoMetadataToJSON( + getRecordResponseNangoMetadata: GetRecordResponseNangoMetadata, +): string { + return JSON.stringify( + GetRecordResponseNangoMetadata$outboundSchema.parse( + getRecordResponseNangoMetadata, + ), + ); +} + +export function getRecordResponseNangoMetadataFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetRecordResponseNangoMetadata$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetRecordResponseNangoMetadata' from JSON`, + ); } /** @internal */ +export const Records$inboundSchema: z.ZodType = + z.object({ + "your-properties": z.string().optional(), + _nango_metadata: z.lazy(() => GetRecordResponseNangoMetadata$inboundSchema) + .optional(), + }).transform((v) => { + return remap$(v, { + "your-properties": "yourProperties", + "_nango_metadata": "nangoMetadata", + }); + }); + +/** @internal */ +export type Records$Outbound = { + "your-properties"?: string | undefined; + _nango_metadata?: GetRecordResponseNangoMetadata$Outbound | undefined; +}; + +/** @internal */ +export const Records$outboundSchema: z.ZodType< + Records$Outbound, + z.ZodTypeDef, + Records +> = z.object({ + yourProperties: z.string().optional(), + nangoMetadata: z.lazy(() => GetRecordResponseNangoMetadata$outboundSchema) + .optional(), +}).transform((v) => { + return remap$(v, { + yourProperties: "your-properties", + nangoMetadata: "_nango_metadata", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Records$ { - export const inboundSchema: z.ZodType = z - .object({ - "your-properties": z.string().optional(), - _nango_metadata: z.lazy(() => GetRecordResponseNangoMetadata$.inboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - "your-properties": "yourProperties", - _nango_metadata: "nangoMetadata", - }); - }); - - export type Outbound = { - "your-properties"?: string | undefined; - _nango_metadata?: GetRecordResponseNangoMetadata$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - yourProperties: z.string().optional(), - nangoMetadata: z.lazy(() => GetRecordResponseNangoMetadata$.outboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - yourProperties: "your-properties", - nangoMetadata: "_nango_metadata", - }); - }); + /** @deprecated use `Records$inboundSchema` instead. */ + export const inboundSchema = Records$inboundSchema; + /** @deprecated use `Records$outboundSchema` instead. */ + export const outboundSchema = Records$outboundSchema; + /** @deprecated use `Records$Outbound` instead. */ + export type Outbound = Records$Outbound; } +export function recordsToJSON(records: Records): string { + return JSON.stringify(Records$outboundSchema.parse(records)); +} + +export function recordsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Records$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Records' from JSON`, + ); +} + +/** @internal */ +export const GetRecordResponse$inboundSchema: z.ZodType< + GetRecordResponse, + z.ZodTypeDef, + unknown +> = z.object({ + records: z.array(z.lazy(() => Records$inboundSchema)).optional(), + next_cursor: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "next_cursor": "nextCursor", + }); +}); + /** @internal */ +export type GetRecordResponse$Outbound = { + records?: Array | undefined; + next_cursor?: string | undefined; +}; + +/** @internal */ +export const GetRecordResponse$outboundSchema: z.ZodType< + GetRecordResponse$Outbound, + z.ZodTypeDef, + GetRecordResponse +> = z.object({ + records: z.array(z.lazy(() => Records$outboundSchema)).optional(), + nextCursor: z.string().optional(), +}).transform((v) => { + return remap$(v, { + nextCursor: "next_cursor", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetRecordResponse$ { - export const inboundSchema: z.ZodType = z - .object({ - records: z.array(z.lazy(() => Records$.inboundSchema)).optional(), - next_cursor: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - next_cursor: "nextCursor", - }); - }); - - export type Outbound = { - records?: Array | undefined; - next_cursor?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - records: z.array(z.lazy(() => Records$.outboundSchema)).optional(), - nextCursor: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - nextCursor: "next_cursor", - }); - }); + /** @deprecated use `GetRecordResponse$inboundSchema` instead. */ + export const inboundSchema = GetRecordResponse$inboundSchema; + /** @deprecated use `GetRecordResponse$outboundSchema` instead. */ + export const outboundSchema = GetRecordResponse$outboundSchema; + /** @deprecated use `GetRecordResponse$Outbound` instead. */ + export type Outbound = GetRecordResponse$Outbound; +} + +export function getRecordResponseToJSON( + getRecordResponse: GetRecordResponse, +): string { + return JSON.stringify( + GetRecordResponse$outboundSchema.parse(getRecordResponse), + ); +} + +export function getRecordResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetRecordResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetRecordResponse' from JSON`, + ); } diff --git a/src/models/components/getsyncrecordresponse.ts b/src/models/components/getsyncrecordresponse.ts index 4ba8d04..be612a5 100644 --- a/src/models/components/getsyncrecordresponse.ts +++ b/src/models/components/getsyncrecordresponse.ts @@ -1,122 +1,204 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * The last action seen on this record */ export enum LastAction { - Added = "ADDED", - Updated = "UPDATED", - Deleted = "DELETED", + Added = "ADDED", + Updated = "UPDATED", + Deleted = "DELETED", } export type NangoMetadata = { - /** - * The timestamp at which Nango detected the record as deleted - */ - deletedAt?: string | undefined; - /** - * The last action seen on this record - */ - lastAction?: LastAction | undefined; - /** - * The timestamp at which Nango first saw this record - */ - firstSeenAt?: string | undefined; - /** - * The timestamp at which Nango last detected a change to this record - */ - lastModifiedAt?: string | undefined; + /** + * The timestamp at which Nango detected the record as deleted + */ + deletedAt?: string | undefined; + /** + * The last action seen on this record + */ + lastAction?: LastAction | undefined; + /** + * The timestamp at which Nango first saw this record + */ + firstSeenAt?: string | undefined; + /** + * The timestamp at which Nango last detected a change to this record + */ + lastModifiedAt?: string | undefined; }; export type GetSyncRecordResponse = { - /** - * The data Nango synced in for you - */ - yourProperties?: string | undefined; - nangoMetadata?: NangoMetadata | undefined; + /** + * The data Nango synced in for you + */ + yourProperties?: string | undefined; + nangoMetadata?: NangoMetadata | undefined; }; /** @internal */ +export const LastAction$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(LastAction); + +/** @internal */ +export const LastAction$outboundSchema: z.ZodNativeEnum = + LastAction$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace LastAction$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(LastAction); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `LastAction$inboundSchema` instead. */ + export const inboundSchema = LastAction$inboundSchema; + /** @deprecated use `LastAction$outboundSchema` instead. */ + export const outboundSchema = LastAction$outboundSchema; } /** @internal */ +export const NangoMetadata$inboundSchema: z.ZodType< + NangoMetadata, + z.ZodTypeDef, + unknown +> = z.object({ + deleted_at: z.string().optional(), + last_action: LastAction$inboundSchema.optional(), + first_seen_at: z.string().optional(), + last_modified_at: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "deleted_at": "deletedAt", + "last_action": "lastAction", + "first_seen_at": "firstSeenAt", + "last_modified_at": "lastModifiedAt", + }); +}); + +/** @internal */ +export type NangoMetadata$Outbound = { + deleted_at?: string | undefined; + last_action?: string | undefined; + first_seen_at?: string | undefined; + last_modified_at?: string | undefined; +}; + +/** @internal */ +export const NangoMetadata$outboundSchema: z.ZodType< + NangoMetadata$Outbound, + z.ZodTypeDef, + NangoMetadata +> = z.object({ + deletedAt: z.string().optional(), + lastAction: LastAction$outboundSchema.optional(), + firstSeenAt: z.string().optional(), + lastModifiedAt: z.string().optional(), +}).transform((v) => { + return remap$(v, { + deletedAt: "deleted_at", + lastAction: "last_action", + firstSeenAt: "first_seen_at", + lastModifiedAt: "last_modified_at", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace NangoMetadata$ { - export const inboundSchema: z.ZodType = z - .object({ - deleted_at: z.string().optional(), - last_action: LastAction$.inboundSchema.optional(), - first_seen_at: z.string().optional(), - last_modified_at: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - deleted_at: "deletedAt", - last_action: "lastAction", - first_seen_at: "firstSeenAt", - last_modified_at: "lastModifiedAt", - }); - }); - - export type Outbound = { - deleted_at?: string | undefined; - last_action?: string | undefined; - first_seen_at?: string | undefined; - last_modified_at?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - deletedAt: z.string().optional(), - lastAction: LastAction$.outboundSchema.optional(), - firstSeenAt: z.string().optional(), - lastModifiedAt: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - deletedAt: "deleted_at", - lastAction: "last_action", - firstSeenAt: "first_seen_at", - lastModifiedAt: "last_modified_at", - }); - }); + /** @deprecated use `NangoMetadata$inboundSchema` instead. */ + export const inboundSchema = NangoMetadata$inboundSchema; + /** @deprecated use `NangoMetadata$outboundSchema` instead. */ + export const outboundSchema = NangoMetadata$outboundSchema; + /** @deprecated use `NangoMetadata$Outbound` instead. */ + export type Outbound = NangoMetadata$Outbound; } +export function nangoMetadataToJSON(nangoMetadata: NangoMetadata): string { + return JSON.stringify(NangoMetadata$outboundSchema.parse(nangoMetadata)); +} + +export function nangoMetadataFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => NangoMetadata$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'NangoMetadata' from JSON`, + ); +} + +/** @internal */ +export const GetSyncRecordResponse$inboundSchema: z.ZodType< + GetSyncRecordResponse, + z.ZodTypeDef, + unknown +> = z.object({ + "your-properties": z.string().optional(), + _nango_metadata: z.lazy(() => NangoMetadata$inboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + "your-properties": "yourProperties", + "_nango_metadata": "nangoMetadata", + }); +}); + +/** @internal */ +export type GetSyncRecordResponse$Outbound = { + "your-properties"?: string | undefined; + _nango_metadata?: NangoMetadata$Outbound | undefined; +}; + /** @internal */ +export const GetSyncRecordResponse$outboundSchema: z.ZodType< + GetSyncRecordResponse$Outbound, + z.ZodTypeDef, + GetSyncRecordResponse +> = z.object({ + yourProperties: z.string().optional(), + nangoMetadata: z.lazy(() => NangoMetadata$outboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + yourProperties: "your-properties", + nangoMetadata: "_nango_metadata", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetSyncRecordResponse$ { - export const inboundSchema: z.ZodType = z - .object({ - "your-properties": z.string().optional(), - _nango_metadata: z.lazy(() => NangoMetadata$.inboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - "your-properties": "yourProperties", - _nango_metadata: "nangoMetadata", - }); - }); - - export type Outbound = { - "your-properties"?: string | undefined; - _nango_metadata?: NangoMetadata$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - yourProperties: z.string().optional(), - nangoMetadata: z.lazy(() => NangoMetadata$.outboundSchema).optional(), - }) - .transform((v) => { - return remap$(v, { - yourProperties: "your-properties", - nangoMetadata: "_nango_metadata", - }); - }); + /** @deprecated use `GetSyncRecordResponse$inboundSchema` instead. */ + export const inboundSchema = GetSyncRecordResponse$inboundSchema; + /** @deprecated use `GetSyncRecordResponse$outboundSchema` instead. */ + export const outboundSchema = GetSyncRecordResponse$outboundSchema; + /** @deprecated use `GetSyncRecordResponse$Outbound` instead. */ + export type Outbound = GetSyncRecordResponse$Outbound; +} + +export function getSyncRecordResponseToJSON( + getSyncRecordResponse: GetSyncRecordResponse, +): string { + return JSON.stringify( + GetSyncRecordResponse$outboundSchema.parse(getSyncRecordResponse), + ); +} + +export function getSyncRecordResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetSyncRecordResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetSyncRecordResponse' from JSON`, + ); } diff --git a/src/models/components/getsyncstatusresponse.ts b/src/models/components/getsyncstatusresponse.ts index 42b34b9..9d658a7 100644 --- a/src/models/components/getsyncstatusresponse.ts +++ b/src/models/components/getsyncstatusresponse.ts @@ -1,26 +1,29 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * The current status of the sync. */ export enum Status { - Running = "RUNNING", - Paused = "PAUSED", - Stopped = "STOPPED", - Success = "SUCCESS", - Error = "ERROR", + Running = "RUNNING", + Paused = "PAUSED", + Stopped = "STOPPED", + Success = "SUCCESS", + Error = "ERROR", } /** * The most recent sync type completed */ export enum Type { - Incremental = "INCREMENTAL", - Initial = "INITIAL", + Incremental = "INCREMENTAL", + Initial = "INITIAL", } /** @@ -29,113 +32,245 @@ export enum Type { export type LatestResult = {}; export type Syncs = { - /** - * The unique identifier for the sync. - */ - id?: string | undefined; - /** - * The name of the sync. - */ - name?: string | undefined; - /** - * The current status of the sync. - */ - status?: Status | undefined; - /** - * The most recent sync type completed - */ - type?: Type | undefined; - /** - * ISO string of the most recently completed sync - */ - finishedAt?: string | undefined; - /** - * ISO string of the next scheduled sync time - */ - nextScheduledSyncAt?: string | undefined; - /** - * The execution frequency of the sync - */ - frequency?: string | undefined; - /** - * Additional information regarding the latest result of the sync. Contains a model name with added, updated and deleted records - */ - latestResult?: LatestResult | undefined; + /** + * The unique identifier for the sync. + */ + id?: string | undefined; + /** + * The name of the sync. + */ + name?: string | undefined; + /** + * The current status of the sync. + */ + status?: Status | undefined; + /** + * The most recent sync type completed + */ + type?: Type | undefined; + /** + * ISO string of the most recently completed sync + */ + finishedAt?: string | undefined; + /** + * ISO string of the next scheduled sync time + */ + nextScheduledSyncAt?: string | undefined; + /** + * The execution frequency of the sync + */ + frequency?: string | undefined; + /** + * Additional information regarding the latest result of the sync. Contains a model name with added, updated and deleted records + */ + latestResult?: LatestResult | undefined; }; export type GetSyncStatusResponse = { - syncs?: Array | undefined; + syncs?: Array | undefined; }; /** @internal */ +export const Status$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(Status); + +/** @internal */ +export const Status$outboundSchema: z.ZodNativeEnum = + Status$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Status$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(Status); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `Status$inboundSchema` instead. */ + export const inboundSchema = Status$inboundSchema; + /** @deprecated use `Status$outboundSchema` instead. */ + export const outboundSchema = Status$outboundSchema; } /** @internal */ +export const Type$inboundSchema: z.ZodNativeEnum = z.nativeEnum( + Type, +); + +/** @internal */ +export const Type$outboundSchema: z.ZodNativeEnum = + Type$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Type$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(Type); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `Type$inboundSchema` instead. */ + export const inboundSchema = Type$inboundSchema; + /** @deprecated use `Type$outboundSchema` instead. */ + export const outboundSchema = Type$outboundSchema; } /** @internal */ +export const LatestResult$inboundSchema: z.ZodType< + LatestResult, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type LatestResult$Outbound = {}; + +/** @internal */ +export const LatestResult$outboundSchema: z.ZodType< + LatestResult$Outbound, + z.ZodTypeDef, + LatestResult +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace LatestResult$ { - export const inboundSchema: z.ZodType = z.object({}); + /** @deprecated use `LatestResult$inboundSchema` instead. */ + export const inboundSchema = LatestResult$inboundSchema; + /** @deprecated use `LatestResult$outboundSchema` instead. */ + export const outboundSchema = LatestResult$outboundSchema; + /** @deprecated use `LatestResult$Outbound` instead. */ + export type Outbound = LatestResult$Outbound; +} - export type Outbound = {}; +export function latestResultToJSON(latestResult: LatestResult): string { + return JSON.stringify(LatestResult$outboundSchema.parse(latestResult)); +} - export const outboundSchema: z.ZodType = z.object({}); +export function latestResultFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => LatestResult$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'LatestResult' from JSON`, + ); } /** @internal */ +export const Syncs$inboundSchema: z.ZodType = z + .object({ + id: z.string().optional(), + name: z.string().optional(), + status: Status$inboundSchema.optional(), + type: Type$inboundSchema.optional(), + finishedAt: z.string().optional(), + nextScheduledSyncAt: z.string().optional(), + frequency: z.string().optional(), + latestResult: z.lazy(() => LatestResult$inboundSchema).optional(), + }); + +/** @internal */ +export type Syncs$Outbound = { + id?: string | undefined; + name?: string | undefined; + status?: string | undefined; + type?: string | undefined; + finishedAt?: string | undefined; + nextScheduledSyncAt?: string | undefined; + frequency?: string | undefined; + latestResult?: LatestResult$Outbound | undefined; +}; + +/** @internal */ +export const Syncs$outboundSchema: z.ZodType< + Syncs$Outbound, + z.ZodTypeDef, + Syncs +> = z.object({ + id: z.string().optional(), + name: z.string().optional(), + status: Status$outboundSchema.optional(), + type: Type$outboundSchema.optional(), + finishedAt: z.string().optional(), + nextScheduledSyncAt: z.string().optional(), + frequency: z.string().optional(), + latestResult: z.lazy(() => LatestResult$outboundSchema).optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Syncs$ { - export const inboundSchema: z.ZodType = z.object({ - id: z.string().optional(), - name: z.string().optional(), - status: Status$.inboundSchema.optional(), - type: Type$.inboundSchema.optional(), - finishedAt: z.string().optional(), - nextScheduledSyncAt: z.string().optional(), - frequency: z.string().optional(), - latestResult: z.lazy(() => LatestResult$.inboundSchema).optional(), - }); - - export type Outbound = { - id?: string | undefined; - name?: string | undefined; - status?: string | undefined; - type?: string | undefined; - finishedAt?: string | undefined; - nextScheduledSyncAt?: string | undefined; - frequency?: string | undefined; - latestResult?: LatestResult$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = z.object({ - id: z.string().optional(), - name: z.string().optional(), - status: Status$.outboundSchema.optional(), - type: Type$.outboundSchema.optional(), - finishedAt: z.string().optional(), - nextScheduledSyncAt: z.string().optional(), - frequency: z.string().optional(), - latestResult: z.lazy(() => LatestResult$.outboundSchema).optional(), - }); + /** @deprecated use `Syncs$inboundSchema` instead. */ + export const inboundSchema = Syncs$inboundSchema; + /** @deprecated use `Syncs$outboundSchema` instead. */ + export const outboundSchema = Syncs$outboundSchema; + /** @deprecated use `Syncs$Outbound` instead. */ + export type Outbound = Syncs$Outbound; } +export function syncsToJSON(syncs: Syncs): string { + return JSON.stringify(Syncs$outboundSchema.parse(syncs)); +} + +export function syncsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Syncs$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Syncs' from JSON`, + ); +} + +/** @internal */ +export const GetSyncStatusResponse$inboundSchema: z.ZodType< + GetSyncStatusResponse, + z.ZodTypeDef, + unknown +> = z.object({ + syncs: z.array(z.lazy(() => Syncs$inboundSchema)).optional(), +}); + /** @internal */ +export type GetSyncStatusResponse$Outbound = { + syncs?: Array | undefined; +}; + +/** @internal */ +export const GetSyncStatusResponse$outboundSchema: z.ZodType< + GetSyncStatusResponse$Outbound, + z.ZodTypeDef, + GetSyncStatusResponse +> = z.object({ + syncs: z.array(z.lazy(() => Syncs$outboundSchema)).optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetSyncStatusResponse$ { - export const inboundSchema: z.ZodType = z.object({ - syncs: z.array(z.lazy(() => Syncs$.inboundSchema)).optional(), - }); - - export type Outbound = { - syncs?: Array | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - syncs: z.array(z.lazy(() => Syncs$.outboundSchema)).optional(), - }); + /** @deprecated use `GetSyncStatusResponse$inboundSchema` instead. */ + export const inboundSchema = GetSyncStatusResponse$inboundSchema; + /** @deprecated use `GetSyncStatusResponse$outboundSchema` instead. */ + export const outboundSchema = GetSyncStatusResponse$outboundSchema; + /** @deprecated use `GetSyncStatusResponse$Outbound` instead. */ + export type Outbound = GetSyncStatusResponse$Outbound; +} + +export function getSyncStatusResponseToJSON( + getSyncStatusResponse: GetSyncStatusResponse, +): string { + return JSON.stringify( + GetSyncStatusResponse$outboundSchema.parse(getSyncStatusResponse), + ); +} + +export function getSyncStatusResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetSyncStatusResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetSyncStatusResponse' from JSON`, + ); } diff --git a/src/models/components/index.ts b/src/models/components/index.ts index 24e0f8d..af3ffe1 100644 --- a/src/models/components/index.ts +++ b/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 "./createactiontriggerrequest.js"; diff --git a/src/models/components/integrationsresponse200.ts b/src/models/components/integrationsresponse200.ts index 4f0b98a..63d7ddd 100644 --- a/src/models/components/integrationsresponse200.ts +++ b/src/models/components/integrationsresponse200.ts @@ -1,41 +1,113 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type Items = {}; export type IntegrationsResponse200 = { - configs: Array; - items?: Items | undefined; + configs: Array; + items?: Items | undefined; }; /** @internal */ +export const Items$inboundSchema: z.ZodType = z + .object({}); + +/** @internal */ +export type Items$Outbound = {}; + +/** @internal */ +export const Items$outboundSchema: z.ZodType< + Items$Outbound, + z.ZodTypeDef, + Items +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Items$ { - export const inboundSchema: z.ZodType = z.object({}); + /** @deprecated use `Items$inboundSchema` instead. */ + export const inboundSchema = Items$inboundSchema; + /** @deprecated use `Items$outboundSchema` instead. */ + export const outboundSchema = Items$outboundSchema; + /** @deprecated use `Items$Outbound` instead. */ + export type Outbound = Items$Outbound; +} - export type Outbound = {}; +export function itemsToJSON(items: Items): string { + return JSON.stringify(Items$outboundSchema.parse(items)); +} - export const outboundSchema: z.ZodType = z.object({}); +export function itemsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Items$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Items' from JSON`, + ); } /** @internal */ +export const IntegrationsResponse200$inboundSchema: z.ZodType< + IntegrationsResponse200, + z.ZodTypeDef, + unknown +> = z.object({ + configs: z.array(z.any()), + items: z.lazy(() => Items$inboundSchema).optional(), +}); + +/** @internal */ +export type IntegrationsResponse200$Outbound = { + configs: Array; + items?: Items$Outbound | undefined; +}; + +/** @internal */ +export const IntegrationsResponse200$outboundSchema: z.ZodType< + IntegrationsResponse200$Outbound, + z.ZodTypeDef, + IntegrationsResponse200 +> = z.object({ + configs: z.array(z.any()), + items: z.lazy(() => Items$outboundSchema).optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace IntegrationsResponse200$ { - export const inboundSchema: z.ZodType = - z.object({ - configs: z.array(z.any()), - items: z.lazy(() => Items$.inboundSchema).optional(), - }); - - export type Outbound = { - configs: Array; - items?: Items$.Outbound | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - configs: z.array(z.any()), - items: z.lazy(() => Items$.outboundSchema).optional(), - }); + /** @deprecated use `IntegrationsResponse200$inboundSchema` instead. */ + export const inboundSchema = IntegrationsResponse200$inboundSchema; + /** @deprecated use `IntegrationsResponse200$outboundSchema` instead. */ + export const outboundSchema = IntegrationsResponse200$outboundSchema; + /** @deprecated use `IntegrationsResponse200$Outbound` instead. */ + export type Outbound = IntegrationsResponse200$Outbound; +} + +export function integrationsResponse200ToJSON( + integrationsResponse200: IntegrationsResponse200, +): string { + return JSON.stringify( + IntegrationsResponse200$outboundSchema.parse(integrationsResponse200), + ); +} + +export function integrationsResponse200FromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => IntegrationsResponse200$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'IntegrationsResponse200' from JSON`, + ); } diff --git a/src/models/components/listintegrationsrequest.ts b/src/models/components/listintegrationsrequest.ts index 1ce5700..ae831c8 100644 --- a/src/models/components/listintegrationsrequest.ts +++ b/src/models/components/listintegrationsrequest.ts @@ -1,18 +1,58 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type ListIntegrationsRequest = {}; /** @internal */ +export const ListIntegrationsRequest$inboundSchema: z.ZodType< + ListIntegrationsRequest, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type ListIntegrationsRequest$Outbound = {}; + +/** @internal */ +export const ListIntegrationsRequest$outboundSchema: z.ZodType< + ListIntegrationsRequest$Outbound, + z.ZodTypeDef, + ListIntegrationsRequest +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace ListIntegrationsRequest$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `ListIntegrationsRequest$inboundSchema` instead. */ + export const inboundSchema = ListIntegrationsRequest$inboundSchema; + /** @deprecated use `ListIntegrationsRequest$outboundSchema` instead. */ + export const outboundSchema = ListIntegrationsRequest$outboundSchema; + /** @deprecated use `ListIntegrationsRequest$Outbound` instead. */ + export type Outbound = ListIntegrationsRequest$Outbound; +} - export type Outbound = {}; +export function listIntegrationsRequestToJSON( + listIntegrationsRequest: ListIntegrationsRequest, +): string { + return JSON.stringify( + ListIntegrationsRequest$outboundSchema.parse(listIntegrationsRequest), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function listIntegrationsRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => ListIntegrationsRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'ListIntegrationsRequest' from JSON`, + ); } diff --git a/src/models/components/patchproxyrequest.ts b/src/models/components/patchproxyrequest.ts index de0ad77..cd4bfe5 100644 --- a/src/models/components/patchproxyrequest.ts +++ b/src/models/components/patchproxyrequest.ts @@ -1,37 +1,75 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type PatchProxyRequest = { - dollarANYBODYPARAMS?: string | undefined; + dollarANYBODYPARAMS?: string | undefined; +}; + +/** @internal */ +export const PatchProxyRequest$inboundSchema: z.ZodType< + PatchProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + $ANY_BODY_PARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "$ANY_BODY_PARAMS": "dollarANYBODYPARAMS", + }); +}); + +/** @internal */ +export type PatchProxyRequest$Outbound = { + $ANY_BODY_PARAMS?: string | undefined; }; /** @internal */ +export const PatchProxyRequest$outboundSchema: z.ZodType< + PatchProxyRequest$Outbound, + z.ZodTypeDef, + PatchProxyRequest +> = z.object({ + dollarANYBODYPARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace PatchProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - $ANY_BODY_PARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - $ANY_BODY_PARAMS: "dollarANYBODYPARAMS", - }); - }); - - export type Outbound = { - $ANY_BODY_PARAMS?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - dollarANYBODYPARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", - }); - }); + /** @deprecated use `PatchProxyRequest$inboundSchema` instead. */ + export const inboundSchema = PatchProxyRequest$inboundSchema; + /** @deprecated use `PatchProxyRequest$outboundSchema` instead. */ + export const outboundSchema = PatchProxyRequest$outboundSchema; + /** @deprecated use `PatchProxyRequest$Outbound` instead. */ + export type Outbound = PatchProxyRequest$Outbound; +} + +export function patchProxyRequestToJSON( + patchProxyRequest: PatchProxyRequest, +): string { + return JSON.stringify( + PatchProxyRequest$outboundSchema.parse(patchProxyRequest), + ); +} + +export function patchProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PatchProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PatchProxyRequest' from JSON`, + ); } diff --git a/src/models/components/putproxyrequest.ts b/src/models/components/putproxyrequest.ts index 41cd49e..dadb4e3 100644 --- a/src/models/components/putproxyrequest.ts +++ b/src/models/components/putproxyrequest.ts @@ -1,37 +1,73 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type PutProxyRequest = { - dollarANYBODYPARAMS?: string | undefined; + dollarANYBODYPARAMS?: string | undefined; +}; + +/** @internal */ +export const PutProxyRequest$inboundSchema: z.ZodType< + PutProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + $ANY_BODY_PARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "$ANY_BODY_PARAMS": "dollarANYBODYPARAMS", + }); +}); + +/** @internal */ +export type PutProxyRequest$Outbound = { + $ANY_BODY_PARAMS?: string | undefined; }; /** @internal */ +export const PutProxyRequest$outboundSchema: z.ZodType< + PutProxyRequest$Outbound, + z.ZodTypeDef, + PutProxyRequest +> = z.object({ + dollarANYBODYPARAMS: z.string().optional(), +}).transform((v) => { + return remap$(v, { + dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace PutProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - $ANY_BODY_PARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - $ANY_BODY_PARAMS: "dollarANYBODYPARAMS", - }); - }); - - export type Outbound = { - $ANY_BODY_PARAMS?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - dollarANYBODYPARAMS: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - dollarANYBODYPARAMS: "$ANY_BODY_PARAMS", - }); - }); + /** @deprecated use `PutProxyRequest$inboundSchema` instead. */ + export const inboundSchema = PutProxyRequest$inboundSchema; + /** @deprecated use `PutProxyRequest$outboundSchema` instead. */ + export const outboundSchema = PutProxyRequest$outboundSchema; + /** @deprecated use `PutProxyRequest$Outbound` instead. */ + export type Outbound = PutProxyRequest$Outbound; +} + +export function putProxyRequestToJSON( + putProxyRequest: PutProxyRequest, +): string { + return JSON.stringify(PutProxyRequest$outboundSchema.parse(putProxyRequest)); +} + +export function putProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PutProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PutProxyRequest' from JSON`, + ); } diff --git a/src/models/components/updateconnectionfrequencyrequest.ts b/src/models/components/updateconnectionfrequencyrequest.ts index b159f46..8122d8a 100644 --- a/src/models/components/updateconnectionfrequencyrequest.ts +++ b/src/models/components/updateconnectionfrequencyrequest.ts @@ -1,70 +1,105 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type UpdateConnectionFrequencyRequest = { - /** - * The ID of the integration you established within Nango - */ - providerConfigKey: string; - /** - * The ID of the connection - */ - connectionId: string; - /** - * The name of the sync you want to update - */ - syncName: string; - /** - * The frequency you want to set (ex: 'every hour'). Set null to revert to the default frequency - */ - frequency: string; + /** + * The ID of the integration you established within Nango + */ + providerConfigKey: string; + /** + * The ID of the connection + */ + connectionId: string; + /** + * The name of the sync you want to update + */ + syncName: string; + /** + * The frequency you want to set (ex: 'every hour'). Set null to revert to the default frequency + */ + frequency: string; }; /** @internal */ +export const UpdateConnectionFrequencyRequest$inboundSchema: z.ZodType< + UpdateConnectionFrequencyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + provider_config_key: z.string(), + connection_id: z.string(), + sync_name: z.string(), + frequency: z.string(), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "connection_id": "connectionId", + "sync_name": "syncName", + }); +}); + +/** @internal */ +export type UpdateConnectionFrequencyRequest$Outbound = { + provider_config_key: string; + connection_id: string; + sync_name: string; + frequency: string; +}; + +/** @internal */ +export const UpdateConnectionFrequencyRequest$outboundSchema: z.ZodType< + UpdateConnectionFrequencyRequest$Outbound, + z.ZodTypeDef, + UpdateConnectionFrequencyRequest +> = z.object({ + providerConfigKey: z.string(), + connectionId: z.string(), + syncName: z.string(), + frequency: z.string(), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + connectionId: "connection_id", + syncName: "sync_name", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace UpdateConnectionFrequencyRequest$ { - export const inboundSchema: z.ZodType = - z - .object({ - provider_config_key: z.string(), - connection_id: z.string(), - sync_name: z.string(), - frequency: z.string(), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - connection_id: "connectionId", - sync_name: "syncName", - }); - }); + /** @deprecated use `UpdateConnectionFrequencyRequest$inboundSchema` instead. */ + export const inboundSchema = UpdateConnectionFrequencyRequest$inboundSchema; + /** @deprecated use `UpdateConnectionFrequencyRequest$outboundSchema` instead. */ + export const outboundSchema = UpdateConnectionFrequencyRequest$outboundSchema; + /** @deprecated use `UpdateConnectionFrequencyRequest$Outbound` instead. */ + export type Outbound = UpdateConnectionFrequencyRequest$Outbound; +} - export type Outbound = { - provider_config_key: string; - connection_id: string; - sync_name: string; - frequency: string; - }; +export function updateConnectionFrequencyRequestToJSON( + updateConnectionFrequencyRequest: UpdateConnectionFrequencyRequest, +): string { + return JSON.stringify( + UpdateConnectionFrequencyRequest$outboundSchema.parse( + updateConnectionFrequencyRequest, + ), + ); +} - export const outboundSchema: z.ZodType< - Outbound, - z.ZodTypeDef, - UpdateConnectionFrequencyRequest - > = z - .object({ - providerConfigKey: z.string(), - connectionId: z.string(), - syncName: z.string(), - frequency: z.string(), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - connectionId: "connection_id", - syncName: "sync_name", - }); - }); +export function updateConnectionFrequencyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateConnectionFrequencyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateConnectionFrequencyRequest' from JSON`, + ); } diff --git a/src/models/components/updateconnectionfrequencyresponse.ts b/src/models/components/updateconnectionfrequencyresponse.ts index 884f605..f8b2175 100644 --- a/src/models/components/updateconnectionfrequencyresponse.ts +++ b/src/models/components/updateconnectionfrequencyresponse.ts @@ -1,35 +1,72 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type UpdateConnectionFrequencyResponse = { - /** - * The updated frequency value - */ - frequency?: string | undefined; + /** + * The updated frequency value + */ + frequency?: string | undefined; }; /** @internal */ +export const UpdateConnectionFrequencyResponse$inboundSchema: z.ZodType< + UpdateConnectionFrequencyResponse, + z.ZodTypeDef, + unknown +> = z.object({ + frequency: z.string().optional(), +}); + +/** @internal */ +export type UpdateConnectionFrequencyResponse$Outbound = { + frequency?: string | undefined; +}; + +/** @internal */ +export const UpdateConnectionFrequencyResponse$outboundSchema: z.ZodType< + UpdateConnectionFrequencyResponse$Outbound, + z.ZodTypeDef, + UpdateConnectionFrequencyResponse +> = z.object({ + frequency: 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 UpdateConnectionFrequencyResponse$ { - export const inboundSchema: z.ZodType< - UpdateConnectionFrequencyResponse, - z.ZodTypeDef, - unknown - > = z.object({ - frequency: z.string().optional(), - }); - - export type Outbound = { - frequency?: string | undefined; - }; - - export const outboundSchema: z.ZodType< - Outbound, - z.ZodTypeDef, - UpdateConnectionFrequencyResponse - > = z.object({ - frequency: z.string().optional(), - }); + /** @deprecated use `UpdateConnectionFrequencyResponse$inboundSchema` instead. */ + export const inboundSchema = UpdateConnectionFrequencyResponse$inboundSchema; + /** @deprecated use `UpdateConnectionFrequencyResponse$outboundSchema` instead. */ + export const outboundSchema = + UpdateConnectionFrequencyResponse$outboundSchema; + /** @deprecated use `UpdateConnectionFrequencyResponse$Outbound` instead. */ + export type Outbound = UpdateConnectionFrequencyResponse$Outbound; +} + +export function updateConnectionFrequencyResponseToJSON( + updateConnectionFrequencyResponse: UpdateConnectionFrequencyResponse, +): string { + return JSON.stringify( + UpdateConnectionFrequencyResponse$outboundSchema.parse( + updateConnectionFrequencyResponse, + ), + ); +} + +export function updateConnectionFrequencyResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateConnectionFrequencyResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateConnectionFrequencyResponse' from JSON`, + ); } diff --git a/src/models/components/updateintegrationrequest.ts b/src/models/components/updateintegrationrequest.ts index 9eef4e7..d5bdd96 100644 --- a/src/models/components/updateintegrationrequest.ts +++ b/src/models/components/updateintegrationrequest.ts @@ -1,18 +1,58 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type UpdateIntegrationRequest = {}; /** @internal */ +export const UpdateIntegrationRequest$inboundSchema: z.ZodType< + UpdateIntegrationRequest, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type UpdateIntegrationRequest$Outbound = {}; + +/** @internal */ +export const UpdateIntegrationRequest$outboundSchema: z.ZodType< + UpdateIntegrationRequest$Outbound, + z.ZodTypeDef, + UpdateIntegrationRequest +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace UpdateIntegrationRequest$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `UpdateIntegrationRequest$inboundSchema` instead. */ + export const inboundSchema = UpdateIntegrationRequest$inboundSchema; + /** @deprecated use `UpdateIntegrationRequest$outboundSchema` instead. */ + export const outboundSchema = UpdateIntegrationRequest$outboundSchema; + /** @deprecated use `UpdateIntegrationRequest$Outbound` instead. */ + export type Outbound = UpdateIntegrationRequest$Outbound; +} - export type Outbound = {}; +export function updateIntegrationRequestToJSON( + updateIntegrationRequest: UpdateIntegrationRequest, +): string { + return JSON.stringify( + UpdateIntegrationRequest$outboundSchema.parse(updateIntegrationRequest), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function updateIntegrationRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateIntegrationRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateIntegrationRequest' from JSON`, + ); } diff --git a/src/models/errors/httpclienterrors.ts b/src/models/errors/httpclienterrors.ts new file mode 100644 index 0000000..b34f612 --- /dev/null +++ b/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/src/models/errors/index.ts b/src/models/errors/index.ts index 193fc7c..3be5bb7 100644 --- a/src/models/errors/index.ts +++ b/src/models/errors/index.ts @@ -1,7 +1,8 @@ /* - * 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 "./response400.js"; export * from "./response404.js"; export * from "./sdkerror.js"; diff --git a/src/models/errors/response400.ts b/src/models/errors/response400.ts index cc60531..166faba 100644 --- a/src/models/errors/response400.ts +++ b/src/models/errors/response400.ts @@ -1,56 +1,65 @@ /* - * 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"; -/** - * Invalid request - */ export type Response400Data = { - message?: string | undefined; + message?: string | undefined; }; -/** - * Invalid request - */ export class Response400 extends Error { - /** The original data that was passed to this error instance. */ - data$: Response400Data; + /** The original data that was passed to this error instance. */ + data$: Response400Data; - constructor(err: Response400Data) { - super(""); - this.data$ = err; + constructor(err: Response400Data) { + const message = "message" in err && typeof err.message === "string" + ? err.message + : `API error occurred: ${JSON.stringify(err)}`; + super(message); + this.data$ = err; - this.message = - "message" in err && typeof err.message === "string" - ? err.message - : "API error occurred"; - - this.name = "Response400"; - } + this.name = "Response400"; + } } /** @internal */ +export const Response400$inboundSchema: z.ZodType< + Response400, + z.ZodTypeDef, + unknown +> = z.object({ + message: z.string().optional(), +}) + .transform((v) => { + return new Response400(v); + }); + +/** @internal */ +export type Response400$Outbound = { + message?: string | undefined; +}; + +/** @internal */ +export const Response400$outboundSchema: z.ZodType< + Response400$Outbound, + z.ZodTypeDef, + Response400 +> = z.instanceof(Response400) + .transform(v => v.data$) + .pipe(z.object({ + message: 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 Response400$ { - export const inboundSchema: z.ZodType = z - .object({ - message: z.string().optional(), - }) - .transform((v) => { - return new Response400(v); - }); - - export type Outbound = { - message?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .instanceof(Response400) - .transform((v) => v.data$) - .pipe( - z.object({ - message: z.string().optional(), - }) - ); + /** @deprecated use `Response400$inboundSchema` instead. */ + export const inboundSchema = Response400$inboundSchema; + /** @deprecated use `Response400$outboundSchema` instead. */ + export const outboundSchema = Response400$outboundSchema; + /** @deprecated use `Response400$Outbound` instead. */ + export type Outbound = Response400$Outbound; } diff --git a/src/models/errors/response404.ts b/src/models/errors/response404.ts index 477621c..eccbac6 100644 --- a/src/models/errors/response404.ts +++ b/src/models/errors/response404.ts @@ -1,56 +1,65 @@ /* - * 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"; -/** - * Unknown integration - */ export type Response404Data = { - message?: string | undefined; + message?: string | undefined; }; -/** - * Unknown integration - */ export class Response404 extends Error { - /** The original data that was passed to this error instance. */ - data$: Response404Data; + /** The original data that was passed to this error instance. */ + data$: Response404Data; - constructor(err: Response404Data) { - super(""); - this.data$ = err; + constructor(err: Response404Data) { + const message = "message" in err && typeof err.message === "string" + ? err.message + : `API error occurred: ${JSON.stringify(err)}`; + super(message); + this.data$ = err; - this.message = - "message" in err && typeof err.message === "string" - ? err.message - : "API error occurred"; - - this.name = "Response404"; - } + this.name = "Response404"; + } } /** @internal */ +export const Response404$inboundSchema: z.ZodType< + Response404, + z.ZodTypeDef, + unknown +> = z.object({ + message: z.string().optional(), +}) + .transform((v) => { + return new Response404(v); + }); + +/** @internal */ +export type Response404$Outbound = { + message?: string | undefined; +}; + +/** @internal */ +export const Response404$outboundSchema: z.ZodType< + Response404$Outbound, + z.ZodTypeDef, + Response404 +> = z.instanceof(Response404) + .transform(v => v.data$) + .pipe(z.object({ + message: 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 Response404$ { - export const inboundSchema: z.ZodType = z - .object({ - message: z.string().optional(), - }) - .transform((v) => { - return new Response404(v); - }); - - export type Outbound = { - message?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .instanceof(Response404) - .transform((v) => v.data$) - .pipe( - z.object({ - message: z.string().optional(), - }) - ); + /** @deprecated use `Response404$inboundSchema` instead. */ + export const inboundSchema = Response404$inboundSchema; + /** @deprecated use `Response404$outboundSchema` instead. */ + export const outboundSchema = Response404$outboundSchema; + /** @deprecated use `Response404$Outbound` instead. */ + export type Outbound = Response404$Outbound; } diff --git a/src/models/errors/sdkerror.ts b/src/models/errors/sdkerror.ts index 5a94e84..001f465 100644 --- a/src/models/errors/sdkerror.ts +++ b/src/models/errors/sdkerror.ts @@ -1,25 +1,27 @@ /* - * 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 { - public readonly statusCode: number; - public readonly contentType: string; + public readonly statusCode: number; + public readonly contentType: string; - constructor( - message: string, - public readonly rawResponse: Response, - public readonly body: string = "" - ) { - const statusCode = rawResponse.status; - const contentType = rawResponse.headers.get("content-type") || ""; - const bodyString = body.length > 0 ? `\n${body}` : ""; + constructor( + message: string, + public readonly rawResponse: Response, + public readonly body: string = "", + ) { + const statusCode = rawResponse.status; + const contentType = rawResponse.headers.get("content-type") || ""; + const bodyString = body.length > 0 ? `\n${body}` : ""; - super(`${message}: Status ${statusCode} Content-Type ${contentType} Body ${bodyString}`); + super( + `${message}: Status ${statusCode} Content-Type ${contentType} Body ${bodyString}`, + ); - this.statusCode = statusCode; - this.contentType = contentType; + this.statusCode = statusCode; + this.contentType = contentType; - this.name = "SDKError"; - } + this.name = "SDKError"; + } } diff --git a/src/models/errors/sdkvalidationerror.ts b/src/models/errors/sdkvalidationerror.ts index 5eb9218..16929b9 100644 --- a/src/models/errors/sdkvalidationerror.ts +++ b/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/src/models/operations/createactiontrigger.ts b/src/models/operations/createactiontrigger.ts index 2469c21..e98b18e 100644 --- a/src/models/operations/createactiontrigger.ts +++ b/src/models/operations/createactiontrigger.ts @@ -1,56 +1,96 @@ /* - * 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"; import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; import * as components from "../components/index.js"; -import * as z from "zod"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateActionTriggerRequest = { - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - createActionTriggerRequest: components.CreateActionTriggerRequest; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + createActionTriggerRequest: components.CreateActionTriggerRequest; +}; + +/** @internal */ +export const CreateActionTriggerRequest$inboundSchema: z.ZodType< + CreateActionTriggerRequest, + z.ZodTypeDef, + unknown +> = z.object({ + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + CreateActionTriggerRequest: + components.CreateActionTriggerRequest$inboundSchema, +}).transform((v) => { + return remap$(v, { + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "CreateActionTriggerRequest": "createActionTriggerRequest", + }); +}); + +/** @internal */ +export type CreateActionTriggerRequest$Outbound = { + "Connection-Id": string; + "Provider-Config-Key": string; + CreateActionTriggerRequest: components.CreateActionTriggerRequest$Outbound; }; /** @internal */ +export const CreateActionTriggerRequest$outboundSchema: z.ZodType< + CreateActionTriggerRequest$Outbound, + z.ZodTypeDef, + CreateActionTriggerRequest +> = z.object({ + connectionId: z.string(), + providerConfigKey: z.string(), + createActionTriggerRequest: + components.CreateActionTriggerRequest$outboundSchema, +}).transform((v) => { + return remap$(v, { + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + createActionTriggerRequest: "CreateActionTriggerRequest", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateActionTriggerRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - CreateActionTriggerRequest: components.CreateActionTriggerRequest$.inboundSchema, - }) - .transform((v) => { - return remap$(v, { - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - CreateActionTriggerRequest: "createActionTriggerRequest", - }); - }); - - export type Outbound = { - "Connection-Id": string; - "Provider-Config-Key": string; - CreateActionTriggerRequest: components.CreateActionTriggerRequest$.Outbound; - }; - - export const outboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - providerConfigKey: z.string(), - createActionTriggerRequest: components.CreateActionTriggerRequest$.outboundSchema, - }) - .transform((v) => { - return remap$(v, { - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - createActionTriggerRequest: "CreateActionTriggerRequest", - }); - }); + /** @deprecated use `CreateActionTriggerRequest$inboundSchema` instead. */ + export const inboundSchema = CreateActionTriggerRequest$inboundSchema; + /** @deprecated use `CreateActionTriggerRequest$outboundSchema` instead. */ + export const outboundSchema = CreateActionTriggerRequest$outboundSchema; + /** @deprecated use `CreateActionTriggerRequest$Outbound` instead. */ + export type Outbound = CreateActionTriggerRequest$Outbound; +} + +export function createActionTriggerRequestToJSON( + createActionTriggerRequest: CreateActionTriggerRequest, +): string { + return JSON.stringify( + CreateActionTriggerRequest$outboundSchema.parse(createActionTriggerRequest), + ); +} + +export function createActionTriggerRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateActionTriggerRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateActionTriggerRequest' from JSON`, + ); } diff --git a/src/models/operations/createmetadata.ts b/src/models/operations/createmetadata.ts index 4320ac9..1102913 100644 --- a/src/models/operations/createmetadata.ts +++ b/src/models/operations/createmetadata.ts @@ -1,66 +1,141 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateMetadataRequestBody = {}; export type CreateMetadataRequest = { - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - requestBody: CreateMetadataRequestBody; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + requestBody: CreateMetadataRequestBody; }; /** @internal */ +export const CreateMetadataRequestBody$inboundSchema: z.ZodType< + CreateMetadataRequestBody, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type CreateMetadataRequestBody$Outbound = {}; + +/** @internal */ +export const CreateMetadataRequestBody$outboundSchema: z.ZodType< + CreateMetadataRequestBody$Outbound, + z.ZodTypeDef, + CreateMetadataRequestBody +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateMetadataRequestBody$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `CreateMetadataRequestBody$inboundSchema` instead. */ + export const inboundSchema = CreateMetadataRequestBody$inboundSchema; + /** @deprecated use `CreateMetadataRequestBody$outboundSchema` instead. */ + export const outboundSchema = CreateMetadataRequestBody$outboundSchema; + /** @deprecated use `CreateMetadataRequestBody$Outbound` instead. */ + export type Outbound = CreateMetadataRequestBody$Outbound; +} - export type Outbound = {}; +export function createMetadataRequestBodyToJSON( + createMetadataRequestBody: CreateMetadataRequestBody, +): string { + return JSON.stringify( + CreateMetadataRequestBody$outboundSchema.parse(createMetadataRequestBody), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function createMetadataRequestBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateMetadataRequestBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateMetadataRequestBody' from JSON`, + ); } /** @internal */ +export const CreateMetadataRequest$inboundSchema: z.ZodType< + CreateMetadataRequest, + z.ZodTypeDef, + unknown +> = z.object({ + connectionId: z.string(), + "Provider-Config-Key": z.string(), + RequestBody: z.lazy(() => CreateMetadataRequestBody$inboundSchema), +}).transform((v) => { + return remap$(v, { + "Provider-Config-Key": "providerConfigKey", + "RequestBody": "requestBody", + }); +}); + +/** @internal */ +export type CreateMetadataRequest$Outbound = { + connectionId: string; + "Provider-Config-Key": string; + RequestBody: CreateMetadataRequestBody$Outbound; +}; + +/** @internal */ +export const CreateMetadataRequest$outboundSchema: z.ZodType< + CreateMetadataRequest$Outbound, + z.ZodTypeDef, + CreateMetadataRequest +> = z.object({ + connectionId: z.string(), + providerConfigKey: z.string(), + requestBody: z.lazy(() => CreateMetadataRequestBody$outboundSchema), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "Provider-Config-Key", + requestBody: "RequestBody", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateMetadataRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - "Provider-Config-Key": z.string(), - RequestBody: z.lazy(() => CreateMetadataRequestBody$.inboundSchema), - }) - .transform((v) => { - return remap$(v, { - "Provider-Config-Key": "providerConfigKey", - RequestBody: "requestBody", - }); - }); + /** @deprecated use `CreateMetadataRequest$inboundSchema` instead. */ + export const inboundSchema = CreateMetadataRequest$inboundSchema; + /** @deprecated use `CreateMetadataRequest$outboundSchema` instead. */ + export const outboundSchema = CreateMetadataRequest$outboundSchema; + /** @deprecated use `CreateMetadataRequest$Outbound` instead. */ + export type Outbound = CreateMetadataRequest$Outbound; +} - export type Outbound = { - connectionId: string; - "Provider-Config-Key": string; - RequestBody: CreateMetadataRequestBody$.Outbound; - }; +export function createMetadataRequestToJSON( + createMetadataRequest: CreateMetadataRequest, +): string { + return JSON.stringify( + CreateMetadataRequest$outboundSchema.parse(createMetadataRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - providerConfigKey: z.string(), - requestBody: z.lazy(() => CreateMetadataRequestBody$.outboundSchema), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "Provider-Config-Key", - requestBody: "RequestBody", - }); - }); +export function createMetadataRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateMetadataRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateMetadataRequest' from JSON`, + ); } diff --git a/src/models/operations/createproxy.ts b/src/models/operations/createproxy.ts index 839763c..1849133 100644 --- a/src/models/operations/createproxy.ts +++ b/src/models/operations/createproxy.ts @@ -1,96 +1,134 @@ /* - * 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"; import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; import * as components from "../components/index.js"; -import * as z from "zod"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type CreateProxyRequest = { - anyPath: string; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * The number of retries in case of failure (with exponential back-off). Optional, default 0. - */ - retries?: string | undefined; - /** - * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional - */ - baseUrlOverride?: string | undefined; - /** - * Override the decompress option when making requests. Optional, defaults to false - */ - decompress?: string | undefined; - /** - * Any other headers you send are passed on to the external API - */ - nangoProxyDollarANYHEADER?: string | undefined; - createProxyRequest?: components.CreateProxyRequest | undefined; + anyPath: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * The number of retries in case of failure (with exponential back-off). Optional, default 0. + */ + retries?: string | undefined; + /** + * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional + */ + baseUrlOverride?: string | undefined; + /** + * Override the decompress option when making requests. Optional, defaults to false + */ + decompress?: string | undefined; + /** + * Any other headers you send are passed on to the external API + */ + nangoProxyDollarANYHEADER?: string | undefined; + createProxyRequest?: components.CreateProxyRequest | undefined; }; /** @internal */ +export const CreateProxyRequest$inboundSchema: z.ZodType< + CreateProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + anyPath: z.string(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + Retries: z.string().optional(), + "Base-Url-Override": z.string().optional(), + Decompress: z.string().optional(), + "nango-proxy-$ANY_HEADER": z.string().optional(), + CreateProxyRequest: components.CreateProxyRequest$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "Retries": "retries", + "Base-Url-Override": "baseUrlOverride", + "Decompress": "decompress", + "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", + "CreateProxyRequest": "createProxyRequest", + }); +}); + +/** @internal */ +export type CreateProxyRequest$Outbound = { + anyPath: string; + "Connection-Id": string; + "Provider-Config-Key": string; + Retries?: string | undefined; + "Base-Url-Override"?: string | undefined; + Decompress?: string | undefined; + "nango-proxy-$ANY_HEADER"?: string | undefined; + CreateProxyRequest?: components.CreateProxyRequest$Outbound | undefined; +}; + +/** @internal */ +export const CreateProxyRequest$outboundSchema: z.ZodType< + CreateProxyRequest$Outbound, + z.ZodTypeDef, + CreateProxyRequest +> = z.object({ + anyPath: z.string(), + connectionId: z.string(), + providerConfigKey: z.string(), + retries: z.string().optional(), + baseUrlOverride: z.string().optional(), + decompress: z.string().optional(), + nangoProxyDollarANYHEADER: z.string().optional(), + createProxyRequest: components.CreateProxyRequest$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + retries: "Retries", + baseUrlOverride: "Base-Url-Override", + decompress: "Decompress", + nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", + createProxyRequest: "CreateProxyRequest", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace CreateProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - Retries: z.string().optional(), - "Base-Url-Override": z.string().optional(), - Decompress: z.string().optional(), - "nango-proxy-$ANY_HEADER": z.string().optional(), - CreateProxyRequest: components.CreateProxyRequest$.inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - Retries: "retries", - "Base-Url-Override": "baseUrlOverride", - Decompress: "decompress", - "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", - CreateProxyRequest: "createProxyRequest", - }); - }); + /** @deprecated use `CreateProxyRequest$inboundSchema` instead. */ + export const inboundSchema = CreateProxyRequest$inboundSchema; + /** @deprecated use `CreateProxyRequest$outboundSchema` instead. */ + export const outboundSchema = CreateProxyRequest$outboundSchema; + /** @deprecated use `CreateProxyRequest$Outbound` instead. */ + export type Outbound = CreateProxyRequest$Outbound; +} - export type Outbound = { - anyPath: string; - "Connection-Id": string; - "Provider-Config-Key": string; - Retries?: string | undefined; - "Base-Url-Override"?: string | undefined; - Decompress?: string | undefined; - "nango-proxy-$ANY_HEADER"?: string | undefined; - CreateProxyRequest?: components.CreateProxyRequest$.Outbound | undefined; - }; +export function createProxyRequestToJSON( + createProxyRequest: CreateProxyRequest, +): string { + return JSON.stringify( + CreateProxyRequest$outboundSchema.parse(createProxyRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - connectionId: z.string(), - providerConfigKey: z.string(), - retries: z.string().optional(), - baseUrlOverride: z.string().optional(), - decompress: z.string().optional(), - nangoProxyDollarANYHEADER: z.string().optional(), - createProxyRequest: components.CreateProxyRequest$.outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - retries: "Retries", - baseUrlOverride: "Base-Url-Override", - decompress: "Decompress", - nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", - createProxyRequest: "CreateProxyRequest", - }); - }); +export function createProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateProxyRequest' from JSON`, + ); } diff --git a/src/models/operations/deleteconnections.ts b/src/models/operations/deleteconnections.ts index e35a98f..ce0e323 100644 --- a/src/models/operations/deleteconnections.ts +++ b/src/models/operations/deleteconnections.ts @@ -1,47 +1,85 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type DeleteConnectionsRequest = { - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; +}; + +/** @internal */ +export const DeleteConnectionsRequest$inboundSchema: z.ZodType< + DeleteConnectionsRequest, + z.ZodTypeDef, + unknown +> = z.object({ + connectionId: z.string(), + provider_config_key: z.string(), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + }); +}); + +/** @internal */ +export type DeleteConnectionsRequest$Outbound = { + connectionId: string; + provider_config_key: string; }; /** @internal */ +export const DeleteConnectionsRequest$outboundSchema: z.ZodType< + DeleteConnectionsRequest$Outbound, + z.ZodTypeDef, + DeleteConnectionsRequest +> = z.object({ + connectionId: z.string(), + providerConfigKey: z.string(), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace DeleteConnectionsRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - provider_config_key: z.string(), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - }); - }); - - export type Outbound = { - connectionId: string; - provider_config_key: string; - }; - - export const outboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - providerConfigKey: z.string(), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - }); - }); + /** @deprecated use `DeleteConnectionsRequest$inboundSchema` instead. */ + export const inboundSchema = DeleteConnectionsRequest$inboundSchema; + /** @deprecated use `DeleteConnectionsRequest$outboundSchema` instead. */ + export const outboundSchema = DeleteConnectionsRequest$outboundSchema; + /** @deprecated use `DeleteConnectionsRequest$Outbound` instead. */ + export type Outbound = DeleteConnectionsRequest$Outbound; +} + +export function deleteConnectionsRequestToJSON( + deleteConnectionsRequest: DeleteConnectionsRequest, +): string { + return JSON.stringify( + DeleteConnectionsRequest$outboundSchema.parse(deleteConnectionsRequest), + ); +} + +export function deleteConnectionsRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => DeleteConnectionsRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'DeleteConnectionsRequest' from JSON`, + ); } diff --git a/src/models/operations/deleteintegration.ts b/src/models/operations/deleteintegration.ts index 08705a5..8c89ea3 100644 --- a/src/models/operations/deleteintegration.ts +++ b/src/models/operations/deleteintegration.ts @@ -1,29 +1,69 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type DeleteIntegrationRequest = { - /** - * The integration ID that you created in Nango. - */ - providerConfigKey: string; + /** + * The integration ID that you created in Nango. + */ + providerConfigKey: string; }; /** @internal */ +export const DeleteIntegrationRequest$inboundSchema: z.ZodType< + DeleteIntegrationRequest, + z.ZodTypeDef, + unknown +> = z.object({ + providerConfigKey: z.string(), +}); + +/** @internal */ +export type DeleteIntegrationRequest$Outbound = { + providerConfigKey: string; +}; + +/** @internal */ +export const DeleteIntegrationRequest$outboundSchema: z.ZodType< + DeleteIntegrationRequest$Outbound, + z.ZodTypeDef, + DeleteIntegrationRequest +> = z.object({ + providerConfigKey: 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 DeleteIntegrationRequest$ { - export const inboundSchema: z.ZodType = - z.object({ - providerConfigKey: z.string(), - }); - - export type Outbound = { - providerConfigKey: string; - }; - - export const outboundSchema: z.ZodType = - z.object({ - providerConfigKey: z.string(), - }); + /** @deprecated use `DeleteIntegrationRequest$inboundSchema` instead. */ + export const inboundSchema = DeleteIntegrationRequest$inboundSchema; + /** @deprecated use `DeleteIntegrationRequest$outboundSchema` instead. */ + export const outboundSchema = DeleteIntegrationRequest$outboundSchema; + /** @deprecated use `DeleteIntegrationRequest$Outbound` instead. */ + export type Outbound = DeleteIntegrationRequest$Outbound; +} + +export function deleteIntegrationRequestToJSON( + deleteIntegrationRequest: DeleteIntegrationRequest, +): string { + return JSON.stringify( + DeleteIntegrationRequest$outboundSchema.parse(deleteIntegrationRequest), + ); +} + +export function deleteIntegrationRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => DeleteIntegrationRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'DeleteIntegrationRequest' from JSON`, + ); } diff --git a/src/models/operations/deleteproxy.ts b/src/models/operations/deleteproxy.ts index e4fc7ae..e912768 100644 --- a/src/models/operations/deleteproxy.ts +++ b/src/models/operations/deleteproxy.ts @@ -1,95 +1,133 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type DeleteProxyRequest = { - anyPath: string; - dollarANYQUERYPARAMS: string; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * The number of retries in case of failure (with exponential back-off). Optional, default 0. - */ - retries?: string | undefined; - /** - * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional - */ - baseUrlOverride?: string | undefined; - /** - * Override the decompress option when making requests. Optional, defaults to false - */ - decompress?: string | undefined; - /** - * Any other headers you send are passed on to the external API - */ - nangoProxyDollarANYHEADER?: string | undefined; + anyPath: string; + dollarANYQUERYPARAMS: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * The number of retries in case of failure (with exponential back-off). Optional, default 0. + */ + retries?: string | undefined; + /** + * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional + */ + baseUrlOverride?: string | undefined; + /** + * Override the decompress option when making requests. Optional, defaults to false + */ + decompress?: string | undefined; + /** + * Any other headers you send are passed on to the external API + */ + nangoProxyDollarANYHEADER?: string | undefined; }; /** @internal */ +export const DeleteProxyRequest$inboundSchema: z.ZodType< + DeleteProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + anyPath: z.string(), + $ANY_QUERY_PARAMS: z.string(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + Retries: z.string().optional(), + "Base-Url-Override": z.string().optional(), + Decompress: z.string().optional(), + "nango-proxy-$ANY_HEADER": z.string().optional(), +}).transform((v) => { + return remap$(v, { + "$ANY_QUERY_PARAMS": "dollarANYQUERYPARAMS", + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "Retries": "retries", + "Base-Url-Override": "baseUrlOverride", + "Decompress": "decompress", + "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", + }); +}); + +/** @internal */ +export type DeleteProxyRequest$Outbound = { + anyPath: string; + $ANY_QUERY_PARAMS: string; + "Connection-Id": string; + "Provider-Config-Key": string; + Retries?: string | undefined; + "Base-Url-Override"?: string | undefined; + Decompress?: string | undefined; + "nango-proxy-$ANY_HEADER"?: string | undefined; +}; + +/** @internal */ +export const DeleteProxyRequest$outboundSchema: z.ZodType< + DeleteProxyRequest$Outbound, + z.ZodTypeDef, + DeleteProxyRequest +> = z.object({ + anyPath: z.string(), + dollarANYQUERYPARAMS: z.string(), + connectionId: z.string(), + providerConfigKey: z.string(), + retries: z.string().optional(), + baseUrlOverride: z.string().optional(), + decompress: z.string().optional(), + nangoProxyDollarANYHEADER: z.string().optional(), +}).transform((v) => { + return remap$(v, { + dollarANYQUERYPARAMS: "$ANY_QUERY_PARAMS", + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + retries: "Retries", + baseUrlOverride: "Base-Url-Override", + decompress: "Decompress", + nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace DeleteProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - $ANY_QUERY_PARAMS: z.string(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - Retries: z.string().optional(), - "Base-Url-Override": z.string().optional(), - Decompress: z.string().optional(), - "nango-proxy-$ANY_HEADER": z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - $ANY_QUERY_PARAMS: "dollarANYQUERYPARAMS", - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - Retries: "retries", - "Base-Url-Override": "baseUrlOverride", - Decompress: "decompress", - "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", - }); - }); + /** @deprecated use `DeleteProxyRequest$inboundSchema` instead. */ + export const inboundSchema = DeleteProxyRequest$inboundSchema; + /** @deprecated use `DeleteProxyRequest$outboundSchema` instead. */ + export const outboundSchema = DeleteProxyRequest$outboundSchema; + /** @deprecated use `DeleteProxyRequest$Outbound` instead. */ + export type Outbound = DeleteProxyRequest$Outbound; +} - export type Outbound = { - anyPath: string; - $ANY_QUERY_PARAMS: string; - "Connection-Id": string; - "Provider-Config-Key": string; - Retries?: string | undefined; - "Base-Url-Override"?: string | undefined; - Decompress?: string | undefined; - "nango-proxy-$ANY_HEADER"?: string | undefined; - }; +export function deleteProxyRequestToJSON( + deleteProxyRequest: DeleteProxyRequest, +): string { + return JSON.stringify( + DeleteProxyRequest$outboundSchema.parse(deleteProxyRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - dollarANYQUERYPARAMS: z.string(), - connectionId: z.string(), - providerConfigKey: z.string(), - retries: z.string().optional(), - baseUrlOverride: z.string().optional(), - decompress: z.string().optional(), - nangoProxyDollarANYHEADER: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - dollarANYQUERYPARAMS: "$ANY_QUERY_PARAMS", - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - retries: "Retries", - baseUrlOverride: "Base-Url-Override", - decompress: "Decompress", - nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", - }); - }); +export function deleteProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => DeleteProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'DeleteProxyRequest' from JSON`, + ); } diff --git a/src/models/operations/getconnections.ts b/src/models/operations/getconnections.ts index ff62c6e..c2dc74e 100644 --- a/src/models/operations/getconnections.ts +++ b/src/models/operations/getconnections.ts @@ -1,65 +1,103 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetConnectionsRequest = { - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * If true, Nango will attempt to refresh the access access token regardless of its expiration status (false by default). - */ - forceRefresh?: boolean | undefined; - /** - * If true, return the refresh token as part of the response (false by default). - */ - refreshToken?: boolean | undefined; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * If true, Nango will attempt to refresh the access access token regardless of its expiration status (false by default). + */ + forceRefresh?: boolean | undefined; + /** + * If true, return the refresh token as part of the response (false by default). + */ + refreshToken?: boolean | undefined; }; /** @internal */ +export const GetConnectionsRequest$inboundSchema: z.ZodType< + GetConnectionsRequest, + z.ZodTypeDef, + unknown +> = z.object({ + connectionId: z.string(), + provider_config_key: z.string(), + force_refresh: z.boolean().optional(), + refresh_token: z.boolean().optional(), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "force_refresh": "forceRefresh", + "refresh_token": "refreshToken", + }); +}); + +/** @internal */ +export type GetConnectionsRequest$Outbound = { + connectionId: string; + provider_config_key: string; + force_refresh?: boolean | undefined; + refresh_token?: boolean | undefined; +}; + +/** @internal */ +export const GetConnectionsRequest$outboundSchema: z.ZodType< + GetConnectionsRequest$Outbound, + z.ZodTypeDef, + GetConnectionsRequest +> = z.object({ + connectionId: z.string(), + providerConfigKey: z.string(), + forceRefresh: z.boolean().optional(), + refreshToken: z.boolean().optional(), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + forceRefresh: "force_refresh", + refreshToken: "refresh_token", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetConnectionsRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - provider_config_key: z.string(), - force_refresh: z.boolean().optional(), - refresh_token: z.boolean().optional(), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - force_refresh: "forceRefresh", - refresh_token: "refreshToken", - }); - }); + /** @deprecated use `GetConnectionsRequest$inboundSchema` instead. */ + export const inboundSchema = GetConnectionsRequest$inboundSchema; + /** @deprecated use `GetConnectionsRequest$outboundSchema` instead. */ + export const outboundSchema = GetConnectionsRequest$outboundSchema; + /** @deprecated use `GetConnectionsRequest$Outbound` instead. */ + export type Outbound = GetConnectionsRequest$Outbound; +} - export type Outbound = { - connectionId: string; - provider_config_key: string; - force_refresh?: boolean | undefined; - refresh_token?: boolean | undefined; - }; +export function getConnectionsRequestToJSON( + getConnectionsRequest: GetConnectionsRequest, +): string { + return JSON.stringify( + GetConnectionsRequest$outboundSchema.parse(getConnectionsRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - providerConfigKey: z.string(), - forceRefresh: z.boolean().optional(), - refreshToken: z.boolean().optional(), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - forceRefresh: "force_refresh", - refreshToken: "refresh_token", - }); - }); +export function getConnectionsRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetConnectionsRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetConnectionsRequest' from JSON`, + ); } diff --git a/src/models/operations/getintegration.ts b/src/models/operations/getintegration.ts index 5df4f23..2156d4f 100644 --- a/src/models/operations/getintegration.ts +++ b/src/models/operations/getintegration.ts @@ -1,47 +1,85 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetIntegrationRequest = { - /** - * The integration ID that you created in Nango. - */ - providerConfigKey: string; - /** - * If true, the response will contain the client ID, secret, scopes, auth_mode and app link - if applicable. include_creds is false by default. - */ - includeCreds?: boolean | undefined; + /** + * The integration ID that you created in Nango. + */ + providerConfigKey: string; + /** + * If true, the response will contain the client ID, secret, scopes, auth_mode and app link - if applicable. include_creds is false by default. + */ + includeCreds?: boolean | undefined; +}; + +/** @internal */ +export const GetIntegrationRequest$inboundSchema: z.ZodType< + GetIntegrationRequest, + z.ZodTypeDef, + unknown +> = z.object({ + providerConfigKey: z.string(), + include_creds: z.boolean().optional(), +}).transform((v) => { + return remap$(v, { + "include_creds": "includeCreds", + }); +}); + +/** @internal */ +export type GetIntegrationRequest$Outbound = { + providerConfigKey: string; + include_creds?: boolean | undefined; }; /** @internal */ +export const GetIntegrationRequest$outboundSchema: z.ZodType< + GetIntegrationRequest$Outbound, + z.ZodTypeDef, + GetIntegrationRequest +> = z.object({ + providerConfigKey: z.string(), + includeCreds: z.boolean().optional(), +}).transform((v) => { + return remap$(v, { + includeCreds: "include_creds", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetIntegrationRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - include_creds: z.boolean().optional(), - }) - .transform((v) => { - return remap$(v, { - include_creds: "includeCreds", - }); - }); - - export type Outbound = { - providerConfigKey: string; - include_creds?: boolean | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - includeCreds: z.boolean().optional(), - }) - .transform((v) => { - return remap$(v, { - includeCreds: "include_creds", - }); - }); + /** @deprecated use `GetIntegrationRequest$inboundSchema` instead. */ + export const inboundSchema = GetIntegrationRequest$inboundSchema; + /** @deprecated use `GetIntegrationRequest$outboundSchema` instead. */ + export const outboundSchema = GetIntegrationRequest$outboundSchema; + /** @deprecated use `GetIntegrationRequest$Outbound` instead. */ + export type Outbound = GetIntegrationRequest$Outbound; +} + +export function getIntegrationRequestToJSON( + getIntegrationRequest: GetIntegrationRequest, +): string { + return JSON.stringify( + GetIntegrationRequest$outboundSchema.parse(getIntegrationRequest), + ); +} + +export function getIntegrationRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetIntegrationRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetIntegrationRequest' from JSON`, + ); } diff --git a/src/models/operations/getproxy.ts b/src/models/operations/getproxy.ts index bc9e381..01cd5df 100644 --- a/src/models/operations/getproxy.ts +++ b/src/models/operations/getproxy.ts @@ -1,95 +1,131 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetProxyRequest = { - anyPath: string; - dollarANYQUERYPARAMS: string; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * The number of retries in case of failure (with exponential back-off). Optional, default 0. - */ - retries?: string | undefined; - /** - * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional - */ - baseUrlOverride?: string | undefined; - /** - * Override the decompress option when making requests. Optional, defaults to false - */ - decompress?: string | undefined; - /** - * Any other headers you send are passed on to the external API - */ - nangoProxyDollarANYHEADER?: string | undefined; + anyPath: string; + dollarANYQUERYPARAMS: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * The number of retries in case of failure (with exponential back-off). Optional, default 0. + */ + retries?: string | undefined; + /** + * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional + */ + baseUrlOverride?: string | undefined; + /** + * Override the decompress option when making requests. Optional, defaults to false + */ + decompress?: string | undefined; + /** + * Any other headers you send are passed on to the external API + */ + nangoProxyDollarANYHEADER?: string | undefined; }; /** @internal */ +export const GetProxyRequest$inboundSchema: z.ZodType< + GetProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + anyPath: z.string(), + $ANY_QUERY_PARAMS: z.string(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + Retries: z.string().optional(), + "Base-Url-Override": z.string().optional(), + Decompress: z.string().optional(), + "nango-proxy-$ANY_HEADER": z.string().optional(), +}).transform((v) => { + return remap$(v, { + "$ANY_QUERY_PARAMS": "dollarANYQUERYPARAMS", + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "Retries": "retries", + "Base-Url-Override": "baseUrlOverride", + "Decompress": "decompress", + "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", + }); +}); + +/** @internal */ +export type GetProxyRequest$Outbound = { + anyPath: string; + $ANY_QUERY_PARAMS: string; + "Connection-Id": string; + "Provider-Config-Key": string; + Retries?: string | undefined; + "Base-Url-Override"?: string | undefined; + Decompress?: string | undefined; + "nango-proxy-$ANY_HEADER"?: string | undefined; +}; + +/** @internal */ +export const GetProxyRequest$outboundSchema: z.ZodType< + GetProxyRequest$Outbound, + z.ZodTypeDef, + GetProxyRequest +> = z.object({ + anyPath: z.string(), + dollarANYQUERYPARAMS: z.string(), + connectionId: z.string(), + providerConfigKey: z.string(), + retries: z.string().optional(), + baseUrlOverride: z.string().optional(), + decompress: z.string().optional(), + nangoProxyDollarANYHEADER: z.string().optional(), +}).transform((v) => { + return remap$(v, { + dollarANYQUERYPARAMS: "$ANY_QUERY_PARAMS", + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + retries: "Retries", + baseUrlOverride: "Base-Url-Override", + decompress: "Decompress", + nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - $ANY_QUERY_PARAMS: z.string(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - Retries: z.string().optional(), - "Base-Url-Override": z.string().optional(), - Decompress: z.string().optional(), - "nango-proxy-$ANY_HEADER": z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - $ANY_QUERY_PARAMS: "dollarANYQUERYPARAMS", - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - Retries: "retries", - "Base-Url-Override": "baseUrlOverride", - Decompress: "decompress", - "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", - }); - }); + /** @deprecated use `GetProxyRequest$inboundSchema` instead. */ + export const inboundSchema = GetProxyRequest$inboundSchema; + /** @deprecated use `GetProxyRequest$outboundSchema` instead. */ + export const outboundSchema = GetProxyRequest$outboundSchema; + /** @deprecated use `GetProxyRequest$Outbound` instead. */ + export type Outbound = GetProxyRequest$Outbound; +} - export type Outbound = { - anyPath: string; - $ANY_QUERY_PARAMS: string; - "Connection-Id": string; - "Provider-Config-Key": string; - Retries?: string | undefined; - "Base-Url-Override"?: string | undefined; - Decompress?: string | undefined; - "nango-proxy-$ANY_HEADER"?: string | undefined; - }; +export function getProxyRequestToJSON( + getProxyRequest: GetProxyRequest, +): string { + return JSON.stringify(GetProxyRequest$outboundSchema.parse(getProxyRequest)); +} - export const outboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - dollarANYQUERYPARAMS: z.string(), - connectionId: z.string(), - providerConfigKey: z.string(), - retries: z.string().optional(), - baseUrlOverride: z.string().optional(), - decompress: z.string().optional(), - nangoProxyDollarANYHEADER: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - dollarANYQUERYPARAMS: "$ANY_QUERY_PARAMS", - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - retries: "Retries", - baseUrlOverride: "Base-Url-Override", - decompress: "Decompress", - nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", - }); - }); +export function getProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetProxyRequest' from JSON`, + ); } diff --git a/src/models/operations/getrecord.ts b/src/models/operations/getrecord.ts index 4d402ee..ff9d9c6 100644 --- a/src/models/operations/getrecord.ts +++ b/src/models/operations/getrecord.ts @@ -1,102 +1,152 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. */ export enum Filter { - Added = "added", - Updated = "updated", - Deleted = "deleted", + Added = "added", + Updated = "updated", + Deleted = "deleted", } export type GetRecordRequest = { - /** - * The data model to fetch - */ - model: string; - /** - * Timestamp, e.g. 2023-05-31T11:46:13.390Z. If passed only records added or updated after this timestamp are returned, otherwise all records are returned. - */ - delta?: string | undefined; - /** - * The maximum number of records to return. If not passed, all records are returned. - */ - limit?: number | undefined; - /** - * Base 64 encoded value that can be used to fetch the next page of results. The cursor will be included until there are no more results to paginate through. - * - * @remarks - * - */ - cursor?: string | undefined; - /** - * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. - */ - filter?: Filter | undefined; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; + /** + * The data model to fetch + */ + model: string; + /** + * Timestamp, e.g. 2023-05-31T11:46:13.390Z. If passed only records added or updated after this timestamp are returned, otherwise all records are returned. + */ + delta?: string | undefined; + /** + * The maximum number of records to return. If not passed, all records are returned. + */ + limit?: number | undefined; + /** + * Base 64 encoded value that can be used to fetch the next page of results. The cursor will be included until there are no more results to paginate through. + * + * @remarks + */ + cursor?: string | undefined; + /** + * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. + */ + filter?: Filter | undefined; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; }; /** @internal */ +export const Filter$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(Filter); + +/** @internal */ +export const Filter$outboundSchema: z.ZodNativeEnum = + Filter$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Filter$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(Filter); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `Filter$inboundSchema` instead. */ + export const inboundSchema = Filter$inboundSchema; + /** @deprecated use `Filter$outboundSchema` instead. */ + export const outboundSchema = Filter$outboundSchema; } /** @internal */ +export const GetRecordRequest$inboundSchema: z.ZodType< + GetRecordRequest, + z.ZodTypeDef, + unknown +> = z.object({ + model: z.string(), + delta: z.string().optional(), + limit: z.number().int().optional(), + cursor: z.string().optional(), + filter: Filter$inboundSchema.optional(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), +}).transform((v) => { + return remap$(v, { + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + }); +}); + +/** @internal */ +export type GetRecordRequest$Outbound = { + model: string; + delta?: string | undefined; + limit?: number | undefined; + cursor?: string | undefined; + filter?: string | undefined; + "Connection-Id": string; + "Provider-Config-Key": string; +}; + +/** @internal */ +export const GetRecordRequest$outboundSchema: z.ZodType< + GetRecordRequest$Outbound, + z.ZodTypeDef, + GetRecordRequest +> = z.object({ + model: z.string(), + delta: z.string().optional(), + limit: z.number().int().optional(), + cursor: z.string().optional(), + filter: Filter$outboundSchema.optional(), + connectionId: z.string(), + providerConfigKey: z.string(), +}).transform((v) => { + return remap$(v, { + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetRecordRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - model: z.string(), - delta: z.string().optional(), - limit: z.number().int().optional(), - cursor: z.string().optional(), - filter: Filter$.inboundSchema.optional(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - }) - .transform((v) => { - return remap$(v, { - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - }); - }); + /** @deprecated use `GetRecordRequest$inboundSchema` instead. */ + export const inboundSchema = GetRecordRequest$inboundSchema; + /** @deprecated use `GetRecordRequest$outboundSchema` instead. */ + export const outboundSchema = GetRecordRequest$outboundSchema; + /** @deprecated use `GetRecordRequest$Outbound` instead. */ + export type Outbound = GetRecordRequest$Outbound; +} - export type Outbound = { - model: string; - delta?: string | undefined; - limit?: number | undefined; - cursor?: string | undefined; - filter?: string | undefined; - "Connection-Id": string; - "Provider-Config-Key": string; - }; +export function getRecordRequestToJSON( + getRecordRequest: GetRecordRequest, +): string { + return JSON.stringify( + GetRecordRequest$outboundSchema.parse(getRecordRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - model: z.string(), - delta: z.string().optional(), - limit: z.number().int().optional(), - cursor: z.string().optional(), - filter: Filter$.outboundSchema.optional(), - connectionId: z.string(), - providerConfigKey: z.string(), - }) - .transform((v) => { - return remap$(v, { - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - }); - }); +export function getRecordRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetRecordRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetRecordRequest' from JSON`, + ); } diff --git a/src/models/operations/getsyncrecord.ts b/src/models/operations/getsyncrecord.ts index bc6e160..abd9215 100644 --- a/src/models/operations/getsyncrecord.ts +++ b/src/models/operations/getsyncrecord.ts @@ -1,145 +1,224 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; /** * Set how the records are sorted. The default is id. The options are 'created_at', 'updated_at', 'id'. */ export enum SortBy { - CreatedAt = "created_at", - UpdatedAt = "updated_at", - Id = "id", + CreatedAt = "created_at", + UpdatedAt = "updated_at", + Id = "id", } /** * Set the order of results. The default is 'desc'. The options are 'desc' or 'asc'. */ export enum Order { - Desc = "desc", - Asc = "asc", + Desc = "desc", + Asc = "asc", } /** * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. */ export enum QueryParamFilter { - Added = "added", - Updated = "updated", - Deleted = "deleted", + Added = "added", + Updated = "updated", + Deleted = "deleted", } export type GetSyncRecordRequest = { - /** - * The data model to fetch - */ - model: string; - /** - * Timestamp, e.g. 2023-05-31T11:46:13.390Z. If passed only records added or updated after this timestamp are returned, otherwise all records are returned. - */ - delta?: string | undefined; - /** - * The maximum number of records to return. If not passed, all records are returned. - */ - limit?: number | undefined; - /** - * The number of records to skip. If not passed, no records are skipped. - */ - offset?: number | undefined; - /** - * Set how the records are sorted. The default is id. The options are 'created_at', 'updated_at', 'id'. - */ - sortBy?: SortBy | undefined; - /** - * Set the order of results. The default is 'desc'. The options are 'desc' or 'asc'. - */ - order?: Order | undefined; - /** - * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. - */ - filter?: QueryParamFilter | undefined; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; + /** + * The data model to fetch + */ + model: string; + /** + * Timestamp, e.g. 2023-05-31T11:46:13.390Z. If passed only records added or updated after this timestamp are returned, otherwise all records are returned. + */ + delta?: string | undefined; + /** + * The maximum number of records to return. If not passed, all records are returned. + */ + limit?: number | undefined; + /** + * The number of records to skip. If not passed, no records are skipped. + */ + offset?: number | undefined; + /** + * Set how the records are sorted. The default is id. The options are 'created_at', 'updated_at', 'id'. + */ + sortBy?: SortBy | undefined; + /** + * Set the order of results. The default is 'desc'. The options are 'desc' or 'asc'. + */ + order?: Order | undefined; + /** + * Filter to only show results that have been added or updated or deleted. Helpful when used in conjuction with the delta parameter to retrieve a subset or records that were added, updated, or deleted with the latest sync. + */ + filter?: QueryParamFilter | undefined; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; }; /** @internal */ +export const SortBy$inboundSchema: z.ZodNativeEnum = z + .nativeEnum(SortBy); + +/** @internal */ +export const SortBy$outboundSchema: z.ZodNativeEnum = + SortBy$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace SortBy$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(SortBy); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `SortBy$inboundSchema` instead. */ + export const inboundSchema = SortBy$inboundSchema; + /** @deprecated use `SortBy$outboundSchema` instead. */ + export const outboundSchema = SortBy$outboundSchema; } /** @internal */ +export const Order$inboundSchema: z.ZodNativeEnum = z.nativeEnum( + Order, +); + +/** @internal */ +export const Order$outboundSchema: z.ZodNativeEnum = + Order$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace Order$ { - export const inboundSchema: z.ZodNativeEnum = z.nativeEnum(Order); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `Order$inboundSchema` instead. */ + export const inboundSchema = Order$inboundSchema; + /** @deprecated use `Order$outboundSchema` instead. */ + export const outboundSchema = Order$outboundSchema; } /** @internal */ +export const QueryParamFilter$inboundSchema: z.ZodNativeEnum< + typeof QueryParamFilter +> = z.nativeEnum(QueryParamFilter); + +/** @internal */ +export const QueryParamFilter$outboundSchema: z.ZodNativeEnum< + typeof QueryParamFilter +> = QueryParamFilter$inboundSchema; + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace QueryParamFilter$ { - export const inboundSchema: z.ZodNativeEnum = - z.nativeEnum(QueryParamFilter); - export const outboundSchema: z.ZodNativeEnum = inboundSchema; + /** @deprecated use `QueryParamFilter$inboundSchema` instead. */ + export const inboundSchema = QueryParamFilter$inboundSchema; + /** @deprecated use `QueryParamFilter$outboundSchema` instead. */ + export const outboundSchema = QueryParamFilter$outboundSchema; } /** @internal */ +export const GetSyncRecordRequest$inboundSchema: z.ZodType< + GetSyncRecordRequest, + z.ZodTypeDef, + unknown +> = z.object({ + model: z.string(), + delta: z.string().optional(), + limit: z.number().int().optional(), + offset: z.number().int().optional(), + sort_by: SortBy$inboundSchema.optional(), + order: Order$inboundSchema.optional(), + filter: QueryParamFilter$inboundSchema.optional(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), +}).transform((v) => { + return remap$(v, { + "sort_by": "sortBy", + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + }); +}); + +/** @internal */ +export type GetSyncRecordRequest$Outbound = { + model: string; + delta?: string | undefined; + limit?: number | undefined; + offset?: number | undefined; + sort_by?: string | undefined; + order?: string | undefined; + filter?: string | undefined; + "Connection-Id": string; + "Provider-Config-Key": string; +}; + +/** @internal */ +export const GetSyncRecordRequest$outboundSchema: z.ZodType< + GetSyncRecordRequest$Outbound, + z.ZodTypeDef, + GetSyncRecordRequest +> = z.object({ + model: z.string(), + delta: z.string().optional(), + limit: z.number().int().optional(), + offset: z.number().int().optional(), + sortBy: SortBy$outboundSchema.optional(), + order: Order$outboundSchema.optional(), + filter: QueryParamFilter$outboundSchema.optional(), + connectionId: z.string(), + providerConfigKey: z.string(), +}).transform((v) => { + return remap$(v, { + sortBy: "sort_by", + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetSyncRecordRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - model: z.string(), - delta: z.string().optional(), - limit: z.number().int().optional(), - offset: z.number().int().optional(), - sort_by: SortBy$.inboundSchema.optional(), - order: Order$.inboundSchema.optional(), - filter: QueryParamFilter$.inboundSchema.optional(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - }) - .transform((v) => { - return remap$(v, { - sort_by: "sortBy", - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - }); - }); - - export type Outbound = { - model: string; - delta?: string | undefined; - limit?: number | undefined; - offset?: number | undefined; - sort_by?: string | undefined; - order?: string | undefined; - filter?: string | undefined; - "Connection-Id": string; - "Provider-Config-Key": string; - }; - - export const outboundSchema: z.ZodType = z - .object({ - model: z.string(), - delta: z.string().optional(), - limit: z.number().int().optional(), - offset: z.number().int().optional(), - sortBy: SortBy$.outboundSchema.optional(), - order: Order$.outboundSchema.optional(), - filter: QueryParamFilter$.outboundSchema.optional(), - connectionId: z.string(), - providerConfigKey: z.string(), - }) - .transform((v) => { - return remap$(v, { - sortBy: "sort_by", - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - }); - }); + /** @deprecated use `GetSyncRecordRequest$inboundSchema` instead. */ + export const inboundSchema = GetSyncRecordRequest$inboundSchema; + /** @deprecated use `GetSyncRecordRequest$outboundSchema` instead. */ + export const outboundSchema = GetSyncRecordRequest$outboundSchema; + /** @deprecated use `GetSyncRecordRequest$Outbound` instead. */ + export type Outbound = GetSyncRecordRequest$Outbound; +} + +export function getSyncRecordRequestToJSON( + getSyncRecordRequest: GetSyncRecordRequest, +): string { + return JSON.stringify( + GetSyncRecordRequest$outboundSchema.parse(getSyncRecordRequest), + ); +} + +export function getSyncRecordRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetSyncRecordRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetSyncRecordRequest' from JSON`, + ); } diff --git a/src/models/operations/getsyncstatus.ts b/src/models/operations/getsyncstatus.ts index 16dead2..6b119cf 100644 --- a/src/models/operations/getsyncstatus.ts +++ b/src/models/operations/getsyncstatus.ts @@ -1,56 +1,94 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type GetSyncStatusRequest = { - /** - * The ID of the integration you established within Nango - */ - providerConfigKey: string; - /** - * The name of the syncs you want to fetch a status for. Pass in "*" to return all syncs per the integration - */ - syncs: string; - /** - * The ID of the connection. If omitted, all connections will be surfaced. - */ - connectionId?: string | undefined; + /** + * The ID of the integration you established within Nango + */ + providerConfigKey: string; + /** + * The name of the syncs you want to fetch a status for. Pass in "*" to return all syncs per the integration + */ + syncs: string; + /** + * The ID of the connection. If omitted, all connections will be surfaced. + */ + connectionId?: string | undefined; +}; + +/** @internal */ +export const GetSyncStatusRequest$inboundSchema: z.ZodType< + GetSyncStatusRequest, + z.ZodTypeDef, + unknown +> = z.object({ + provider_config_key: z.string(), + syncs: z.string(), + connection_id: z.string().optional(), +}).transform((v) => { + return remap$(v, { + "provider_config_key": "providerConfigKey", + "connection_id": "connectionId", + }); +}); + +/** @internal */ +export type GetSyncStatusRequest$Outbound = { + provider_config_key: string; + syncs: string; + connection_id?: string | undefined; }; /** @internal */ +export const GetSyncStatusRequest$outboundSchema: z.ZodType< + GetSyncStatusRequest$Outbound, + z.ZodTypeDef, + GetSyncStatusRequest +> = z.object({ + providerConfigKey: z.string(), + syncs: z.string(), + connectionId: z.string().optional(), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "provider_config_key", + connectionId: "connection_id", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace GetSyncStatusRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - provider_config_key: z.string(), - syncs: z.string(), - connection_id: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - provider_config_key: "providerConfigKey", - connection_id: "connectionId", - }); - }); - - export type Outbound = { - provider_config_key: string; - syncs: string; - connection_id?: string | undefined; - }; - - export const outboundSchema: z.ZodType = z - .object({ - providerConfigKey: z.string(), - syncs: z.string(), - connectionId: z.string().optional(), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "provider_config_key", - connectionId: "connection_id", - }); - }); + /** @deprecated use `GetSyncStatusRequest$inboundSchema` instead. */ + export const inboundSchema = GetSyncStatusRequest$inboundSchema; + /** @deprecated use `GetSyncStatusRequest$outboundSchema` instead. */ + export const outboundSchema = GetSyncStatusRequest$outboundSchema; + /** @deprecated use `GetSyncStatusRequest$Outbound` instead. */ + export type Outbound = GetSyncStatusRequest$Outbound; +} + +export function getSyncStatusRequestToJSON( + getSyncStatusRequest: GetSyncStatusRequest, +): string { + return JSON.stringify( + GetSyncStatusRequest$outboundSchema.parse(getSyncStatusRequest), + ); +} + +export function getSyncStatusRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetSyncStatusRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetSyncStatusRequest' from JSON`, + ); } diff --git a/src/models/operations/index.ts b/src/models/operations/index.ts index 252eefb..a03d8bc 100644 --- a/src/models/operations/index.ts +++ b/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 "./createactiontrigger.js"; diff --git a/src/models/operations/listconnections.ts b/src/models/operations/listconnections.ts index 0cf7638..13179b8 100644 --- a/src/models/operations/listconnections.ts +++ b/src/models/operations/listconnections.ts @@ -1,30 +1,69 @@ /* - * 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"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type ListConnectionsRequest = { - /** - * Filter the list of connections based on this connection ID. - */ - connectionId?: string | undefined; + /** + * Filter the list of connections based on this connection ID. + */ + connectionId?: string | undefined; }; /** @internal */ +export const ListConnectionsRequest$inboundSchema: z.ZodType< + ListConnectionsRequest, + z.ZodTypeDef, + unknown +> = z.object({ + connectionId: z.string().optional(), +}); + +/** @internal */ +export type ListConnectionsRequest$Outbound = { + connectionId?: string | undefined; +}; + +/** @internal */ +export const ListConnectionsRequest$outboundSchema: z.ZodType< + ListConnectionsRequest$Outbound, + z.ZodTypeDef, + ListConnectionsRequest +> = z.object({ + connectionId: 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 ListConnectionsRequest$ { - export const inboundSchema: z.ZodType = z.object( - { - connectionId: z.string().optional(), - } - ); - - export type Outbound = { - connectionId?: string | undefined; - }; - - export const outboundSchema: z.ZodType = - z.object({ - connectionId: z.string().optional(), - }); + /** @deprecated use `ListConnectionsRequest$inboundSchema` instead. */ + export const inboundSchema = ListConnectionsRequest$inboundSchema; + /** @deprecated use `ListConnectionsRequest$outboundSchema` instead. */ + export const outboundSchema = ListConnectionsRequest$outboundSchema; + /** @deprecated use `ListConnectionsRequest$Outbound` instead. */ + export type Outbound = ListConnectionsRequest$Outbound; +} + +export function listConnectionsRequestToJSON( + listConnectionsRequest: ListConnectionsRequest, +): string { + return JSON.stringify( + ListConnectionsRequest$outboundSchema.parse(listConnectionsRequest), + ); +} + +export function listConnectionsRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => ListConnectionsRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'ListConnectionsRequest' from JSON`, + ); } diff --git a/src/models/operations/patchproxy.ts b/src/models/operations/patchproxy.ts index b4b7f98..2f8c155 100644 --- a/src/models/operations/patchproxy.ts +++ b/src/models/operations/patchproxy.ts @@ -1,96 +1,134 @@ /* - * 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"; import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; import * as components from "../components/index.js"; -import * as z from "zod"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type PatchProxyRequest = { - anyPath: string; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * The number of retries in case of failure (with exponential back-off). Optional, default 0. - */ - retries?: string | undefined; - /** - * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional - */ - baseUrlOverride?: string | undefined; - /** - * Override the decompress option when making requests. Optional, defaults to false - */ - decompress?: string | undefined; - /** - * Any other headers you send are passed on to the external API - */ - nangoProxyDollarANYHEADER?: string | undefined; - patchProxyRequest?: components.PatchProxyRequest | undefined; + anyPath: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * The number of retries in case of failure (with exponential back-off). Optional, default 0. + */ + retries?: string | undefined; + /** + * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional + */ + baseUrlOverride?: string | undefined; + /** + * Override the decompress option when making requests. Optional, defaults to false + */ + decompress?: string | undefined; + /** + * Any other headers you send are passed on to the external API + */ + nangoProxyDollarANYHEADER?: string | undefined; + patchProxyRequest?: components.PatchProxyRequest | undefined; }; /** @internal */ +export const PatchProxyRequest$inboundSchema: z.ZodType< + PatchProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + anyPath: z.string(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + Retries: z.string().optional(), + "Base-Url-Override": z.string().optional(), + Decompress: z.string().optional(), + "nango-proxy-$ANY_HEADER": z.string().optional(), + PatchProxyRequest: components.PatchProxyRequest$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "Retries": "retries", + "Base-Url-Override": "baseUrlOverride", + "Decompress": "decompress", + "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", + "PatchProxyRequest": "patchProxyRequest", + }); +}); + +/** @internal */ +export type PatchProxyRequest$Outbound = { + anyPath: string; + "Connection-Id": string; + "Provider-Config-Key": string; + Retries?: string | undefined; + "Base-Url-Override"?: string | undefined; + Decompress?: string | undefined; + "nango-proxy-$ANY_HEADER"?: string | undefined; + PatchProxyRequest?: components.PatchProxyRequest$Outbound | undefined; +}; + +/** @internal */ +export const PatchProxyRequest$outboundSchema: z.ZodType< + PatchProxyRequest$Outbound, + z.ZodTypeDef, + PatchProxyRequest +> = z.object({ + anyPath: z.string(), + connectionId: z.string(), + providerConfigKey: z.string(), + retries: z.string().optional(), + baseUrlOverride: z.string().optional(), + decompress: z.string().optional(), + nangoProxyDollarANYHEADER: z.string().optional(), + patchProxyRequest: components.PatchProxyRequest$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + retries: "Retries", + baseUrlOverride: "Base-Url-Override", + decompress: "Decompress", + nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", + patchProxyRequest: "PatchProxyRequest", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace PatchProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - Retries: z.string().optional(), - "Base-Url-Override": z.string().optional(), - Decompress: z.string().optional(), - "nango-proxy-$ANY_HEADER": z.string().optional(), - PatchProxyRequest: components.PatchProxyRequest$.inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - Retries: "retries", - "Base-Url-Override": "baseUrlOverride", - Decompress: "decompress", - "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", - PatchProxyRequest: "patchProxyRequest", - }); - }); + /** @deprecated use `PatchProxyRequest$inboundSchema` instead. */ + export const inboundSchema = PatchProxyRequest$inboundSchema; + /** @deprecated use `PatchProxyRequest$outboundSchema` instead. */ + export const outboundSchema = PatchProxyRequest$outboundSchema; + /** @deprecated use `PatchProxyRequest$Outbound` instead. */ + export type Outbound = PatchProxyRequest$Outbound; +} - export type Outbound = { - anyPath: string; - "Connection-Id": string; - "Provider-Config-Key": string; - Retries?: string | undefined; - "Base-Url-Override"?: string | undefined; - Decompress?: string | undefined; - "nango-proxy-$ANY_HEADER"?: string | undefined; - PatchProxyRequest?: components.PatchProxyRequest$.Outbound | undefined; - }; +export function patchProxyRequestToJSON( + patchProxyRequest: PatchProxyRequest, +): string { + return JSON.stringify( + PatchProxyRequest$outboundSchema.parse(patchProxyRequest), + ); +} - export const outboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - connectionId: z.string(), - providerConfigKey: z.string(), - retries: z.string().optional(), - baseUrlOverride: z.string().optional(), - decompress: z.string().optional(), - nangoProxyDollarANYHEADER: z.string().optional(), - patchProxyRequest: components.PatchProxyRequest$.outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - retries: "Retries", - baseUrlOverride: "Base-Url-Override", - decompress: "Decompress", - nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", - patchProxyRequest: "PatchProxyRequest", - }); - }); +export function patchProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PatchProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PatchProxyRequest' from JSON`, + ); } diff --git a/src/models/operations/putproxy.ts b/src/models/operations/putproxy.ts index 93ecc84..b86d066 100644 --- a/src/models/operations/putproxy.ts +++ b/src/models/operations/putproxy.ts @@ -1,96 +1,132 @@ /* - * 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"; import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; import * as components from "../components/index.js"; -import * as z from "zod"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type PutProxyRequest = { - anyPath: string; - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - /** - * The number of retries in case of failure (with exponential back-off). Optional, default 0. - */ - retries?: string | undefined; - /** - * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional - */ - baseUrlOverride?: string | undefined; - /** - * Override the decompress option when making requests. Optional, defaults to false - */ - decompress?: string | undefined; - /** - * Any other headers you send are passed on to the external API - */ - nangoProxyDollarANYHEADER?: string | undefined; - putProxyRequest?: components.PutProxyRequest | undefined; + anyPath: string; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + /** + * The number of retries in case of failure (with exponential back-off). Optional, default 0. + */ + retries?: string | undefined; + /** + * Provide an API base URL when the base API is not listed in the providers.yaml or it needs to be overridden. Optional + */ + baseUrlOverride?: string | undefined; + /** + * Override the decompress option when making requests. Optional, defaults to false + */ + decompress?: string | undefined; + /** + * Any other headers you send are passed on to the external API + */ + nangoProxyDollarANYHEADER?: string | undefined; + putProxyRequest?: components.PutProxyRequest | undefined; }; /** @internal */ +export const PutProxyRequest$inboundSchema: z.ZodType< + PutProxyRequest, + z.ZodTypeDef, + unknown +> = z.object({ + anyPath: z.string(), + "Connection-Id": z.string(), + "Provider-Config-Key": z.string(), + Retries: z.string().optional(), + "Base-Url-Override": z.string().optional(), + Decompress: z.string().optional(), + "nango-proxy-$ANY_HEADER": z.string().optional(), + PutProxyRequest: components.PutProxyRequest$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "Connection-Id": "connectionId", + "Provider-Config-Key": "providerConfigKey", + "Retries": "retries", + "Base-Url-Override": "baseUrlOverride", + "Decompress": "decompress", + "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", + "PutProxyRequest": "putProxyRequest", + }); +}); + +/** @internal */ +export type PutProxyRequest$Outbound = { + anyPath: string; + "Connection-Id": string; + "Provider-Config-Key": string; + Retries?: string | undefined; + "Base-Url-Override"?: string | undefined; + Decompress?: string | undefined; + "nango-proxy-$ANY_HEADER"?: string | undefined; + PutProxyRequest?: components.PutProxyRequest$Outbound | undefined; +}; + +/** @internal */ +export const PutProxyRequest$outboundSchema: z.ZodType< + PutProxyRequest$Outbound, + z.ZodTypeDef, + PutProxyRequest +> = z.object({ + anyPath: z.string(), + connectionId: z.string(), + providerConfigKey: z.string(), + retries: z.string().optional(), + baseUrlOverride: z.string().optional(), + decompress: z.string().optional(), + nangoProxyDollarANYHEADER: z.string().optional(), + putProxyRequest: components.PutProxyRequest$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + connectionId: "Connection-Id", + providerConfigKey: "Provider-Config-Key", + retries: "Retries", + baseUrlOverride: "Base-Url-Override", + decompress: "Decompress", + nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", + putProxyRequest: "PutProxyRequest", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace PutProxyRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - "Connection-Id": z.string(), - "Provider-Config-Key": z.string(), - Retries: z.string().optional(), - "Base-Url-Override": z.string().optional(), - Decompress: z.string().optional(), - "nango-proxy-$ANY_HEADER": z.string().optional(), - PutProxyRequest: components.PutProxyRequest$.inboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - "Connection-Id": "connectionId", - "Provider-Config-Key": "providerConfigKey", - Retries: "retries", - "Base-Url-Override": "baseUrlOverride", - Decompress: "decompress", - "nango-proxy-$ANY_HEADER": "nangoProxyDollarANYHEADER", - PutProxyRequest: "putProxyRequest", - }); - }); + /** @deprecated use `PutProxyRequest$inboundSchema` instead. */ + export const inboundSchema = PutProxyRequest$inboundSchema; + /** @deprecated use `PutProxyRequest$outboundSchema` instead. */ + export const outboundSchema = PutProxyRequest$outboundSchema; + /** @deprecated use `PutProxyRequest$Outbound` instead. */ + export type Outbound = PutProxyRequest$Outbound; +} - export type Outbound = { - anyPath: string; - "Connection-Id": string; - "Provider-Config-Key": string; - Retries?: string | undefined; - "Base-Url-Override"?: string | undefined; - Decompress?: string | undefined; - "nango-proxy-$ANY_HEADER"?: string | undefined; - PutProxyRequest?: components.PutProxyRequest$.Outbound | undefined; - }; +export function putProxyRequestToJSON( + putProxyRequest: PutProxyRequest, +): string { + return JSON.stringify(PutProxyRequest$outboundSchema.parse(putProxyRequest)); +} - export const outboundSchema: z.ZodType = z - .object({ - anyPath: z.string(), - connectionId: z.string(), - providerConfigKey: z.string(), - retries: z.string().optional(), - baseUrlOverride: z.string().optional(), - decompress: z.string().optional(), - nangoProxyDollarANYHEADER: z.string().optional(), - putProxyRequest: components.PutProxyRequest$.outboundSchema.optional(), - }) - .transform((v) => { - return remap$(v, { - connectionId: "Connection-Id", - providerConfigKey: "Provider-Config-Key", - retries: "Retries", - baseUrlOverride: "Base-Url-Override", - decompress: "Decompress", - nangoProxyDollarANYHEADER: "nango-proxy-$ANY_HEADER", - putProxyRequest: "PutProxyRequest", - }); - }); +export function putProxyRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PutProxyRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PutProxyRequest' from JSON`, + ); } diff --git a/src/models/operations/updatemetadata.ts b/src/models/operations/updatemetadata.ts index 132f0a9..54829c1 100644 --- a/src/models/operations/updatemetadata.ts +++ b/src/models/operations/updatemetadata.ts @@ -1,22 +1,25 @@ /* - * 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"; import * as z from "zod"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; export type UpdateMetadataRequestBody = {}; export type UpdateMetadataRequest = { - /** - * The connection ID used to create the connection. - */ - connectionId: string; - /** - * The integration ID used to create the connection (aka Unique Key). - */ - providerConfigKey: string; - requestBody: UpdateMetadataRequestBody; + /** + * The connection ID used to create the connection. + */ + connectionId: string; + /** + * The integration ID used to create the connection (aka Unique Key). + */ + providerConfigKey: string; + requestBody: UpdateMetadataRequestBody; }; /** @@ -25,58 +28,167 @@ export type UpdateMetadataRequest = { export type UpdateMetadataResponseBody = {}; /** @internal */ +export const UpdateMetadataRequestBody$inboundSchema: z.ZodType< + UpdateMetadataRequestBody, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type UpdateMetadataRequestBody$Outbound = {}; + +/** @internal */ +export const UpdateMetadataRequestBody$outboundSchema: z.ZodType< + UpdateMetadataRequestBody$Outbound, + z.ZodTypeDef, + UpdateMetadataRequestBody +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace UpdateMetadataRequestBody$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `UpdateMetadataRequestBody$inboundSchema` instead. */ + export const inboundSchema = UpdateMetadataRequestBody$inboundSchema; + /** @deprecated use `UpdateMetadataRequestBody$outboundSchema` instead. */ + export const outboundSchema = UpdateMetadataRequestBody$outboundSchema; + /** @deprecated use `UpdateMetadataRequestBody$Outbound` instead. */ + export type Outbound = UpdateMetadataRequestBody$Outbound; +} - export type Outbound = {}; +export function updateMetadataRequestBodyToJSON( + updateMetadataRequestBody: UpdateMetadataRequestBody, +): string { + return JSON.stringify( + UpdateMetadataRequestBody$outboundSchema.parse(updateMetadataRequestBody), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function updateMetadataRequestBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateMetadataRequestBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateMetadataRequestBody' from JSON`, + ); } /** @internal */ +export const UpdateMetadataRequest$inboundSchema: z.ZodType< + UpdateMetadataRequest, + z.ZodTypeDef, + unknown +> = z.object({ + connectionId: z.string(), + "Provider-Config-Key": z.string(), + RequestBody: z.lazy(() => UpdateMetadataRequestBody$inboundSchema), +}).transform((v) => { + return remap$(v, { + "Provider-Config-Key": "providerConfigKey", + "RequestBody": "requestBody", + }); +}); + +/** @internal */ +export type UpdateMetadataRequest$Outbound = { + connectionId: string; + "Provider-Config-Key": string; + RequestBody: UpdateMetadataRequestBody$Outbound; +}; + +/** @internal */ +export const UpdateMetadataRequest$outboundSchema: z.ZodType< + UpdateMetadataRequest$Outbound, + z.ZodTypeDef, + UpdateMetadataRequest +> = z.object({ + connectionId: z.string(), + providerConfigKey: z.string(), + requestBody: z.lazy(() => UpdateMetadataRequestBody$outboundSchema), +}).transform((v) => { + return remap$(v, { + providerConfigKey: "Provider-Config-Key", + requestBody: "RequestBody", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace UpdateMetadataRequest$ { - export const inboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - "Provider-Config-Key": z.string(), - RequestBody: z.lazy(() => UpdateMetadataRequestBody$.inboundSchema), - }) - .transform((v) => { - return remap$(v, { - "Provider-Config-Key": "providerConfigKey", - RequestBody: "requestBody", - }); - }); - - export type Outbound = { - connectionId: string; - "Provider-Config-Key": string; - RequestBody: UpdateMetadataRequestBody$.Outbound; - }; - - export const outboundSchema: z.ZodType = z - .object({ - connectionId: z.string(), - providerConfigKey: z.string(), - requestBody: z.lazy(() => UpdateMetadataRequestBody$.outboundSchema), - }) - .transform((v) => { - return remap$(v, { - providerConfigKey: "Provider-Config-Key", - requestBody: "RequestBody", - }); - }); + /** @deprecated use `UpdateMetadataRequest$inboundSchema` instead. */ + export const inboundSchema = UpdateMetadataRequest$inboundSchema; + /** @deprecated use `UpdateMetadataRequest$outboundSchema` instead. */ + export const outboundSchema = UpdateMetadataRequest$outboundSchema; + /** @deprecated use `UpdateMetadataRequest$Outbound` instead. */ + export type Outbound = UpdateMetadataRequest$Outbound; +} + +export function updateMetadataRequestToJSON( + updateMetadataRequest: UpdateMetadataRequest, +): string { + return JSON.stringify( + UpdateMetadataRequest$outboundSchema.parse(updateMetadataRequest), + ); +} + +export function updateMetadataRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateMetadataRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateMetadataRequest' from JSON`, + ); } /** @internal */ +export const UpdateMetadataResponseBody$inboundSchema: z.ZodType< + UpdateMetadataResponseBody, + z.ZodTypeDef, + unknown +> = z.object({}); + +/** @internal */ +export type UpdateMetadataResponseBody$Outbound = {}; + +/** @internal */ +export const UpdateMetadataResponseBody$outboundSchema: z.ZodType< + UpdateMetadataResponseBody$Outbound, + z.ZodTypeDef, + UpdateMetadataResponseBody +> = z.object({}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ export namespace UpdateMetadataResponseBody$ { - export const inboundSchema: z.ZodType = - z.object({}); + /** @deprecated use `UpdateMetadataResponseBody$inboundSchema` instead. */ + export const inboundSchema = UpdateMetadataResponseBody$inboundSchema; + /** @deprecated use `UpdateMetadataResponseBody$outboundSchema` instead. */ + export const outboundSchema = UpdateMetadataResponseBody$outboundSchema; + /** @deprecated use `UpdateMetadataResponseBody$Outbound` instead. */ + export type Outbound = UpdateMetadataResponseBody$Outbound; +} - export type Outbound = {}; +export function updateMetadataResponseBodyToJSON( + updateMetadataResponseBody: UpdateMetadataResponseBody, +): string { + return JSON.stringify( + UpdateMetadataResponseBody$outboundSchema.parse(updateMetadataResponseBody), + ); +} - export const outboundSchema: z.ZodType = - z.object({}); +export function updateMetadataResponseBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdateMetadataResponseBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdateMetadataResponseBody' from JSON`, + ); } diff --git a/src/sdk/actions.ts b/src/sdk/actions.ts index 750f142..febae28 100644 --- a/src/sdk/actions.ts +++ b/src/sdk/actions.ts @@ -1,116 +1,31 @@ /* - * 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 { encodeJSON as encodeJSON$, encodeSimple as encodeSimple$ } from "../lib/encodings.js"; -import { HTTPClient } from "../lib/http.js"; -import * as schemas$ from "../lib/schemas.js"; +import { actionsCreateTrigger } from "../funcs/actionsCreateTrigger.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as errors from "../models/errors/index.js"; -import * as operations from "../models/operations/index.js"; +import { unwrapAsync } from "../types/fp.js"; export class Actions 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$; - } - - /** - * Triggers an action for a connection. - * - * @remarks - * Triggers an action for a connection - */ - async createTrigger( - connectionId: string, - providerConfigKey: string, - createActionTriggerRequest: components.CreateActionTriggerRequest, - options?: RequestOptions - ): Promise { - const input$: operations.CreateActionTriggerRequest = { - connectionId: connectionId, - providerConfigKey: providerConfigKey, - createActionTriggerRequest: createActionTriggerRequest, - }; - 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$) => operations.CreateActionTriggerRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.CreateActionTriggerRequest, { explode: true }); - - const path$ = this.templateURLComponent("/action/trigger")(); - - const query$ = ""; - - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { - operationID: "createActionTrigger", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "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 responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .json(200, components.CreateActionTriggerResponse$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } + /** + * Triggers an action for a connection. + * + * @remarks + * Triggers an action for a connection + */ + async createTrigger( + connectionId: string, + providerConfigKey: string, + createActionTriggerRequest: components.CreateActionTriggerRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(actionsCreateTrigger( + this, + connectionId, + providerConfigKey, + createActionTriggerRequest, + options, + )); + } } diff --git a/src/sdk/connections.ts b/src/sdk/connections.ts index f267f78..25fbe45 100644 --- a/src/sdk/connections.ts +++ b/src/sdk/connections.ts @@ -1,416 +1,134 @@ /* - * 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 { connectionsCreate } from "../funcs/connectionsCreate.js"; +import { connectionsCreateMetadata } from "../funcs/connectionsCreateMetadata.js"; +import { connectionsDelete } from "../funcs/connectionsDelete.js"; +import { connectionsGet } from "../funcs/connectionsGet.js"; +import { connectionsList } from "../funcs/connectionsList.js"; +import { connectionsUpdate } from "../funcs/connectionsUpdate.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as errors from "../models/errors/index.js"; import * as operations from "../models/operations/index.js"; -import * as z from "zod"; +import { unwrapAsync } from "../types/fp.js"; export class Connections 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$; - } - - /** - * Returns a list of connections, optionally filtered by connection ID. - * - * @remarks - * Returns a list of connections - */ - async list( - connectionId?: string | undefined, - options?: RequestOptions - ): Promise { - const input$: operations.ListConnectionsRequest = { - connectionId: connectionId, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.ListConnectionsRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const path$ = this.templateURLComponent("/connection")(); - - const query$ = encodeFormQuery$({ - connectionId: payload$.connectionId, - }); - - const context = { operationID: "listConnections", 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, components.GetConnectionResponse$) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Adds a connection using an existing access token, along with optional OAuth or basic authentication credentials, and additional metadata or configuration. - * - * @remarks - * Adds a connection for which you already have an access token - */ - async create( - request: components.CreateConnectionRequest, - options?: RequestOptions - ): Promise { - const input$ = request; - void input$; // request input is unused - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Content-Type", "application/json"); - headers$.set("Accept", "application/json"); - - const path$ = this.templateURLComponent("/connection")(); - - const query$ = ""; - - const context = { operationID: "createConnection", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "POST", path: path$, headers: headers$, query: query$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .void(200, z.void()) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Returns details of a specific connection identified by its connection ID, associated with the specified integration, with optional parameters for force refresh and returning the refresh token. - * - * @remarks - * Returns a specific connection - */ - async get( - connectionId: string, - providerConfigKey: string, - forceRefresh?: boolean | undefined, - refreshToken?: boolean | undefined, - options?: RequestOptions - ): Promise { - const input$: operations.GetConnectionsRequest = { - connectionId: connectionId, - providerConfigKey: providerConfigKey, - forceRefresh: forceRefresh, - refreshToken: refreshToken, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.GetConnectionsRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - connectionId: encodeSimple$("connectionId", payload$.connectionId, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/connection/{connectionId}")(pathParams$); - - const query$ = encodeFormQuery$({ - force_refresh: payload$.force_refresh, - provider_config_key: payload$.provider_config_key, - refresh_token: payload$.refresh_token, - }); - - const context = { operationID: "getConnections", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "404", "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() - .void(200, z.void()) - .json(400, errors.Response400$, { err: true }) - .json(404, errors.Response404$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Deletes a specific connection identified by its connection ID, associated with the specified integration. - * - * @remarks - * Deletes a specific connection - */ - async delete( - connectionId: string, - providerConfigKey: string, - options?: RequestOptions - ): Promise { - const input$: operations.DeleteConnectionsRequest = { - connectionId: connectionId, - providerConfigKey: providerConfigKey, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.DeleteConnectionsRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - connectionId: encodeSimple$("connectionId", payload$.connectionId, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/connection/{connectionId}")(pathParams$); - - const query$ = encodeFormQuery$({ - provider_config_key: payload$.provider_config_key, - }); - - const context = { - operationID: "deleteConnections", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "404", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "DELETE", 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() - .void(204, z.void()) - .json(400, errors.Response400$, { err: true }) - .json(404, errors.Response404$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Set custom metadata for the specified connection. - * - * @remarks - * Set custom metadata for the connection. - */ - async createMetadata( - connectionId: string, - providerConfigKey: string, - requestBody: operations.CreateMetadataRequestBody, - options?: RequestOptions - ): Promise { - const input$: operations.CreateMetadataRequest = { - connectionId: connectionId, - providerConfigKey: providerConfigKey, - requestBody: requestBody, - }; - 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$) => operations.CreateMetadataRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.RequestBody, { explode: true }); - - const pathParams$ = { - connectionId: encodeSimple$("connectionId", payload$.connectionId, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/connection/{connectionId}/metadata")(pathParams$); - - const query$ = ""; - - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "createMetadata", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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 responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .void(201, z.void()) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Update custom metadata for the specified connection. - * - * @remarks - * Update custom metadata for the connection. - */ - async update( - connectionId: string, - providerConfigKey: string, - requestBody: operations.UpdateMetadataRequestBody, - options?: RequestOptions - ): Promise { - const input$: operations.UpdateMetadataRequest = { - connectionId: connectionId, - providerConfigKey: providerConfigKey, - requestBody: requestBody, - }; - 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$) => operations.UpdateMetadataRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.RequestBody, { explode: true }); - - const pathParams$ = { - connectionId: encodeSimple$("connectionId", payload$.connectionId, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/connection/{connectionId}/metadata")(pathParams$); - - const query$ = ""; - - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "updateMetadata", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "PATCH", 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.UpdateMetadataResponseBody$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } + /** + * Returns a list of connections, optionally filtered by connection ID. + * + * @remarks + * Returns a list of connections + */ + async list( + connectionId?: string | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsList( + this, + connectionId, + options, + )); + } + + /** + * Adds a connection using an existing access token, along with optional OAuth or basic authentication credentials, and additional metadata or configuration. + * + * @remarks + * Adds a connection for which you already have an access token + */ + async create( + request: components.CreateConnectionRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsCreate( + this, + request, + options, + )); + } + + /** + * Returns details of a specific connection identified by its connection ID, associated with the specified integration, with optional parameters for force refresh and returning the refresh token. + * + * @remarks + * Returns a specific connection + */ + async get( + connectionId: string, + providerConfigKey: string, + forceRefresh?: boolean | undefined, + refreshToken?: boolean | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsGet( + this, + connectionId, + providerConfigKey, + forceRefresh, + refreshToken, + options, + )); + } + + /** + * Deletes a specific connection identified by its connection ID, associated with the specified integration. + * + * @remarks + * Deletes a specific connection + */ + async delete( + connectionId: string, + providerConfigKey: string, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsDelete( + this, + connectionId, + providerConfigKey, + options, + )); + } + + /** + * Set custom metadata for the specified connection. + * + * @remarks + * Set custom metadata for the connection. + */ + async createMetadata( + connectionId: string, + providerConfigKey: string, + requestBody: operations.CreateMetadataRequestBody, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsCreateMetadata( + this, + connectionId, + providerConfigKey, + requestBody, + options, + )); + } + + /** + * Update custom metadata for the specified connection. + * + * @remarks + * Update custom metadata for the connection. + */ + async update( + connectionId: string, + providerConfigKey: string, + requestBody: operations.UpdateMetadataRequestBody, + options?: RequestOptions, + ): Promise { + return unwrapAsync(connectionsUpdate( + this, + connectionId, + providerConfigKey, + requestBody, + options, + )); + } } diff --git a/src/sdk/environment.ts b/src/sdk/environment.ts index 8dea492..e8f0e46 100644 --- a/src/sdk/environment.ts +++ b/src/sdk/environment.ts @@ -1,76 +1,25 @@ /* - * 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 { HTTPClient } from "../lib/http.js"; +import { environmentGet } from "../funcs/environmentGet.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as z from "zod"; +import { unwrapAsync } from "../types/fp.js"; export class Environment 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$; - } - - /** - * Retrieve the environment variables as added in the Nango dashboard. - * - * @remarks - * Retrieve the environment variables as added in the Nango dashboard - */ - async get(options?: RequestOptions): Promise> { - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const path$ = this.templateURLComponent("/environment-variables")(); - - const query$ = ""; - - const context = { - operationID: "getEnvironmentVariable", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "GET", path: path$, headers: headers$, query: query$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher>() - .json(200, z.array(components.GetEnvironmentVariableResponse$.inboundSchema)) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } + /** + * Retrieve the environment variables as added in the Nango dashboard. + * + * @remarks + * Retrieve the environment variables as added in the Nango dashboard + */ + async get( + options?: RequestOptions, + ): Promise> { + return unwrapAsync(environmentGet( + this, + options, + )); + } } diff --git a/src/sdk/index.ts b/src/sdk/index.ts index 34a84fc..ecac226 100644 --- a/src/sdk/index.ts +++ b/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/src/sdk/integrations.ts b/src/sdk/integrations.ts index 903a613..123aad9 100644 --- a/src/sdk/integrations.ts +++ b/src/sdk/integrations.ts @@ -1,301 +1,99 @@ /* - * 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$, - encodeSimple as encodeSimple$, -} from "../lib/encodings.js"; -import { HTTPClient } from "../lib/http.js"; -import * as schemas$ from "../lib/schemas.js"; +import { integrationsCreate } from "../funcs/integrationsCreate.js"; +import { integrationsDelete } from "../funcs/integrationsDelete.js"; +import { integrationsGet } from "../funcs/integrationsGet.js"; +import { integrationsList } from "../funcs/integrationsList.js"; +import { integrationsUpdate } from "../funcs/integrationsUpdate.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as errors from "../models/errors/index.js"; -import * as operations from "../models/operations/index.js"; -import * as z from "zod"; +import { unwrapAsync } from "../types/fp.js"; export class Integrations 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$; - } - - /** - * Returns a list of integrations including their unique keys and providers as configured in the Nango API. - * - * @remarks - * Returns a list of integrations - */ - async list(options?: RequestOptions): Promise { - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const path$ = this.templateURLComponent("/config")(); - - const query$ = ""; - - const context = { operationID: "listIntegrations", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "GET", path: path$, headers: headers$, query: query$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .json(200, components.IntegrationsResponse200$) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. - * - * @remarks - * Create a new integration - */ - async create( - request: components.ListIntegrationsRequest, - options?: RequestOptions - ): Promise { - const input$ = request; - void input$; // request input is unused - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Content-Type", "application/json"); - headers$.set("Accept", "application/json"); - - const path$ = this.templateURLComponent("/config")(); - - const query$ = ""; - - const context = { - operationID: "createIntegrations", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "POST", path: path$, headers: headers$, query: query$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .json(200, components.IntegrationsResponse200$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. - * - * @remarks - * Edit an integration (only for OAuth APIs) - */ - async update( - request: components.UpdateIntegrationRequest, - options?: RequestOptions - ): Promise { - const input$ = request; - void input$; // request input is unused - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Content-Type", "application/json"); - headers$.set("Accept", "application/json"); - - const path$ = this.templateURLComponent("/config")(); - - const query$ = ""; - - const context = { - operationID: "updateIntegration", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "404", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "PUT", path: path$, headers: headers$, query: query$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .json(200, components.IntegrationsResponse200$) - .json(400, errors.Response400$, { err: true }) - .json(404, errors.Response404$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. - * - * @remarks - * Returns a specific integration - */ - async get( - providerConfigKey: string, - includeCreds?: boolean | undefined, - options?: RequestOptions - ): Promise { - const input$: operations.GetIntegrationRequest = { - providerConfigKey: providerConfigKey, - includeCreds: includeCreds, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.GetIntegrationRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - providerConfigKey: encodeSimple$("providerConfigKey", payload$.providerConfigKey, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/config/{providerConfigKey}")(pathParams$); - - const query$ = encodeFormQuery$({ - include_creds: payload$.include_creds, - }); - - const context = { operationID: "getIntegration", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "404", "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, components.GetIntegrationResponse$) - .json(400, errors.Response400$, { err: true }) - .json(404, errors.Response404$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Deletes a specific integration identified by its provider configuration key. - * - * @remarks - * Deletes a specific integration - */ - async delete(providerConfigKey: string, options?: RequestOptions): Promise { - const input$: operations.DeleteIntegrationRequest = { - providerConfigKey: providerConfigKey, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.DeleteIntegrationRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - providerConfigKey: encodeSimple$("providerConfigKey", payload$.providerConfigKey, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/config/{providerConfigKey}")(pathParams$); - - const query$ = ""; - - const context = { - operationID: "deleteIntegration", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "404", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "DELETE", 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() - .void(204, z.void()) - .json(400, errors.Response400$, { err: true }) - .json(404, errors.Response404$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } + /** + * Returns a list of integrations including their unique keys and providers as configured in the Nango API. + * + * @remarks + * Returns a list of integrations + */ + async list( + options?: RequestOptions, + ): Promise { + return unwrapAsync(integrationsList( + this, + options, + )); + } + + /** + * Create a new integration including its provider configuration, OAuth details if applicable, and associated integration ID. + * + * @remarks + * Create a new integration + */ + async create( + request: components.ListIntegrationsRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(integrationsCreate( + this, + request, + options, + )); + } + + /** + * Edit an integration, specifically tailored for OAuth APIs, updating the provider configuration along with OAuth client ID and secret. + * + * @remarks + * Edit an integration (only for OAuth APIs) + */ + async update( + request: components.UpdateIntegrationRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(integrationsUpdate( + this, + request, + options, + )); + } + + /** + * Returns details of a specific integration identified by its provider configuration key, optionally including credentials if specified. + * + * @remarks + * Returns a specific integration + */ + async get( + providerConfigKey: string, + includeCreds?: boolean | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(integrationsGet( + this, + providerConfigKey, + includeCreds, + options, + )); + } + + /** + * Deletes a specific integration identified by its provider configuration key. + * + * @remarks + * Deletes a specific integration + */ + async delete( + providerConfigKey: string, + options?: RequestOptions, + ): Promise { + return unwrapAsync(integrationsDelete( + this, + providerConfigKey, + options, + )); + } } diff --git a/src/sdk/proxy.ts b/src/sdk/proxy.ts index a88df6c..2bb6d32 100644 --- a/src/sdk/proxy.ts +++ b/src/sdk/proxy.ts @@ -1,486 +1,99 @@ /* - * 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 { proxyCreate } from "../funcs/proxyCreate.js"; +import { proxyDelete } from "../funcs/proxyDelete.js"; +import { proxyGet } from "../funcs/proxyGet.js"; +import { proxyModify } from "../funcs/proxyModify.js"; +import { proxyUpdate } from "../funcs/proxyUpdate.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as operations from "../models/operations/index.js"; -import * as z from "zod"; +import { unwrapAsync } from "../types/fp.js"; export class Proxy 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$; - } - - /** - * Make a GET request with the Proxy. - * - * @remarks - * Make a GET request with the Proxy. - */ - async get(request: operations.GetProxyRequest, options?: RequestOptions): Promise { - const input$ = request; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "*/*"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.GetProxyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - anyPath: encodeSimple$("anyPath", payload$.anyPath, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/proxy/{anyPath}")(pathParams$); - - const query$ = encodeFormQuery$({ - $ANY_QUERY_PARAMS: payload$.$ANY_QUERY_PARAMS, - }); - - headers$.set( - "Base-Url-Override", - encodeSimple$("Base-Url-Override", payload$["Base-Url-Override"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Decompress", - encodeSimple$("Decompress", payload$.Decompress, { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Retries", - encodeSimple$("Retries", payload$.Retries, { explode: false, charEncoding: "none" }) - ); - headers$.set( - "nango-proxy-$ANY_HEADER", - encodeSimple$("nango-proxy-$ANY_HEADER", payload$["nango-proxy-$ANY_HEADER"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "getProxy", 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() - .void(200, z.void()) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Make a POST request with the Proxy. - * - * @remarks - * Make a POST request with the Proxy. - */ - async create(request: operations.CreateProxyRequest, 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", "*/*"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.CreateProxyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.CreateProxyRequest, { explode: true }); - - const pathParams$ = { - anyPath: encodeSimple$("anyPath", payload$.anyPath, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/proxy/{anyPath}")(pathParams$); - - const query$ = ""; - - headers$.set( - "Base-Url-Override", - encodeSimple$("Base-Url-Override", payload$["Base-Url-Override"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Decompress", - encodeSimple$("Decompress", payload$.Decompress, { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Retries", - encodeSimple$("Retries", payload$.Retries, { explode: false, charEncoding: "none" }) - ); - headers$.set( - "nango-proxy-$ANY_HEADER", - encodeSimple$("nango-proxy-$ANY_HEADER", payload$["nango-proxy-$ANY_HEADER"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "createProxy", 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(200, z.void()) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Make a PUT request with the Proxy. - * - * @remarks - * Make a PUT request with the Proxy. - */ - async update(request: operations.PutProxyRequest, 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", "*/*"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.PutProxyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.PutProxyRequest, { explode: true }); - - const pathParams$ = { - anyPath: encodeSimple$("anyPath", payload$.anyPath, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/proxy/{anyPath}")(pathParams$); - - const query$ = ""; - - headers$.set( - "Base-Url-Override", - encodeSimple$("Base-Url-Override", payload$["Base-Url-Override"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Decompress", - encodeSimple$("Decompress", payload$.Decompress, { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Retries", - encodeSimple$("Retries", payload$.Retries, { explode: false, charEncoding: "none" }) - ); - headers$.set( - "nango-proxy-$ANY_HEADER", - encodeSimple$("nango-proxy-$ANY_HEADER", payload$["nango-proxy-$ANY_HEADER"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "putProxy", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "PUT", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .void(200, z.void()) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Make a PATCH request with the Proxy. - * - * @remarks - * Make a PATCH request with the Proxy. - */ - async modify(request: operations.PatchProxyRequest, 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", "*/*"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.PatchProxyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$.PatchProxyRequest, { explode: true }); - - const pathParams$ = { - anyPath: encodeSimple$("anyPath", payload$.anyPath, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/proxy/{anyPath}")(pathParams$); - - const query$ = ""; - - headers$.set( - "Base-Url-Override", - encodeSimple$("Base-Url-Override", payload$["Base-Url-Override"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Decompress", - encodeSimple$("Decompress", payload$.Decompress, { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Retries", - encodeSimple$("Retries", payload$.Retries, { explode: false, charEncoding: "none" }) - ); - headers$.set( - "nango-proxy-$ANY_HEADER", - encodeSimple$("nango-proxy-$ANY_HEADER", payload$["nango-proxy-$ANY_HEADER"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "patchProxy", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "PATCH", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .void(200, z.void()) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } - - /** - * Make a DELETE request with the Proxy. - * - * @remarks - * Make a DELETE request with the Proxy. - */ - async delete(request: operations.DeleteProxyRequest, options?: RequestOptions): Promise { - const input$ = request; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "*/*"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.DeleteProxyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const pathParams$ = { - anyPath: encodeSimple$("anyPath", payload$.anyPath, { - explode: false, - charEncoding: "percent", - }), - }; - const path$ = this.templateURLComponent("/proxy/{anyPath}")(pathParams$); - - const query$ = encodeFormQuery$({ - $ANY_QUERY_PARAMS: payload$.$ANY_QUERY_PARAMS, - }); - - headers$.set( - "Base-Url-Override", - encodeSimple$("Base-Url-Override", payload$["Base-Url-Override"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Decompress", - encodeSimple$("Decompress", payload$.Decompress, { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Retries", - encodeSimple$("Retries", payload$.Retries, { explode: false, charEncoding: "none" }) - ); - headers$.set( - "nango-proxy-$ANY_HEADER", - encodeSimple$("nango-proxy-$ANY_HEADER", payload$["nango-proxy-$ANY_HEADER"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "deleteProxy", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "DELETE", path: path$, headers: headers$, query: query$, body: body$ }, - options - ); - - const response = await this.do$(request$, doOptions); - - const [result$] = await this.matcher() - .void(200, z.void()) - .fail(["4XX", "5XX"]) - .match(response); - - return result$; - } + /** + * Make a GET request with the Proxy. + * + * @remarks + * Make a GET request with the Proxy. + */ + async get( + request: operations.GetProxyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(proxyGet( + this, + request, + options, + )); + } + + /** + * Make a POST request with the Proxy. + * + * @remarks + * Make a POST request with the Proxy. + */ + async create( + request: operations.CreateProxyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(proxyCreate( + this, + request, + options, + )); + } + + /** + * Make a PUT request with the Proxy. + * + * @remarks + * Make a PUT request with the Proxy. + */ + async update( + request: operations.PutProxyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(proxyUpdate( + this, + request, + options, + )); + } + + /** + * Make a PATCH request with the Proxy. + * + * @remarks + * Make a PATCH request with the Proxy. + */ + async modify( + request: operations.PatchProxyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(proxyModify( + this, + request, + options, + )); + } + + /** + * Make a DELETE request with the Proxy. + * + * @remarks + * Make a DELETE request with the Proxy. + */ + async delete( + request: operations.DeleteProxyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(proxyDelete( + this, + request, + options, + )); + } } diff --git a/src/sdk/records.ts b/src/sdk/records.ts index 0f0f043..23531bf 100644 --- a/src/sdk/records.ts +++ b/src/sdk/records.ts @@ -1,114 +1,28 @@ /* - * 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$, - encodeSimple as encodeSimple$, -} from "../lib/encodings.js"; -import { HTTPClient } from "../lib/http.js"; -import * as schemas$ from "../lib/schemas.js"; +import { recordsGet } from "../funcs/recordsGet.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as errors from "../models/errors/index.js"; import * as operations from "../models/operations/index.js"; +import { unwrapAsync } from "../types/fp.js"; export class Records 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$; - } - - /** - * Returns data synced with Nango Sync, filtered by specified parameters. - * - * @remarks - * Returns data synced with Nango Sync - */ - async get( - request: operations.GetRecordRequest, - 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.GetRecordRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const path$ = this.templateURLComponent("/records")(); - - const query$ = encodeFormQuery$({ - cursor: payload$.cursor, - delta: payload$.delta, - filter: payload$.filter, - limit: payload$.limit, - model: payload$.model, - }); - - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "getRecord", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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, components.GetRecordResponse$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } + /** + * Returns data synced with Nango Sync, filtered by specified parameters. + * + * @remarks + * Returns data synced with Nango Sync + */ + async get( + request: operations.GetRecordRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(recordsGet( + this, + request, + options, + )); + } } diff --git a/src/sdk/sdk.ts b/src/sdk/sdk.ts index 2b4fc4d..1b5f64c 100644 --- a/src/sdk/sdk.ts +++ b/src/sdk/sdk.ts @@ -1,10 +1,7 @@ /* - * 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 { Actions } from "./actions.js"; import { Connections } from "./connections.js"; @@ -15,64 +12,38 @@ import { Records } from "./records.js"; import { Sync } from "./sync.js"; export class Nango 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 _integrations?: Integrations; - get integrations(): Integrations { - return (this._integrations ??= new Integrations(this.options$)); - } - - private _connections?: Connections; - get connections(): Connections { - return (this._connections ??= new Connections(this.options$)); - } - - private _records?: Records; - get records(): Records { - return (this._records ??= new Records(this.options$)); - } - - private _sync?: Sync; - get sync(): Sync { - return (this._sync ??= new Sync(this.options$)); - } - - private _actions?: Actions; - get actions(): Actions { - return (this._actions ??= new Actions(this.options$)); - } - - private _environment?: Environment; - get environment(): Environment { - return (this._environment ??= new Environment(this.options$)); - } - - private _proxy?: Proxy; - get proxy(): Proxy { - return (this._proxy ??= new Proxy(this.options$)); - } + private _integrations?: Integrations; + get integrations(): Integrations { + return (this._integrations ??= new Integrations(this._options)); + } + + private _connections?: Connections; + get connections(): Connections { + return (this._connections ??= new Connections(this._options)); + } + + private _records?: Records; + get records(): Records { + return (this._records ??= new Records(this._options)); + } + + private _sync?: Sync; + get sync(): Sync { + return (this._sync ??= new Sync(this._options)); + } + + private _actions?: Actions; + get actions(): Actions { + return (this._actions ??= new Actions(this._options)); + } + + private _environment?: Environment; + get environment(): Environment { + return (this._environment ??= new Environment(this._options)); + } + + private _proxy?: Proxy; + get proxy(): Proxy { + return (this._proxy ??= new Proxy(this._options)); + } } diff --git a/src/sdk/sync.ts b/src/sdk/sync.ts index 6cc422c..0f6e60d 100644 --- a/src/sdk/sync.ts +++ b/src/sdk/sync.ts @@ -1,394 +1,122 @@ /* - * 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 { syncCreateTrigger } from "../funcs/syncCreateTrigger.js"; +import { syncGetRecord } from "../funcs/syncGetRecord.js"; +import { syncGetStatus } from "../funcs/syncGetStatus.js"; +import { syncPause } from "../funcs/syncPause.js"; +import { syncStart } from "../funcs/syncStart.js"; +import { syncUpdateFrequency } from "../funcs/syncUpdateFrequency.js"; import { ClientSDK, RequestOptions } from "../lib/sdks.js"; import * as components from "../models/components/index.js"; -import * as errors from "../models/errors/index.js"; import * as operations from "../models/operations/index.js"; -import * as z from "zod"; +import { unwrapAsync } from "../types/fp.js"; export class Sync 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$; - } - - /** - * Returns data synced with Nango Sync, allowing for advanced filtering, sorting, and pagination options. - * - * @remarks - * Returns data synced with Nango Sync - */ - async getRecord( - request: operations.GetSyncRecordRequest, - 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.GetSyncRecordRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const path$ = this.templateURLComponent("/sync/records")(); - - const query$ = encodeFormQuery$({ - delta: payload$.delta, - filter: payload$.filter, - limit: payload$.limit, - model: payload$.model, - offset: payload$.offset, - order: payload$.order, - sort_by: payload$.sort_by, - }); - - headers$.set( - "Connection-Id", - encodeSimple$("Connection-Id", payload$["Connection-Id"], { - explode: false, - charEncoding: "none", - }) - ); - headers$.set( - "Provider-Config-Key", - encodeSimple$("Provider-Config-Key", payload$["Provider-Config-Key"], { - explode: false, - charEncoding: "none", - }) - ); - const context = { operationID: "getSyncRecord", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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, z.array(components.GetSyncRecordResponse$.inboundSchema)) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Triggers an additional, one-off execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. - * - * @remarks - * Triggers an additional, one-off execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). - */ - async createTrigger( - request?: components.CreateSyncTriggerRequest | undefined, - 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.CreateSyncTriggerRequest$.outboundSchema.optional().parse(value$), - "Input validation failed" - ); - const body$ = - payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); - - const path$ = this.templateURLComponent("/sync/trigger")(); - - const query$ = ""; - - const context = { - operationID: "createSyncTrigger", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "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 responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .void(200, z.void()) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Starts the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. - * - * @remarks - * Starts the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). - */ - async start( - request?: components.CreateSyncStartRequest | undefined, - 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.CreateSyncStartRequest$.outboundSchema.optional().parse(value$), - "Input validation failed" - ); - const body$ = - payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); - - const path$ = this.templateURLComponent("/sync/start")(); - - const query$ = ""; - - const context = { operationID: "createSyncStart", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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 responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .void(200, z.void()) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Pauses the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. - * - * @remarks - * Pauses the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). - */ - async pause( - request?: components.CreateSyncPauseRequest | undefined, - 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.CreateSyncPauseRequest$.outboundSchema.optional().parse(value$), - "Input validation failed" - ); - const body$ = - payload$ === undefined ? null : encodeJSON$("body", payload$, { explode: true }); - - const path$ = this.templateURLComponent("/sync/pause")(); - - const query$ = ""; - - const context = { operationID: "createSyncPause", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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 responseFields$ = { - HttpMeta: { Response: response, Request: request$ }, - }; - - const [result$] = await this.matcher() - .void(200, z.void()) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Get the status of specified sync(s) for a given connection or all applicable connections if no connection is specified. - * - * @remarks - * Get the status of specified sync(s) (for a given connection or all applicable connections if no connection is specified) - */ - async getStatus( - providerConfigKey: string, - syncs: string, - connectionId?: string | undefined, - options?: RequestOptions - ): Promise { - const input$: operations.GetSyncStatusRequest = { - providerConfigKey: providerConfigKey, - syncs: syncs, - connectionId: connectionId, - }; - const headers$ = new Headers(); - headers$.set("user-agent", SDK_METADATA.userAgent); - headers$.set("Accept", "application/json"); - - const payload$ = schemas$.parse( - input$, - (value$) => operations.GetSyncStatusRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = null; - - const path$ = this.templateURLComponent("/sync/status")(); - - const query$ = encodeFormQuery$({ - connection_id: payload$.connection_id, - provider_config_key: payload$.provider_config_key, - syncs: payload$.syncs, - }); - - const context = { operationID: "getSyncStatus", oAuth2Scopes: [], securitySource: null }; - - const doOptions = { context, errorCodes: ["400", "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, components.GetSyncStatusResponse$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } - - /** - * Override a sync's default frequency for a specific connection or revert to the default frequency. - * - * @remarks - * Override a sync's default frequency for a specific connection, or revert to the default frequency. - */ - async updateFrequency( - request: components.UpdateConnectionFrequencyRequest, - 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.UpdateConnectionFrequencyRequest$.outboundSchema.parse(value$), - "Input validation failed" - ); - const body$ = encodeJSON$("body", payload$, { explode: true }); - - const path$ = this.templateURLComponent("/sync/update-connection-frequency")(); - - const query$ = ""; - - const context = { - operationID: "updateConnectionFrequency", - oAuth2Scopes: [], - securitySource: null, - }; - - const doOptions = { context, errorCodes: ["400", "4XX", "5XX"] }; - const request$ = this.createRequest$( - context, - { method: "PUT", 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, components.UpdateConnectionFrequencyResponse$) - .json(400, errors.Response400$, { err: true }) - .fail(["4XX", "5XX"]) - .match(response, { extraFields: responseFields$ }); - - return result$; - } + /** + * Returns data synced with Nango Sync, allowing for advanced filtering, sorting, and pagination options. + * + * @remarks + * Returns data synced with Nango Sync + */ + async getRecord( + request: operations.GetSyncRecordRequest, + options?: RequestOptions, + ): Promise> { + return unwrapAsync(syncGetRecord( + this, + request, + options, + )); + } + + /** + * Triggers an additional, one-off execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Triggers an additional, one-off execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ + async createTrigger( + request?: components.CreateSyncTriggerRequest | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(syncCreateTrigger( + this, + request, + options, + )); + } + + /** + * Starts the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Starts the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ + async start( + request?: components.CreateSyncStartRequest | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(syncStart( + this, + request, + options, + )); + } + + /** + * Pauses the continuous execution of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Pauses the continuous execution of specified sync(s) (for a given connection or all applicable connections if no connection is specified). + */ + async pause( + request?: components.CreateSyncPauseRequest | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(syncPause( + this, + request, + options, + )); + } + + /** + * Get the status of specified sync(s) for a given connection or all applicable connections if no connection is specified. + * + * @remarks + * Get the status of specified sync(s) (for a given connection or all applicable connections if no connection is specified) + */ + async getStatus( + providerConfigKey: string, + syncs: string, + connectionId?: string | undefined, + options?: RequestOptions, + ): Promise { + return unwrapAsync(syncGetStatus( + this, + providerConfigKey, + syncs, + connectionId, + options, + )); + } + + /** + * Override a sync's default frequency for a specific connection or revert to the default frequency. + * + * @remarks + * Override a sync's default frequency for a specific connection, or revert to the default frequency. + */ + async updateFrequency( + request: components.UpdateConnectionFrequencyRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(syncUpdateFrequency( + this, + request, + options, + )); + } } diff --git a/src/types/blobs.ts b/src/types/blobs.ts index cbb8a57..4ce8460 100644 --- a/src/types/blobs.ts +++ b/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/src/types/constdatetime.ts b/src/types/constdatetime.ts new file mode 100644 index 0000000..c0a4409 --- /dev/null +++ b/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/src/types/enums.ts b/src/types/enums.ts index 4de0142..6fb6d91 100644 --- a/src/types/enums.ts +++ b/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/src/types/fp.ts b/src/types/fp.ts new file mode 100644 index 0000000..ccbe51e --- /dev/null +++ b/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/src/types/index.ts b/src/types/index.ts index 374373e..e124e81 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,10 +1,11 @@ /* - * 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"; export { blobLikeSchema, isBlobLike } from "./blobs.js"; -export type { Paginator, PageIterator } from "./operations.js"; -export { createPageIterator } from "./operations.js"; export { catchUnrecognizedEnum } from "./enums.js"; -export type { OpenEnum, ClosedEnum, Unrecognized } from "./enums.js"; +export type { ClosedEnum, OpenEnum, Unrecognized } from "./enums.js"; +export type { Result } from "./fp.js"; +export type { PageIterator, Paginator } from "./operations.js"; +export { createPageIterator } from "./operations.js"; +export { RFCDate } from "./rfcdate.js"; diff --git a/src/types/operations.ts b/src/types/operations.ts index 7f83351..beb81e1 100644 --- a/src/types/operations.ts +++ b/src/types/operations.ts @@ -1,25 +1,105 @@ /* - * 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; + "~next"?: PageState | undefined; }; -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, PageState>>, +): Promise> { + const resultIter = await iteratorPromise; + + if (!resultIter.ok) { + throw resultIter.error; + } + + return { + ...resultIter.value, + next: unwrapPaginator(resultIter.next), + "~next": 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; + }); + }; +} + +export const URL_OVERRIDE = Symbol("URL_OVERRIDE"); diff --git a/src/types/rfcdate.ts b/src/types/rfcdate.ts index e80b693..c79b3f5 100644 --- a/src/types/rfcdate.ts +++ b/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}$/; diff --git a/src/types/streams.ts b/src/types/streams.ts new file mode 100644 index 0000000..a0163e7 --- /dev/null +++ b/src/types/streams.ts @@ -0,0 +1,21 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export function isReadableStream( + val: unknown, +): val is ReadableStream { + if (typeof val !== "object" || val === null) { + return false; + } + + // Check for the presence of methods specific to ReadableStream + const stream = val as ReadableStream; + + // ReadableStream has methods like getReader, cancel, and tee + return ( + typeof stream.getReader === "function" && + typeof stream.cancel === "function" && + typeof stream.tee === "function" + ); +} diff --git a/tsconfig.json b/tsconfig.json index 7a86d2d..94d81a3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,8 +2,9 @@ "compilerOptions": { "incremental": true, "tsBuildInfoFile": ".tsbuildinfo", - "target": "ES2018", + "target": "ES2020", "lib": ["ES2022", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", "module": "Node16", "moduleResolution": "Node16",