diff --git a/.gitattributes b/.gitattributes index 87cd654..113eead 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,11 +1,2 @@ -# -# https://help.github.com/articles/dealing-with-line-endings/ -# -# Linux start script should use lf -/gradlew text eol=lf - -# These are Windows script files and should use crlf -*.bat text eol=crlf - # This allows generated code to be indexed correctly -*.java linguist-generated=false \ No newline at end of file +*.ts linguist-generated=false \ No newline at end of file diff --git a/.gitignore b/.gitignore index cf17584..ccddd9f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,26 @@ -# Ignore Gradle project-specific cache directory -.gradle -# Ignore Gradle build output directory -build -bin/ -# Ignore IDE-specific configs -.project -.settings/ +/models +/models/errors +/types +/node_modules +/lib +/sdk +/funcs +/react-query +/mcp-server +/hooks +/index.* +/core.* +/bin +/cjs +/esm +/dist +/.tsbuildinfo +/.eslintcache +/.tshy +/.tshy-* +/__tests__ .DS_Store **/.speakeasy/temp/ **/.speakeasy/logs/ -.speakeasy/reports +.DS_Store +/.speakeasy/reports diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..cf98a6b --- /dev/null +++ b/.npmignore @@ -0,0 +1,15 @@ +**/* +!/FUNCTIONS.md +!/RUNTIMES.md +!/REACT_QUERY.md +!/**/*.ts +!/**/*.js +!/**/*.mjs +!/**/*.json +!/**/*.map + +/eslint.config.mjs +/cjs +/.tshy +/.tshy-* +/__tests__ diff --git a/FUNCTIONS.md b/FUNCTIONS.md new file mode 100644 index 0000000..103e28f --- /dev/null +++ b/FUNCTIONS.md @@ -0,0 +1,85 @@ +# 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 { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsGetAllData } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsGetAllData.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsGetAllData(scalarGalaxyTypescript, {}); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsGetAllData failed:", res.error); + } +} + +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 157b5f3..70bc80a 100644 --- a/README.md +++ b/README.md @@ -1,125 +1,77 @@ -# openapi +# scalar-galaxy-typescript -Developer-friendly & type-safe Java SDK specifically catered to leverage *openapi* API. +Developer-friendly, idiomatic Typescript SDK for the *scalar-galaxy-typescript* API.
- - + +
+
-

-> [!IMPORTANT] -> This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your [workspace](https://app.speakeasy.com/org/vartana/qwerty). Delete this section before > publishing to a package manager. - - ## Summary -Authlete API Explorer:
-
- -
-
-

- Welcome to the Authlete API documentation. Authlete is an API-first service - where every aspect of the platform is configurable via API. This explorer provides a convenient way to - authenticate and interact with the API, allowing you to see Authlete in action quickly. ๐Ÿš€ -

-

- At a high level, the Authlete API is grouped into two categories: -

-
    -
  • Management APIs: Enable you to manage services and clients. ๐Ÿ”ง
  • -
  • Runtime APIs: Allow you to build your own Authorization Servers or Verifiable Credential (VC) - issuers. ๐Ÿ”
  • -
-

All API endpoints are secured using access tokens issued by Authlete's Identity Provider (IdP). If you already - have an Authlete account, simply use the Get Token option on the Authentication page to log in and obtain - an access token for API usage. If you don't have an account yet, sign up - here to get started.

-
-
-
-

๐ŸŒ API Servers

-

Authlete is a global service with clusters available in multiple regions across the world.

-

Currently, our service is available in the following regions:

-
-
-

๐Ÿ‡บ๐Ÿ‡ธ US

-
-
-

๐Ÿ‡ฏ๐Ÿ‡ต JP

-
-
-

๐Ÿ‡ช๐Ÿ‡บ EU

-
-
-

๐Ÿ‡ง๐Ÿ‡ท Brazil

-
-
-

Our customers can host their data in the region that best meets their requirements.

- Select your - preferred server -
-
-

๐Ÿ”‘ Authentication

-

The API Explorer requires an access token to call the API.

-

You can create the access token from the Authlete Management Console and set it in the HTTP Bearer section of Authentication page.

-

Alternatively, if you have an Authlete account, the API Explorer can log you in with your Authlete account and - automatically acquire the required access token.

-
-
-

โš ๏ธ Important Note: When the API Explorer acquires the token after login, the access tokens - will have the same permissions as the user who logs in as part of this flow.

-
-
- Setup your - access token -
-
-

๐ŸŽ“ Tutorials

-

If you have successfully tested the API from the API Console and want to take the next step of integrating the - API into your application, or if you want to see a sample using Authlete APIs, follow the links below. These - resources will help you understand key concepts and how to integrate Authlete API into your applications.

- -
-
-

๐Ÿ›  Contact Us

-

If you have any questions or need assistance, our team is here to help.

- Contact Page -
-
-
+Scalar Galaxy: The Scalar Galaxy is an example OpenAPI specification to test OpenAPI tools and libraries. Itโ€™s a fictional universe with fictional planets and fictional data. Get all the data for [all planets](#tag/planets/GET/planets). + +## Resources + +* https://github.com/scalar/scalar +* https://github.com/OAI/OpenAPI-Specification +* https://scalar.com + +## Markdown Support + +All descriptions *can* contain ~~tons of text~~ **Markdown**. [If GitHub supports the syntax](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax), chances are weโ€™re supporting it, too. You can even create [internal links to reference endpoints](#tag/authentication/POST/user/signup). + +
+ Examples + + **Blockquotes** + + > I love OpenAPI. <3 + + **Tables** + + | Feature | Availability | + | ---------------- | ------------ | + | Markdown Support | โœ“ | + + **Accordion** + + ```html +
+ Using Details Tags +

HTML Example

+
+ ``` + + **Images** + + Yes, thereโ€™s support for images, too! + + ![Empty placeholder image showing the width/height](https://images.placeholders.dev/?width=1280&height=720) + + **Alerts** + + > [!tip] + > You can now use markdown alerts in your descriptions. + +
+ + +For more information about the API: [Documentation](https://github.com/scalar/scalar) ## Table of Contents -* [openapi](#openapi) - * [SDK Installation](#sdk-installation) - * [SDK Example Usage](#sdk-example-usage) - * [Authentication](#authentication) - * [Available Resources and Operations](#available-resources-and-operations) - * [Error Handling](#error-handling) - * [Server Selection](#server-selection) - * [Debugging](#debugging) +* [@shariqnzr-gmail-com-team/scalar-galaxy-typescript](#shariqnzr-gmail-com-teamscalar-galaxy-typescript) + * [Resources](#resources) + * [Markdown Support](#markdown-support) +* [Note that Yarn does not install peer dependencies automatically. You will need](#note-that-yarn-does-not-install-peer-dependencies-automatically-you-will-need) +* [to install zod as shown above.](#to-install-zod-as-shown-above) * [Development](#development) * [Maturity](#maturity) * [Contributions](#contributions) @@ -129,75 +81,63 @@ Authlete API Explorer:
") - .call(); +run(); - if (res.service().isPresent()) { - // handle response - } - } -} ``` @@ -208,41 +148,34 @@ public class Application { This SDK supports the following security schemes globally: -| Name | Type | Scheme | -| ---------- | ------ | ------------ | -| `authlete` | oauth2 | OAuth2 token | -| `bearer` | http | HTTP Bearer | - -You can set the security parameters through the `security` builder method when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example: -```java -package hello.world; - -import java.lang.Exception; -import org.openapis.openapi.Authelete; -import org.openapis.openapi.models.components.Security; -import org.openapis.openapi.models.errors.1api1infoGetResponses400ContentApplication1jsonSchemaException; -import org.openapis.openapi.models.errors.1api1infoGetResponses400Exception; -import org.openapis.openapi.models.operations.ServiceGetApiResponse; - -public class Application { - - public static void main(String[] args) throws 1api1infoGetResponses400Exception, 1api1infoGetResponses400ContentApplication1jsonSchemaException, 1api1infoGetResponses400ContentApplication1jsonSchemaException, Exception { - - Authelete sdk = Authelete.builder() - .security(Security.builder() - .authlete(System.getenv().getOrDefault("AUTHLETE", "")) - .build()) - .build(); +| Name | Type | Scheme | +| --------------- | ------------- | ------------------------ | +| `bearerAuth` | http | HTTP Bearer | +| `basicAuth` | http | HTTP Basic | +| `apiKeyQuery` | apiKey | API key | +| `apiKeyHeader` | apiKey | API key | +| `apiKeyCookie` | apiKey | API key | +| `oAuth2` | oauth2 | OAuth2 token | +| `openIdConnect` | openIdConnect | OpenID Connect Discovery | + +You can set the security parameters through the `security` optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example: +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript({ + security: { + bearerAuth: "", + }, +}); + +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); + + console.log(result); +} - ServiceGetApiResponse res = sdk.serviceManagement().get() - .serviceId("") - .call(); +run(); - if (res.service().isPresent()) { - // handle response - } - } -} ``` @@ -252,389 +185,348 @@ public class Application {
Available methods +### [authentication](docs/sdks/authentication/README.md) -### [authorization()](docs/sdks/authorization/README.md) - -* [issue](docs/sdks/authorization/README.md#issue) - Issue Authorization Response -* [issueForm](docs/sdks/authorization/README.md#issueform) - Issue Authorization Response -* [processPushedRequest](docs/sdks/authorization/README.md#processpushedrequest) - Process Pushed Authorization Request -* [processPushedRequestForm](docs/sdks/authorization/README.md#processpushedrequestform) - Process Pushed Authorization Request -* [getTicketInfo](docs/sdks/authorization/README.md#getticketinfo) - Get Ticket Information -* [getTicketInfoForm](docs/sdks/authorization/README.md#getticketinfoform) - Get Ticket Information - -### [authorizationEndpoint()](docs/sdks/authorizationendpoint/README.md) - -* [process](docs/sdks/authorizationendpoint/README.md#process) - Process Authorization Request -* [processForm](docs/sdks/authorizationendpoint/README.md#processform) - Process Authorization Request -* [updateTicket](docs/sdks/authorizationendpoint/README.md#updateticket) - Update Ticket Information -* [updateTicketForm](docs/sdks/authorizationendpoint/README.md#updateticketform) - Update Ticket Information - -### [authorizationEndpoints()](docs/sdks/authorizationendpoints/README.md) - -* [failAuthRequest](docs/sdks/authorizationendpoints/README.md#failauthrequest) - Fail Authorization Request -* [failAuthRequestForm](docs/sdks/authorizationendpoints/README.md#failauthrequestform) - Fail Authorization Request - -### [ciba()](docs/sdks/ciba/README.md) - -* [process](docs/sdks/ciba/README.md#process) - Process Backchannel Authentication Request -* [processForm](docs/sdks/ciba/README.md#processform) - Process Backchannel Authentication Request -* [issue](docs/sdks/ciba/README.md#issue) - Issue Backchannel Authentication Response -* [issueForm](docs/sdks/ciba/README.md#issueform) - Issue Backchannel Authentication Response -* [fail](docs/sdks/ciba/README.md#fail) - Fail Backchannel Authentication Request -* [failForm](docs/sdks/ciba/README.md#failform) - Fail Backchannel Authentication Request -* [completeBackchannelAuth](docs/sdks/ciba/README.md#completebackchannelauth) - Complete Backchannel Authentication -* [completeBackchannelAuthForm](docs/sdks/ciba/README.md#completebackchannelauthform) - Complete Backchannel Authentication - -### [clientManagement()](docs/sdks/clientmanagement/README.md) - -* [list](docs/sdks/clientmanagement/README.md#list) - List Clients -* [create](docs/sdks/clientmanagement/README.md#create) - Create Client -* [update](docs/sdks/clientmanagement/README.md#update) - Update Client -* [delete](docs/sdks/clientmanagement/README.md#delete) - Delete Client โšก - -### [clients()](docs/sdks/clients/README.md) - -* [getById](docs/sdks/clients/README.md#getbyid) - Get Client -* [updateLock](docs/sdks/clients/README.md#updatelock) - Update Client Lock -* [updateLockForm](docs/sdks/clients/README.md#updatelockform) - Update Client Lock -* [refreshSecret](docs/sdks/clients/README.md#refreshsecret) - Rotate Client Secret -* [updateSecret](docs/sdks/clients/README.md#updatesecret) - Update Client Secret -* [updateSecretForm](docs/sdks/clients/README.md#updatesecretform) - Update Client Secret -* [getAuthorizedApplications](docs/sdks/clients/README.md#getauthorizedapplications) - Get Authorized Applications -* [updateAuthorization](docs/sdks/clients/README.md#updateauthorization) - Update Client Tokens -* [updateAuthorizationForm](docs/sdks/clients/README.md#updateauthorizationform) - Update Client Tokens -* [deleteAuthorization](docs/sdks/clients/README.md#deleteauthorization) - Delete Client Tokens -* [getGrantedScopes](docs/sdks/clients/README.md#getgrantedscopes) - Get Granted Scopes -* [deleteGrantedScopes](docs/sdks/clients/README.md#deletegrantedscopes) - Delete Granted Scopes -* [register](docs/sdks/clients/README.md#register) - Register Client -* [registerForm](docs/sdks/clients/README.md#registerform) - Register Client -* [get](docs/sdks/clients/README.md#get) - Get Client -* [updateRegistration](docs/sdks/clients/README.md#updateregistration) - Update Client -* [updateRegistrationForm](docs/sdks/clients/README.md#updateregistrationform) - Update Client -* [getRequestableScopes](docs/sdks/clients/README.md#getrequestablescopes) - Get Requestable Scopes -* [updateRequestableScopes](docs/sdks/clients/README.md#updaterequestablescopes) - Update Requestable Scopes -* [deleteRequestableScopes](docs/sdks/clients/README.md#deleterequestablescopes) - Delete Requestable Scopes - -### [credentials()](docs/sdks/credentials/README.md) - -* [issueJwt](docs/sdks/credentials/README.md#issuejwt) - /api/{serviceId}/vci/jwtissuer API -* [issueJwtForm](docs/sdks/credentials/README.md#issuejwtform) - /api/{serviceId}/vci/jwtissuer API -* [issueBatch](docs/sdks/credentials/README.md#issuebatch) - /api/{serviceId}/vci/batch/issue API - -### [deviceFlow()](docs/sdks/deviceflow/README.md) - -* [verify](docs/sdks/deviceflow/README.md#verify) - Process Device Verification Request -* [verifyForm](docs/sdks/deviceflow/README.md#verifyform) - Process Device Verification Request -* [complete](docs/sdks/deviceflow/README.md#complete) - Complete Device Authorization -* [completeForm](docs/sdks/deviceflow/README.md#completeform) - Complete Device Authorization +* [createUserJson](docs/sdks/authentication/README.md#createuserjson) - Create a user +* [createUserRaw](docs/sdks/authentication/README.md#createuserraw) - Create a user +* [getTokenJson](docs/sdks/authentication/README.md#gettokenjson) - Get a token +* [getTokenRaw](docs/sdks/authentication/README.md#gettokenraw) - Get a token +* [getMe](docs/sdks/authentication/README.md#getme) - Get authenticated user -### [devices()](docs/sdks/devices/README.md) +### [planets](docs/sdks/planets/README.md) -* [authorize](docs/sdks/devices/README.md#authorize) - Process Device Authorization Request -* [authorizeForm](docs/sdks/devices/README.md#authorizeform) - Process Device Authorization Request +* [getAllData](docs/sdks/planets/README.md#getalldata) - Get all planets +* [createPlanetJson](docs/sdks/planets/README.md#createplanetjson) - Create a planet +* [createPlanetRaw](docs/sdks/planets/README.md#createplanetraw) - Create a planet +* [getPlanet](docs/sdks/planets/README.md#getplanet) - Get a planet +* [updatePlanetJson](docs/sdks/planets/README.md#updateplanetjson) - Update a planet +* [updatePlanetRaw](docs/sdks/planets/README.md#updateplanetraw) - Update a planet +* [deletePlanet](docs/sdks/planets/README.md#deleteplanet) - Delete a planet +* [uploadImage](docs/sdks/planets/README.md#uploadimage) - Upload an image to a planet -### [dynamicClientRegistration()](docs/sdks/dynamicclientregistration/README.md) -* [delete](docs/sdks/dynamicclientregistration/README.md#delete) - Delete Client -* [deleteForm](docs/sdks/dynamicclientregistration/README.md#deleteform) - Delete Client - -### [federation()](docs/sdks/federation/README.md) - -* [register](docs/sdks/federation/README.md#register) - Process Federation Registration Request -* [registerForm](docs/sdks/federation/README.md#registerform) - Process Federation Registration Request - -### [federations()](docs/sdks/federations/README.md) - -* [postConfiguration](docs/sdks/federations/README.md#postconfiguration) - Process Entity Configuration Request - -### [grantManagementEndpoints()](docs/sdks/grantmanagementendpoints/README.md) +
+ -* [processRequest](docs/sdks/grantmanagementendpoints/README.md#processrequest) - Process Grant Management Request + +## Standalone functions -### [hardwareSecurityKey()](docs/sdks/hardwaresecuritykey/README.md) +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. -* [delete](docs/sdks/hardwaresecuritykey/README.md#delete) - Delete Security Key +To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md). -### [hardwareSecurityKeys()](docs/sdks/hardwaresecuritykeys/README.md) +
-* [create](docs/sdks/hardwaresecuritykeys/README.md#create) - Create Security Key -* [createForm](docs/sdks/hardwaresecuritykeys/README.md#createform) - Create Security Key -* [list](docs/sdks/hardwaresecuritykeys/README.md#list) - List Security Keys +Available standalone functions -### [introspectionEndpoint()](docs/sdks/introspectionendpoint/README.md) +- [`authenticationCreateUserJson`](docs/sdks/authentication/README.md#createuserjson) - Create a user +- [`authenticationCreateUserRaw`](docs/sdks/authentication/README.md#createuserraw) - Create a user +- [`authenticationGetMe`](docs/sdks/authentication/README.md#getme) - Get authenticated user +- [`authenticationGetTokenJson`](docs/sdks/authentication/README.md#gettokenjson) - Get a token +- [`authenticationGetTokenRaw`](docs/sdks/authentication/README.md#gettokenraw) - Get a token +- [`planetsCreatePlanetJson`](docs/sdks/planets/README.md#createplanetjson) - Create a planet +- [`planetsCreatePlanetRaw`](docs/sdks/planets/README.md#createplanetraw) - Create a planet +- [`planetsDeletePlanet`](docs/sdks/planets/README.md#deleteplanet) - Delete a planet +- [`planetsGetAllData`](docs/sdks/planets/README.md#getalldata) - Get all planets +- [`planetsGetPlanet`](docs/sdks/planets/README.md#getplanet) - Get a planet +- [`planetsUpdatePlanetJson`](docs/sdks/planets/README.md#updateplanetjson) - Update a planet +- [`planetsUpdatePlanetRaw`](docs/sdks/planets/README.md#updateplanetraw) - Update a planet +- [`planetsUploadImage`](docs/sdks/planets/README.md#uploadimage) - Upload an image to a planet -* [process](docs/sdks/introspectionendpoint/README.md#process) - Process Introspection Request -* [processForm](docs/sdks/introspectionendpoint/README.md#processform) - Process Introspection Request +
+ -### [introspections()](docs/sdks/introspections/README.md) + +## File uploads -* [process](docs/sdks/introspections/README.md#process) - Process OAuth 2.0 Introspection Request -* [processForm](docs/sdks/introspections/README.md#processform) - Process OAuth 2.0 Introspection Request +Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request. -### [joseObject()](docs/sdks/joseobject/README.md) +> [!TIP] +> +> Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory: +> +> - **Node.js v20+:** Since v20, Node.js comes with a native `openAsBlob` function in [`node:fs`](https://nodejs.org/docs/latest-v20.x/api/fs.html#fsopenasblobpath-options). +> - **Bun:** The native [`Bun.file`](https://bun.sh/docs/api/file-io#reading-files-bun-file) function produces a file handle that can be used for streaming file uploads. +> - **Browsers:** All supported browsers return an instance to a [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) when reading the value from an `` element. +> - **Node.js v18:** A file stream can be created using the `fileFrom` helper from [`fetch-blob/from.js`](https://www.npmjs.com/package/fetch-blob). -* [verify](docs/sdks/joseobject/README.md#verify) - Verify JOSE -* [verifyForm](docs/sdks/joseobject/README.md#verifyform) - Verify JOSE +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; -### [jwkSetEndpoint()](docs/sdks/jwksetendpoint/README.md) +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); -* [get](docs/sdks/jwksetendpoint/README.md#get) - Get JWK Set +async function run() { + const result = await scalarGalaxyTypescript.planets.createPlanetRaw( + bytesToStream( + new TextEncoder().encode( + "{\"name\":\"Mars\",\"description\":\"The red planet\",\"type\":\"terrestrial\",\"habitabilityIndex\":0.68,\"physicalProperties\":{\"mass\":0.107,\"radius\":0.532,\"gravity\":0.378,\"temperature\":{\"min\":130,\"max\":308,\"average\":210}},\"atmosphere\":[{\"compound\":\"CO2\",\"percentage\":95.3}],\"discoveredAt\":\"1610-01-07T00:00:00Z\",\"image\":\"https://cdn.scalar.com/photos/mars.jpg\",\"satellites\":[{\"name\":\"Phobos\",\"diameter\":22.2}],\"creator\":{\"name\":\"Marc\"},\"tags\":[\"solar-system\",\"rocky\",\"explored\"],\"callbackUrl\":\"https://example.com/webhook\"}", + ), + ), + ); -### [securityKeys()](docs/sdks/securitykeys/README.md) + console.log(result); +} -* [get](docs/sdks/securitykeys/README.md#get) - Get Security Key +run(); -### [serviceManagement()](docs/sdks/servicemanagement/README.md) +``` + + + +## 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 { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}, { + retries: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, + }); + + console.log(result); +} -* [get](docs/sdks/servicemanagement/README.md#get) - Get Service -* [list](docs/sdks/servicemanagement/README.md#list) - List Services -* [getConfiguration](docs/sdks/servicemanagement/README.md#getconfiguration) - Get Service Configuration +run(); -### [services()](docs/sdks/services/README.md) +``` -* [create](docs/sdks/services/README.md#create) - Create Service -* [update](docs/sdks/services/README.md#update) - Update Service -* [delete](docs/sdks/services/README.md#delete) - Delete Service โšก +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 { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript({ + retryConfig: { + strategy: "backoff", + backoff: { + initialInterval: 1, + maxInterval: 50, + exponent: 1.1, + maxElapsedTime: 100, + }, + retryConnectionErrors: false, + }, +}); + +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); + + console.log(result); +} -### [tokenEndpoint()](docs/sdks/tokenendpoint/README.md) +run(); -* [process](docs/sdks/tokenendpoint/README.md#process) - Process Token Request -* [processForm](docs/sdks/tokenendpoint/README.md#processform) - Process Token Request -* [issue](docs/sdks/tokenendpoint/README.md#issue) - Issue Token Response -* [issueForm](docs/sdks/tokenendpoint/README.md#issueform) - Issue Token Response +``` + -### [tokenOperations()](docs/sdks/tokenoperations/README.md) + +## Error Handling -* [delete](docs/sdks/tokenoperations/README.md#delete) - Delete Access Token -* [revoke](docs/sdks/tokenoperations/README.md#revoke) - Revoke Access Token -* [revokeForm](docs/sdks/tokenoperations/README.md#revokeform) - Revoke Access Token +[`ScalarGalaxyTypescriptError`](./src/models/errors/scalargalaxytypescripterror.ts) is the base class for all HTTP error responses. It has the following properties: -### [tokens()](docs/sdks/tokens/README.md) +| Property | Type | Description | +| ------------------- | ---------- | ------------------------------------------------------ | +| `error.message` | `string` | Error message | +| `error.statusCode` | `number` | HTTP response status code eg `404` | +| `error.headers` | `Headers` | HTTP response headers | +| `error.body` | `string` | HTTP body. Can be empty string if no body is returned. | +| `error.rawResponse` | `Response` | Raw HTTP response | -* [fail](docs/sdks/tokens/README.md#fail) - Fail Token Request -* [failForm](docs/sdks/tokens/README.md#failform) - Fail Token Request -* [revoke](docs/sdks/tokens/README.md#revoke) - Process Revocation Request -* [revokeForm](docs/sdks/tokens/README.md#revokeform) - Process Revocation Request -* [reissueId](docs/sdks/tokens/README.md#reissueid) - Reissue ID Token -* [list](docs/sdks/tokens/README.md#list) - List Issued Tokens -* [create](docs/sdks/tokens/README.md#create) - Create Access Token -* [createForm](docs/sdks/tokens/README.md#createform) - Create Access Token -* [update](docs/sdks/tokens/README.md#update) - Update Access Token -* [updateForm](docs/sdks/tokens/README.md#updateform) - Update Access Token +### Example +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; +import * as errors from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/errors"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + try { + const result = await scalarGalaxyTypescript.planets.getAllData({}); + + console.log(result); + } catch (error) { + if (error instanceof errors.ScalarGalaxyTypescriptError) { + console.log(error.message); + console.log(error.statusCode); + console.log(error.body); + console.log(error.headers); + } + } +} -### [userinfo()](docs/sdks/userinfo/README.md) +run(); -* [get](docs/sdks/userinfo/README.md#get) - Process UserInfo Request -* [getForm](docs/sdks/userinfo/README.md#getform) - Process UserInfo Request -* [issue](docs/sdks/userinfo/README.md#issue) - Issue UserInfo Response -* [issueForm](docs/sdks/userinfo/README.md#issueform) - Issue UserInfo Response +``` -### [utilityEndpoints()](docs/sdks/utilityendpoints/README.md) +### Error Classes +**Primary error:** +* [`ScalarGalaxyTypescriptError`](./src/models/errors/scalargalaxytypescripterror.ts): The base class for HTTP error responses. -* [getInfo](docs/sdks/utilityendpoints/README.md#getinfo) - Get Server Metadata -* [echo](docs/sdks/utilityendpoints/README.md#echo) - Echo +
Less common errors (6) -### [vci()](docs/sdks/vci/README.md) +
-* [parseSingle](docs/sdks/vci/README.md#parsesingle) - /api/{serviceId}/vci/single/parse API -* [parseSingleForm](docs/sdks/vci/README.md#parsesingleform) - /api/{serviceId}/vci/single/parse API +**Network errors:** +* [`ConnectionError`](./src/models/errors/httpclienterrors.ts): HTTP client was unable to make a request to a server. +* [`RequestTimeoutError`](./src/models/errors/httpclienterrors.ts): HTTP request timed out due to an AbortSignal signal. +* [`RequestAbortedError`](./src/models/errors/httpclienterrors.ts): HTTP request was aborted by the client. +* [`InvalidRequestError`](./src/models/errors/httpclienterrors.ts): Any input used to create a request is invalid. +* [`UnexpectedClientError`](./src/models/errors/httpclienterrors.ts): Unrecognised or unexpected error. -### [verifiableCredentialIssuer()](docs/sdks/verifiablecredentialissuer/README.md) -* [getMetadata](docs/sdks/verifiablecredentialissuer/README.md#getmetadata) - /api/{serviceId}/vci/metadata API -* [getMetadataForm](docs/sdks/verifiablecredentialissuer/README.md#getmetadataform) - /api/{serviceId}/vci/metadata API -* [postJwks](docs/sdks/verifiablecredentialissuer/README.md#postjwks) - /api/{serviceId}/vci/jwks API -* [postJwksForm](docs/sdks/verifiablecredentialissuer/README.md#postjwksform) - /api/{serviceId}/vci/jwks API -* [createOffer](docs/sdks/verifiablecredentialissuer/README.md#createoffer) - /api/{serviceId}/vci/offer/create API -* [createOfferForm](docs/sdks/verifiablecredentialissuer/README.md#createofferform) - /api/{serviceId}/vci/offer/create API -* [getOfferInfo](docs/sdks/verifiablecredentialissuer/README.md#getofferinfo) - /api/{serviceId}/vci/offer/info API -* [getOfferInfoForm](docs/sdks/verifiablecredentialissuer/README.md#getofferinfoform) - /api/{serviceId}/vci/offer/info API -* [issueSingle](docs/sdks/verifiablecredentialissuer/README.md#issuesingle) - /api/{serviceId}/vci/single/issue API -* [batchParse](docs/sdks/verifiablecredentialissuer/README.md#batchparse) - /api/{serviceId}/vci/batch/parse API -* [batchParseForm](docs/sdks/verifiablecredentialissuer/README.md#batchparseform) - /api/{serviceId}/vci/batch/parse API -* [parseDeferred](docs/sdks/verifiablecredentialissuer/README.md#parsedeferred) - /api/{serviceId}/vci/deferred/parse API -* [parseDeferredForm](docs/sdks/verifiablecredentialissuer/README.md#parsedeferredform) - /api/{serviceId}/vci/deferred/parse API -* [issueDeferred](docs/sdks/verifiablecredentialissuer/README.md#issuedeferred) - /api/{serviceId}/vci/deferred/issue API +**Inherit from [`ScalarGalaxyTypescriptError`](./src/models/errors/scalargalaxytypescripterror.ts)**: +* [`ResponseValidationError`](./src/models/errors/responsevalidationerror.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.
- - - -## Error Handling + -Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception. + +## Server Selection -By default, an API error will throw a `models/errors/APIException` exception. When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective *Errors* tables in SDK docs for more details on possible exception types for each operation. For example, the `get` method throws the following exceptions: +### Select Server by Index -| Error Type | Status Code | Content Type | -| ---------------------------------------------------------------------------- | ----------- | ---------------- | -| models/errors/1api1infoGetResponses400Exception | 400 | application/json | -| models/errors/1api1infoGetResponses400ContentApplication1jsonSchemaException | 401, 403 | application/json | -| models/errors/1api1infoGetResponses400ContentApplication1jsonSchemaException | 500 | application/json | -| models/errors/APIException | 4XX, 5XX | \*/\* | +You can override the default server globally by passing a server index to the `serverIdx: number` 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 indexes associated with the available servers: -### Example +| # | Server | Variables | Description | +| --- | ------------------------------------- | --------------------- | ------------------------------- | +| 0 | `https://galaxy.scalar.com` | | | +| 1 | `{protocol}://void.scalar.com/{path}` | `protocol`
`path` | Responds with your request data | -```java -package hello.world; +If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor: -import java.lang.Exception; -import org.openapis.openapi.Authelete; -import org.openapis.openapi.models.components.Security; -import org.openapis.openapi.models.errors.1api1infoGetResponses400ContentApplication1jsonSchemaException; -import org.openapis.openapi.models.errors.1api1infoGetResponses400Exception; -import org.openapis.openapi.models.operations.ServiceGetApiResponse; +| Variable | Parameter | Supported Values | Default | Description | +| ---------- | --------------------------------- | ---------------- | --------- | ----------- | +| `protocol` | `protocol: models.ServerProtocol` | - `"https"` | `"https"` | | +| `path` | `path: string` | string | `""` | | -public class Application { +#### Example - public static void main(String[] args) throws 1api1infoGetResponses400Exception, 1api1infoGetResponses400ContentApplication1jsonSchemaException, 1api1infoGetResponses400ContentApplication1jsonSchemaException, Exception { +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; - Authelete sdk = Authelete.builder() - .security(Security.builder() - .authlete(System.getenv().getOrDefault("AUTHLETE", "")) - .build()) - .build(); +const scalarGalaxyTypescript = new ScalarGalaxyTypescript({ + serverIdx: 1, + protocol: "https", + path: "18258", +}); - ServiceGetApiResponse res = sdk.serviceManagement().get() - .serviceId("") - .call(); +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); - if (res.service().isPresent()) { - // handle response - } - } + console.log(result); } -``` - - -## Server Selection +run(); -### Select Server by Index +``` -You can override the default server globally using the `.serverIndex(int serverIdx)` builder method 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 indexes associated with the available servers: +### Override Server URL Per-Client -| # | Server | Description | -| --- | ------------------------- | ------------------- | -| 0 | `https://us.authlete.com` | ๐Ÿ‡บ๐Ÿ‡ธ US Cluster | -| 1 | `https://jp.authlete.com` | ๐Ÿ‡ฏ๐Ÿ‡ต Japan Cluster | -| 2 | `https://eu.authlete.com` | ๐Ÿ‡ช๐Ÿ‡บ Europe Cluster | -| 3 | `https://br.authlete.com` | ๐Ÿ‡ง๐Ÿ‡ท Brazil Cluster | +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 { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; -#### Example +const scalarGalaxyTypescript = new ScalarGalaxyTypescript({ + serverURL: "https://void.scalar.com/", +}); -```java -package hello.world; +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); -import java.lang.Exception; -import org.openapis.openapi.Authelete; -import org.openapis.openapi.models.components.Security; -import org.openapis.openapi.models.errors.1api1infoGetResponses400ContentApplication1jsonSchemaException; -import org.openapis.openapi.models.errors.1api1infoGetResponses400Exception; -import org.openapis.openapi.models.operations.ServiceGetApiResponse; + console.log(result); +} -public class Application { +run(); - public static void main(String[] args) throws 1api1infoGetResponses400Exception, 1api1infoGetResponses400ContentApplication1jsonSchemaException, 1api1infoGetResponses400ContentApplication1jsonSchemaException, Exception { +``` + - Authelete sdk = Authelete.builder() - .serverIndex(3) - .security(Security.builder() - .authlete(System.getenv().getOrDefault("AUTHLETE", "")) - .build()) - .build(); + +## Custom HTTP Client - ServiceGetApiResponse res = sdk.serviceManagement().get() - .serviceId("") - .call(); +The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native +[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This +client is a thin wrapper around `fetch` and provides the ability to attach hooks +around the request lifecycle that can be used to modify the request or handle +errors and response. - if (res.service().isPresent()) { - // handle response - } - } -} -``` +The `HTTPClient` constructor takes an optional `fetcher` argument that can be +used to integrate a third-party HTTP client or when writing tests to mock out +the HTTP client and feed in fixtures. -### Override Server URL Per-Client +The following example shows how to use the `"beforeRequest"` hook to to add a +custom header and a timeout to requests and how to use the `"requestError"` hook +to log errors: -The default server can also be overridden globally using the `.serverURL(String serverUrl)` builder method when initializing the SDK client instance. For example: -```java -package hello.world; +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; +import { HTTPClient } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/lib/http"; -import java.lang.Exception; -import org.openapis.openapi.Authelete; -import org.openapis.openapi.models.components.Security; -import org.openapis.openapi.models.errors.1api1infoGetResponses400ContentApplication1jsonSchemaException; -import org.openapis.openapi.models.errors.1api1infoGetResponses400Exception; -import org.openapis.openapi.models.operations.ServiceGetApiResponse; +const httpClient = new HTTPClient({ + // fetcher takes a function that has the same signature as native `fetch`. + fetcher: (request) => { + return fetch(request); + } +}); -public class Application { +httpClient.addHook("beforeRequest", (request) => { + const nextRequest = new Request(request, { + signal: request.signal || AbortSignal.timeout(5000) + }); - public static void main(String[] args) throws 1api1infoGetResponses400Exception, 1api1infoGetResponses400ContentApplication1jsonSchemaException, 1api1infoGetResponses400ContentApplication1jsonSchemaException, Exception { + nextRequest.headers.set("x-custom-header", "custom value"); - Authelete sdk = Authelete.builder() - .serverURL("https://br.authlete.com") - .security(Security.builder() - .authlete(System.getenv().getOrDefault("AUTHLETE", "")) - .build()) - .build(); + return nextRequest; +}); - ServiceGetApiResponse res = sdk.serviceManagement().get() - .serviceId("") - .call(); +httpClient.addHook("requestError", (error, request) => { + console.group("Request Error"); + console.log("Reason:", `${error}`); + console.log("Endpoint:", `${request.method} ${request.url}`); + console.groupEnd(); +}); - if (res.service().isPresent()) { - // handle response - } - } -} +const sdk = new ScalarGalaxyTypescript({ httpClient }); ``` - + ## Debugging -### Debug You can setup your SDK to emit debug logs for SDK requests and responses. -For request and response logging (especially json bodies), call `enableHTTPDebugLogging(boolean)` on the SDK builder like so: -```java -SDK.builder() - .enableHTTPDebugLogging(true) - .build(); -``` -Example output: -``` -Sending request: http://localhost:35123/bearer#global GET -Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]} -Received response: (GET http://localhost:35123/bearer#global) 200 -Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]} -Response body: -{ - "authenticated": true, - "token": "global" -} -``` -__WARNING__: This should only used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via `SpeakeasyHTTPClient.setRedactedHeaders`. - -__NOTE__: This is a convenience method that calls `HTTPClient.enableDebugLogging()`. The `SpeakeasyHTTPClient` honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting. - -Another option is to set the System property `-Djdk.httpclient.HttpClient.log=all`. However, this second option does not log bodies. - +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. -# Development +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; -## Maturity - -This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage -to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally -looking for the latest version. +const sdk = new ScalarGalaxyTypescript({ debugLogger: console }); +``` + ## Contributions While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. -We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release. +We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release. -### SDK Created by [Speakeasy](https://www.speakeasy.com/?utm_source=openapi&utm_campaign=java) +### SDK Created by [Scalar](https://www.scalar.com/?utm_source=scalar-galaxy-typescript&utm_campaign=typescript) \ No newline at end of file diff --git a/RUNTIMES.md b/RUNTIMES.md new file mode 100644 index 0000000..db7ea94 --- /dev/null +++ b/RUNTIMES.md @@ -0,0 +1,48 @@ +# Supported JavaScript runtimes + +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` +* [Async iterables][async-iter] using `Symbol.asyncIterator` + +[web-fetch]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API +[web-streams]: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API +[async-iter]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols + +Runtime environments that are explicitly supported are: + +- Evergreen browsers which include: Chrome, Safari, Edge, Firefox +- Node.js active and maintenance LTS releases + - Currently, this is v18 and v20 +- Bun v1 and above +- Deno v1.39 + - 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 dce2f77..9deb558 100644 --- a/USAGE.md +++ b/USAGE.md @@ -1,32 +1,16 @@ -```java -package hello.world; +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; -import java.lang.Exception; -import org.openapis.openapi.Authelete; -import org.openapis.openapi.models.components.Security; -import org.openapis.openapi.models.errors.1api1infoGetResponses400ContentApplication1jsonSchemaException; -import org.openapis.openapi.models.errors.1api1infoGetResponses400Exception; -import org.openapis.openapi.models.operations.ServiceGetApiResponse; +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); -public class Application { +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); - public static void main(String[] args) throws 1api1infoGetResponses400Exception, 1api1infoGetResponses400ContentApplication1jsonSchemaException, 1api1infoGetResponses400ContentApplication1jsonSchemaException, Exception { - - Authelete sdk = Authelete.builder() - .security(Security.builder() - .authlete(System.getenv().getOrDefault("AUTHLETE", "")) - .build()) - .build(); + console.log(result); +} - ServiceGetApiResponse res = sdk.serviceManagement().get() - .serviceId("") - .call(); +run(); - if (res.service().isPresent()) { - // handle response - } - } -} ``` \ No newline at end of file diff --git a/code-samples.yaml b/code-samples.yaml new file mode 100644 index 0000000..c940ccf --- /dev/null +++ b/code-samples.yaml @@ -0,0 +1,80 @@ +overlay: 1.0.0 +info: + title: CodeSamples overlay for typescript target + version: 0.0.0 +actions: + - target: $["paths"]["/auth/token"]["post"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "getToken_json" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.authentication.getTokenJson({\n email: \"marc@scalar.com\",\n password: \"i-love-scalar\",\n });\n\n console.log(result);\n}\n\nrun();" + - "lang": "typescript" + "label": "getToken_raw" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.authentication.getTokenRaw(bytesToStream(new TextEncoder().encode(\"{\\\"email\\\":\\\"marc@scalar.com\\\",\\\"password\\\":\\\"i-love-scalar\\\"}\")));\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/me"]["get"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "getMe" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.authentication.getMe();\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/planets"]["get"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "getAllData" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.getAllData({});\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/planets"]["post"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "createPlanet_json" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.createPlanetJson({\n name: \"Mars\",\n description: \"The red planet\",\n type: \"terrestrial\",\n habitabilityIndex: 0.68,\n physicalProperties: {\n mass: 0.107,\n radius: 0.532,\n gravity: 0.378,\n temperature: {\n min: 130,\n max: 308,\n average: 210,\n },\n },\n atmosphere: [\n {\n compound: \"CO2\",\n percentage: 95.3,\n },\n ],\n discoveredAt: new Date(\"1610-01-07T00:00:00Z\"),\n image: \"https://cdn.scalar.com/photos/mars.jpg\",\n satellites: [\n {\n name: \"Phobos\",\n diameter: 22.2,\n },\n ],\n creator: {\n name: \"Marc\",\n },\n tags: [\n \"solar-system\",\n \"rocky\",\n \"explored\",\n ],\n callbackUrl: \"https://example.com/webhook\",\n });\n\n console.log(result);\n}\n\nrun();" + - "lang": "typescript" + "label": "createPlanet_raw" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.createPlanetRaw(bytesToStream(new TextEncoder().encode(\"{\\\"name\\\":\\\"Mars\\\",\\\"description\\\":\\\"The red planet\\\",\\\"type\\\":\\\"terrestrial\\\",\\\"habitabilityIndex\\\":0.68,\\\"physicalProperties\\\":{\\\"mass\\\":0.107,\\\"radius\\\":0.532,\\\"gravity\\\":0.378,\\\"temperature\\\":{\\\"min\\\":130,\\\"max\\\":308,\\\"average\\\":210}},\\\"atmosphere\\\":[{\\\"compound\\\":\\\"CO2\\\",\\\"percentage\\\":95.3}],\\\"discoveredAt\\\":\\\"1610-01-07T00:00:00Z\\\",\\\"image\\\":\\\"https://cdn.scalar.com/photos/mars.jpg\\\",\\\"satellites\\\":[{\\\"name\\\":\\\"Phobos\\\",\\\"diameter\\\":22.2}],\\\"creator\\\":{\\\"name\\\":\\\"Marc\\\"},\\\"tags\\\":[\\\"solar-system\\\",\\\"rocky\\\",\\\"explored\\\"],\\\"callbackUrl\\\":\\\"https://example.com/webhook\\\"}\")));\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/planets/{planetId}"]["delete"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "deletePlanet" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n await scalarGalaxyTypescript.planets.deletePlanet({\n planetId: 1,\n });\n\n\n}\n\nrun();" + - target: $["paths"]["/planets/{planetId}"]["get"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "getPlanet" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.getPlanet({\n planetId: 1,\n });\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/planets/{planetId}"]["put"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "updatePlanet_json" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.updatePlanetJson({\n planetId: 1,\n planet: {\n name: \"Mars\",\n description: \"The red planet\",\n type: \"terrestrial\",\n habitabilityIndex: 0.68,\n physicalProperties: {\n mass: 0.107,\n radius: 0.532,\n gravity: 0.378,\n temperature: {\n min: 130,\n max: 308,\n average: 210,\n },\n },\n atmosphere: [\n {\n compound: \"CO2\",\n percentage: 95.3,\n },\n ],\n discoveredAt: new Date(\"1610-01-07T00:00:00Z\"),\n image: \"https://cdn.scalar.com/photos/mars.jpg\",\n satellites: [\n {\n name: \"Phobos\",\n diameter: 22.2,\n },\n ],\n creator: {\n name: \"Marc\",\n },\n tags: [\n \"solar-system\",\n \"rocky\",\n \"explored\",\n ],\n callbackUrl: \"https://example.com/webhook\",\n },\n });\n\n console.log(result);\n}\n\nrun();" + - "lang": "typescript" + "label": "updatePlanet_raw" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.updatePlanetRaw({\n planetId: 1,\n planet: bytesToStream(new TextEncoder().encode(\"{\\\"name\\\":\\\"Mars\\\",\\\"description\\\":\\\"The red planet\\\",\\\"type\\\":\\\"terrestrial\\\",\\\"habitabilityIndex\\\":0.68,\\\"physicalProperties\\\":{\\\"mass\\\":0.107,\\\"radius\\\":0.532,\\\"gravity\\\":0.378,\\\"temperature\\\":{\\\"min\\\":130,\\\"max\\\":308,\\\"average\\\":210}},\\\"atmosphere\\\":[{\\\"compound\\\":\\\"CO2\\\",\\\"percentage\\\":95.3}],\\\"discoveredAt\\\":\\\"1610-01-07T00:00:00Z\\\",\\\"image\\\":\\\"https://cdn.scalar.com/photos/mars.jpg\\\",\\\"satellites\\\":[{\\\"name\\\":\\\"Phobos\\\",\\\"diameter\\\":22.2}],\\\"creator\\\":{\\\"name\\\":\\\"Marc\\\"},\\\"tags\\\":[\\\"solar-system\\\",\\\"rocky\\\",\\\"explored\\\"],\\\"callbackUrl\\\":\\\"https://example.com/webhook\\\"}\")),\n });\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/planets/{planetId}/image"]["post"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "uploadImage" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\nimport { openAsBlob } from \"node:fs\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.planets.uploadImage({\n planetId: 1,\n requestBody: {\n image: await openAsBlob(\"example.file\"),\n },\n });\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["/user/signup"]["post"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "createUser_json" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.authentication.createUserJson({\n name: \"Marc\",\n email: \"marc@scalar.com\",\n password: \"i-love-scalar\",\n });\n\n console.log(result);\n}\n\nrun();" + - "lang": "typescript" + "label": "createUser_raw" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n const result = await scalarGalaxyTypescript.authentication.createUserRaw(bytesToStream(new TextEncoder().encode(\"{\\\"name\\\":\\\"Marc\\\",\\\"email\\\":\\\"marc@scalar.com\\\",\\\"password\\\":\\\"i-love-scalar\\\"}\")));\n\n console.log(result);\n}\n\nrun();" + - target: $["paths"]["newPlanet"]["post"] + update: + "x-codeSamples": + - "lang": "typescript" + "label": "newPlanet_json" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n await scalarGalaxyTypescript.planets.newPlanetJson({\n name: \"Mars\",\n description: \"The red planet\",\n type: \"terrestrial\",\n habitabilityIndex: 0.68,\n physicalProperties: {\n mass: 0.107,\n radius: 0.532,\n gravity: 0.378,\n temperature: {\n min: 130,\n max: 308,\n average: 210,\n },\n },\n atmosphere: [\n {\n compound: \"CO2\",\n percentage: 95.3,\n },\n ],\n discoveredAt: new Date(\"1610-01-07T00:00:00Z\"),\n image: \"https://cdn.scalar.com/photos/mars.jpg\",\n satellites: [\n {\n name: \"Phobos\",\n diameter: 22.2,\n },\n ],\n creator: {\n name: \"Marc\",\n },\n tags: [\n \"solar-system\",\n \"rocky\",\n \"explored\",\n ],\n callbackUrl: \"https://example.com/webhook\",\n });\n\n\n}\n\nrun();" + - "lang": "typescript" + "label": "newPlanet_raw" + "source": "import { ScalarGalaxyTypescript } from \"@shariqnzr-gmail-com-team/scalar-galaxy-typescript\";\n\nconst scalarGalaxyTypescript = new ScalarGalaxyTypescript();\n\nasync function run() {\n await scalarGalaxyTypescript.planets.newPlanetRaw(bytesToStream(new TextEncoder().encode(\"{\\\"name\\\":\\\"Mars\\\",\\\"description\\\":\\\"The red planet\\\",\\\"type\\\":\\\"terrestrial\\\",\\\"habitabilityIndex\\\":0.68,\\\"physicalProperties\\\":{\\\"mass\\\":0.107,\\\"radius\\\":0.532,\\\"gravity\\\":0.378,\\\"temperature\\\":{\\\"min\\\":130,\\\"max\\\":308,\\\"average\\\":210}},\\\"atmosphere\\\":[{\\\"compound\\\":\\\"CO2\\\",\\\"percentage\\\":95.3}],\\\"discoveredAt\\\":\\\"1610-01-07T00:00:00Z\\\",\\\"image\\\":\\\"https://cdn.scalar.com/photos/mars.jpg\\\",\\\"satellites\\\":[{\\\"name\\\":\\\"Phobos\\\",\\\"diameter\\\":22.2}],\\\"creator\\\":{\\\"name\\\":\\\"Marc\\\"},\\\"tags\\\":[\\\"solar-system\\\",\\\"rocky\\\",\\\"explored\\\"],\\\"callbackUrl\\\":\\\"https://example.com/webhook\\\"}\")));\n\n\n}\n\nrun();" 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/atmosphere.md b/docs/models/components/atmosphere.md new file mode 100644 index 0000000..f34378a --- /dev/null +++ b/docs/models/components/atmosphere.md @@ -0,0 +1,19 @@ +# Atmosphere + +## Example Usage + +```typescript +import { Atmosphere } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Atmosphere = { + compound: "CO2", + percentage: 95.3, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `compound` | *string* | :heavy_minus_sign: | N/A | CO2 | +| `percentage` | *number* | :heavy_minus_sign: | N/A | 95.3 | \ No newline at end of file diff --git a/docs/models/components/credentials.md b/docs/models/components/credentials.md new file mode 100644 index 0000000..34832d2 --- /dev/null +++ b/docs/models/components/credentials.md @@ -0,0 +1,21 @@ +# Credentials + +Credentials to authenticate a user + +## Example Usage + +```typescript +import { Credentials } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Credentials = { + email: "marc@scalar.com", + password: "i-love-scalar", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `email` | *string* | :heavy_check_mark: | N/A | marc@scalar.com | +| `password` | *string* | :heavy_check_mark: | N/A | i-love-scalar | \ No newline at end of file diff --git a/docs/models/components/imageuploadedmessage.md b/docs/models/components/imageuploadedmessage.md new file mode 100644 index 0000000..9b76c82 --- /dev/null +++ b/docs/models/components/imageuploadedmessage.md @@ -0,0 +1,28 @@ +# ImageUploadedMessage + +Message about an image upload + +## Example Usage + +```typescript +import { ImageUploadedMessage } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: ImageUploadedMessage = { + message: "Image uploaded successfully", + imageUrl: + "https://cdn.scalar.com/images/8f47c132-9d1f-4f83-b5a4-91db5ee757ab.jpg", + uploadedAt: new Date("2024-01-15T14:30:00Z"), + fileSize: 1048576, + mimeType: "image/jpeg", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `message` | *string* | :heavy_minus_sign: | N/A | Image uploaded successfully | +| `imageUrl` | *string* | :heavy_minus_sign: | The URL where the uploaded image can be accessed | https://cdn.scalar.com/images/8f47c132-9d1f-4f83-b5a4-91db5ee757ab.jpg | +| `uploadedAt` | [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) | :heavy_minus_sign: | Timestamp when the image was uploaded | 2024-01-15T14:30:00Z | +| `fileSize` | *number* | :heavy_minus_sign: | Size of the uploaded image in bytes | 1048576 | +| `mimeType` | *string* | :heavy_minus_sign: | The content type of the uploaded image | image/jpeg | \ No newline at end of file diff --git a/docs/models/components/physicalproperties.md b/docs/models/components/physicalproperties.md new file mode 100644 index 0000000..900e487 --- /dev/null +++ b/docs/models/components/physicalproperties.md @@ -0,0 +1,27 @@ +# PhysicalProperties + +## Example Usage + +```typescript +import { PhysicalProperties } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: PhysicalProperties = { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `mass` | *number* | :heavy_minus_sign: | Mass in Earth masses | 0.107 | +| `radius` | *number* | :heavy_minus_sign: | Radius in Earth radii | 0.532 | +| `gravity` | *number* | :heavy_minus_sign: | Surface gravity in Earth g | 0.378 | +| `temperature` | [components.Temperature](../../models/components/temperature.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/docs/models/components/planet.md b/docs/models/components/planet.md new file mode 100644 index 0000000..f64cc9f --- /dev/null +++ b/docs/models/components/planet.md @@ -0,0 +1,71 @@ +# Planet + +A planet in the Scalar Galaxy + +## Example Usage + +```typescript +import { Planet } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `id` | *number* | :heavy_check_mark: | N/A | 1 | +| `name` | *string* | :heavy_check_mark: | N/A | Mars | +| `description` | *string* | :heavy_minus_sign: | N/A | The red planet | +| `type` | [components.Type](../../models/components/type.md) | :heavy_minus_sign: | N/A | terrestrial | +| `habitabilityIndex` | *number* | :heavy_minus_sign: | A score from 0 to 1 indicating potential habitability | 0.68 | +| `physicalProperties` | [components.PhysicalProperties](../../models/components/physicalproperties.md) | :heavy_minus_sign: | N/A | | +| `atmosphere` | [components.Atmosphere](../../models/components/atmosphere.md)[] | :heavy_minus_sign: | Atmospheric composition | | +| `discoveredAt` | [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) | :heavy_minus_sign: | N/A | 1610-01-07T00:00:00Z | +| `image` | *string* | :heavy_minus_sign: | N/A | https://cdn.scalar.com/photos/mars.jpg | +| `satellites` | [components.Satellite](../../models/components/satellite.md)[] | :heavy_minus_sign: | N/A | | +| `creator` | [components.User](../../models/components/user.md) | :heavy_minus_sign: | A user | | +| `tags` | *string*[] | :heavy_minus_sign: | N/A | [
"solar-system",
"rocky",
"explored"
] | +| `lastUpdated` | [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) | :heavy_minus_sign: | N/A | 2024-01-15T14:30:00Z | +| `callbackUrl` | *string* | :heavy_minus_sign: | URL to receive notifications about this planet | https://example.com/webhook | \ No newline at end of file diff --git a/docs/models/components/planetinput.md b/docs/models/components/planetinput.md new file mode 100644 index 0000000..f27da71 --- /dev/null +++ b/docs/models/components/planetinput.md @@ -0,0 +1,66 @@ +# PlanetInput + +A planet in the Scalar Galaxy + +## Example Usage + +```typescript +import { PlanetInput } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: PlanetInput = { + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + callbackUrl: "https://example.com/webhook", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| `name` | *string* | :heavy_check_mark: | N/A | Mars | +| `description` | *string* | :heavy_minus_sign: | N/A | The red planet | +| `type` | [components.Type](../../models/components/type.md) | :heavy_minus_sign: | N/A | terrestrial | +| `habitabilityIndex` | *number* | :heavy_minus_sign: | A score from 0 to 1 indicating potential habitability | 0.68 | +| `physicalProperties` | [components.PhysicalProperties](../../models/components/physicalproperties.md) | :heavy_minus_sign: | N/A | | +| `atmosphere` | [components.Atmosphere](../../models/components/atmosphere.md)[] | :heavy_minus_sign: | Atmospheric composition | | +| `discoveredAt` | [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) | :heavy_minus_sign: | N/A | 1610-01-07T00:00:00Z | +| `image` | *string* | :heavy_minus_sign: | N/A | https://cdn.scalar.com/photos/mars.jpg | +| `satellites` | [components.Satellite](../../models/components/satellite.md)[] | :heavy_minus_sign: | N/A | | +| `creator` | [components.UserInput](../../models/components/userinput.md) | :heavy_minus_sign: | A user | | +| `tags` | *string*[] | :heavy_minus_sign: | N/A | [
"solar-system",
"rocky",
"explored"
] | +| `callbackUrl` | *string* | :heavy_minus_sign: | URL to receive notifications about this planet | https://example.com/webhook | \ No newline at end of file diff --git a/docs/models/components/satellite.md b/docs/models/components/satellite.md new file mode 100644 index 0000000..3c187f6 --- /dev/null +++ b/docs/models/components/satellite.md @@ -0,0 +1,21 @@ +# Satellite + +A natural satellite (moon) orbiting a planet + +## Example Usage + +```typescript +import { Satellite } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Satellite = { + name: "Phobos", + diameter: 22.2, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------- | ---------------------- | ---------------------- | ---------------------- | ---------------------- | +| `name` | *string* | :heavy_check_mark: | N/A | Phobos | +| `diameter` | *number* | :heavy_minus_sign: | Diameter in kilometers | 22.2 | \ No newline at end of file diff --git a/docs/models/components/schemebasicauth.md b/docs/models/components/schemebasicauth.md new file mode 100644 index 0000000..6b616bd --- /dev/null +++ b/docs/models/components/schemebasicauth.md @@ -0,0 +1,19 @@ +# SchemeBasicAuth + +## Example Usage + +```typescript +import { SchemeBasicAuth } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: SchemeBasicAuth = { + username: "", + password: "", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `username` | *string* | :heavy_check_mark: | N/A | | +| `password` | *string* | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/docs/models/components/schemeoauth2.md b/docs/models/components/schemeoauth2.md new file mode 100644 index 0000000..74f80e5 --- /dev/null +++ b/docs/models/components/schemeoauth2.md @@ -0,0 +1,20 @@ +# SchemeOAuth2 + +## Example Usage + +```typescript +import { SchemeOAuth2 } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: SchemeOAuth2 = { + clientID: "", + clientSecret: "", +}; +``` + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `clientID` | *string* | :heavy_check_mark: | N/A | +| `clientSecret` | *string* | :heavy_check_mark: | N/A | +| `tokenURL` | *string* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/docs/models/components/security.md b/docs/models/components/security.md new file mode 100644 index 0000000..5f90235 --- /dev/null +++ b/docs/models/components/security.md @@ -0,0 +1,26 @@ +# Security + +## Example Usage + +```typescript +import { Security } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Security = { + basicAuth: { + username: "", + password: "", + }, +}; +``` + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `bearerAuth` | *string* | :heavy_minus_sign: | N/A | +| `basicAuth` | [components.SchemeBasicAuth](../../models/components/schemebasicauth.md) | :heavy_minus_sign: | N/A | +| `apiKeyQuery` | *string* | :heavy_minus_sign: | N/A | +| `apiKeyHeader` | *string* | :heavy_minus_sign: | N/A | +| `apiKeyCookie` | *string* | :heavy_minus_sign: | N/A | +| `oAuth2` | [components.SchemeOAuth2](../../models/components/schemeoauth2.md) | :heavy_minus_sign: | N/A | +| `openIdConnect` | *string* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/components/temperature.md b/docs/models/components/temperature.md new file mode 100644 index 0000000..8b7e0be --- /dev/null +++ b/docs/models/components/temperature.md @@ -0,0 +1,21 @@ +# Temperature + +## Example Usage + +```typescript +import { Temperature } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Temperature = { + min: 130, + max: 308, + average: 210, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------- | ----------------------------- | ----------------------------- | ----------------------------- | ----------------------------- | +| `min` | *number* | :heavy_minus_sign: | Minimum temperature in Kelvin | 130 | +| `max` | *number* | :heavy_minus_sign: | Maximum temperature in Kelvin | 308 | +| `average` | *number* | :heavy_minus_sign: | Average temperature in Kelvin | 210 | \ No newline at end of file diff --git a/docs/models/components/token.md b/docs/models/components/token.md new file mode 100644 index 0000000..d4734f4 --- /dev/null +++ b/docs/models/components/token.md @@ -0,0 +1,20 @@ +# Token + +A token to authenticate a user + +## Example Usage + +```typescript +import { Token } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Token = { + token: + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `token` | *string* | :heavy_minus_sign: | N/A | eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c | \ No newline at end of file diff --git a/docs/models/components/type.md b/docs/models/components/type.md new file mode 100644 index 0000000..ac15ef2 --- /dev/null +++ b/docs/models/components/type.md @@ -0,0 +1,15 @@ +# Type + +## Example Usage + +```typescript +import { Type } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: Type = "terrestrial"; +``` + +## Values + +```typescript +"terrestrial" | "gas_giant" | "ice_giant" | "dwarf" | "super_earth" +``` \ No newline at end of file diff --git a/docs/models/components/user.md b/docs/models/components/user.md new file mode 100644 index 0000000..4378d7d --- /dev/null +++ b/docs/models/components/user.md @@ -0,0 +1,21 @@ +# User + +A user + +## Example Usage + +```typescript +import { User } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: User = { + id: 1, + name: "Marc", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *number* | :heavy_minus_sign: | N/A | 1 | +| `name` | *string* | :heavy_minus_sign: | N/A | Marc | \ No newline at end of file diff --git a/docs/models/components/userinput.md b/docs/models/components/userinput.md new file mode 100644 index 0000000..4d6558a --- /dev/null +++ b/docs/models/components/userinput.md @@ -0,0 +1,19 @@ +# UserInput + +A user + +## Example Usage + +```typescript +import { UserInput } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/components"; + +let value: UserInput = { + name: "Marc", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `name` | *string* | :heavy_minus_sign: | N/A | Marc | \ No newline at end of file diff --git a/docs/models/operations/createplanetjsonresponse.md b/docs/models/operations/createplanetjsonresponse.md new file mode 100644 index 0000000..f11f8c0 --- /dev/null +++ b/docs/models/operations/createplanetjsonresponse.md @@ -0,0 +1,58 @@ +# CreatePlanetJsonResponse + + +## Supported Types + +### `components.Planet` + +```typescript +const value: components.Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/createplanetrawresponse.md b/docs/models/operations/createplanetrawresponse.md new file mode 100644 index 0000000..2969eef --- /dev/null +++ b/docs/models/operations/createplanetrawresponse.md @@ -0,0 +1,58 @@ +# CreatePlanetRawResponse + + +## Supported Types + +### `components.Planet` + +```typescript +const value: components.Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/createuserjsonrequestbody.md b/docs/models/operations/createuserjsonrequestbody.md new file mode 100644 index 0000000..8f212cc --- /dev/null +++ b/docs/models/operations/createuserjsonrequestbody.md @@ -0,0 +1,23 @@ +# CreateUserJsonRequestBody + +Credentials to authenticate a user + +## Example Usage + +```typescript +import { CreateUserJsonRequestBody } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: CreateUserJsonRequestBody = { + name: "Marc", + email: "marc@scalar.com", + password: "i-love-scalar", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `name` | *string* | :heavy_minus_sign: | N/A | Marc | +| `email` | *string* | :heavy_check_mark: | N/A | marc@scalar.com | +| `password` | *string* | :heavy_check_mark: | N/A | i-love-scalar | \ No newline at end of file diff --git a/docs/models/operations/createuserjsonresponse.md b/docs/models/operations/createuserjsonresponse.md new file mode 100644 index 0000000..1336385 --- /dev/null +++ b/docs/models/operations/createuserjsonresponse.md @@ -0,0 +1,20 @@ +# CreateUserJsonResponse + + +## Supported Types + +### `components.User` + +```typescript +const value: components.User = { + id: 1, + name: "Marc", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/createuserrawresponse.md b/docs/models/operations/createuserrawresponse.md new file mode 100644 index 0000000..163f36a --- /dev/null +++ b/docs/models/operations/createuserrawresponse.md @@ -0,0 +1,20 @@ +# CreateUserRawResponse + + +## Supported Types + +### `components.User` + +```typescript +const value: components.User = { + id: 1, + name: "Marc", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/deleteplanetrequest.md b/docs/models/operations/deleteplanetrequest.md new file mode 100644 index 0000000..a531fef --- /dev/null +++ b/docs/models/operations/deleteplanetrequest.md @@ -0,0 +1,17 @@ +# DeletePlanetRequest + +## Example Usage + +```typescript +import { DeletePlanetRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: DeletePlanetRequest = { + planetId: 1, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------- | --------------------------- | --------------------------- | --------------------------- | --------------------------- | +| `planetId` | *number* | :heavy_check_mark: | The ID of the planet to get | 1 | \ No newline at end of file diff --git a/docs/models/operations/getalldatameta.md b/docs/models/operations/getalldatameta.md new file mode 100644 index 0000000..2d32cc7 --- /dev/null +++ b/docs/models/operations/getalldatameta.md @@ -0,0 +1,23 @@ +# GetAllDataMeta + +## Example Usage + +```typescript +import { GetAllDataMeta } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: GetAllDataMeta = { + limit: 10, + offset: 0, + total: 100, + next: "/planets?limit=10&offset=10", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------- | --------------------------- | --------------------------- | --------------------------- | --------------------------- | +| `limit` | *number* | :heavy_minus_sign: | N/A | 10 | +| `offset` | *number* | :heavy_minus_sign: | N/A | 0 | +| `total` | *number* | :heavy_minus_sign: | N/A | 100 | +| `next` | *string* | :heavy_minus_sign: | N/A | /planets?limit=10&offset=10 | \ No newline at end of file diff --git a/docs/models/operations/getalldataplanetsresponsebody.md b/docs/models/operations/getalldataplanetsresponsebody.md new file mode 100644 index 0000000..91ce178 --- /dev/null +++ b/docs/models/operations/getalldataplanetsresponsebody.md @@ -0,0 +1,69 @@ +# GetAllDataPlanetsResponseBody + +A paginated resource + +## Example Usage + +```typescript +import { GetAllDataPlanetsResponseBody } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: GetAllDataPlanetsResponseBody = { + data: [ + { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", + }, + ], + meta: { + limit: 10, + offset: 0, + total: 100, + next: "/planets?limit=10&offset=10", + }, +}; +``` + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `data` | [components.Planet](../../models/components/planet.md)[] | :heavy_minus_sign: | N/A | +| `meta` | [operations.GetAllDataMeta](../../models/operations/getalldatameta.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/getalldatarequest.md b/docs/models/operations/getalldatarequest.md new file mode 100644 index 0000000..e26e279 --- /dev/null +++ b/docs/models/operations/getalldatarequest.md @@ -0,0 +1,16 @@ +# GetAllDataRequest + +## Example Usage + +```typescript +import { GetAllDataRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: GetAllDataRequest = {}; +``` + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `limit` | *number* | :heavy_minus_sign: | The number of items to return | +| `offset` | *number* | :heavy_minus_sign: | The number of items to skip before starting to collect the result set | \ No newline at end of file diff --git a/docs/models/operations/getalldataresponse.md b/docs/models/operations/getalldataresponse.md new file mode 100644 index 0000000..5865b67 --- /dev/null +++ b/docs/models/operations/getalldataresponse.md @@ -0,0 +1,68 @@ +# GetAllDataResponse + + +## Supported Types + +### `operations.GetAllDataResponseBody` + +```typescript +const value: operations.GetAllDataResponseBody = { + data: [ + { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", + }, + ], + meta: { + limit: 10, + offset: 0, + total: 100, + next: "/planets?limit=10&offset=10", + }, +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/getalldataresponsebody.md b/docs/models/operations/getalldataresponsebody.md new file mode 100644 index 0000000..452f26c --- /dev/null +++ b/docs/models/operations/getalldataresponsebody.md @@ -0,0 +1,69 @@ +# GetAllDataResponseBody + +A paginated resource + +## Example Usage + +```typescript +import { GetAllDataResponseBody } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: GetAllDataResponseBody = { + data: [ + { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", + }, + ], + meta: { + limit: 10, + offset: 0, + total: 100, + next: "/planets?limit=10&offset=10", + }, +}; +``` + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `data` | [components.Planet](../../models/components/planet.md)[] | :heavy_minus_sign: | N/A | +| `meta` | [operations.Meta](../../models/operations/meta.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/docs/models/operations/getmeresponse.md b/docs/models/operations/getmeresponse.md new file mode 100644 index 0000000..191f594 --- /dev/null +++ b/docs/models/operations/getmeresponse.md @@ -0,0 +1,20 @@ +# GetMeResponse + + +## Supported Types + +### `components.User` + +```typescript +const value: components.User = { + id: 1, + name: "Marc", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/getplanetrequest.md b/docs/models/operations/getplanetrequest.md new file mode 100644 index 0000000..0b7b5f6 --- /dev/null +++ b/docs/models/operations/getplanetrequest.md @@ -0,0 +1,17 @@ +# GetPlanetRequest + +## Example Usage + +```typescript +import { GetPlanetRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: GetPlanetRequest = { + planetId: 1, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------- | --------------------------- | --------------------------- | --------------------------- | --------------------------- | +| `planetId` | *number* | :heavy_check_mark: | The ID of the planet to get | 1 | \ No newline at end of file diff --git a/docs/models/operations/getplanetresponse.md b/docs/models/operations/getplanetresponse.md new file mode 100644 index 0000000..725877d --- /dev/null +++ b/docs/models/operations/getplanetresponse.md @@ -0,0 +1,58 @@ +# GetPlanetResponse + + +## Supported Types + +### `components.Planet` + +```typescript +const value: components.Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/gettokenjsonresponse.md b/docs/models/operations/gettokenjsonresponse.md new file mode 100644 index 0000000..a903fc5 --- /dev/null +++ b/docs/models/operations/gettokenjsonresponse.md @@ -0,0 +1,20 @@ +# GetTokenJsonResponse + + +## Supported Types + +### `components.Token` + +```typescript +const value: components.Token = { + token: + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/gettokenrawresponse.md b/docs/models/operations/gettokenrawresponse.md new file mode 100644 index 0000000..90e0c2b --- /dev/null +++ b/docs/models/operations/gettokenrawresponse.md @@ -0,0 +1,20 @@ +# GetTokenRawResponse + + +## Supported Types + +### `components.Token` + +```typescript +const value: components.Token = { + token: + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/image.md b/docs/models/operations/image.md new file mode 100644 index 0000000..db9515f --- /dev/null +++ b/docs/models/operations/image.md @@ -0,0 +1,16 @@ +# Image + +## Example Usage + +```typescript +import { Image } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +// No examples available for this model +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- | +| `fileName` | *string* | :heavy_check_mark: | N/A | @mars.jpg | +| `content` | *ReadableStream* | :heavy_check_mark: | N/A | @mars.jpg | \ No newline at end of file diff --git a/docs/models/operations/meta.md b/docs/models/operations/meta.md new file mode 100644 index 0000000..544e907 --- /dev/null +++ b/docs/models/operations/meta.md @@ -0,0 +1,23 @@ +# Meta + +## Example Usage + +```typescript +import { Meta } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: Meta = { + limit: 10, + offset: 0, + total: 100, + next: "/planets?limit=10&offset=10", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------- | --------------------------- | --------------------------- | --------------------------- | --------------------------- | +| `limit` | *number* | :heavy_minus_sign: | N/A | 10 | +| `offset` | *number* | :heavy_minus_sign: | N/A | 0 | +| `total` | *number* | :heavy_minus_sign: | N/A | 100 | +| `next` | *string* | :heavy_minus_sign: | N/A | /planets?limit=10&offset=10 | \ No newline at end of file diff --git a/docs/models/operations/updateplanetjsonrequest.md b/docs/models/operations/updateplanetjsonrequest.md new file mode 100644 index 0000000..091fcda --- /dev/null +++ b/docs/models/operations/updateplanetjsonrequest.md @@ -0,0 +1,18 @@ +# UpdatePlanetJsonRequest + +## Example Usage + +```typescript +import { UpdatePlanetJsonRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +let value: UpdatePlanetJsonRequest = { + planetId: 1, +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `planetId` | *number* | :heavy_check_mark: | The ID of the planet to get | 1 | +| `planet` | [components.PlanetInput](../../models/components/planetinput.md) | :heavy_minus_sign: | New information about the planet | | \ No newline at end of file diff --git a/docs/models/operations/updateplanetjsonresponse.md b/docs/models/operations/updateplanetjsonresponse.md new file mode 100644 index 0000000..9425416 --- /dev/null +++ b/docs/models/operations/updateplanetjsonresponse.md @@ -0,0 +1,58 @@ +# UpdatePlanetJsonResponse + + +## Supported Types + +### `components.Planet` + +```typescript +const value: components.Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/updateplanetrawrequest.md b/docs/models/operations/updateplanetrawrequest.md new file mode 100644 index 0000000..956690b --- /dev/null +++ b/docs/models/operations/updateplanetrawrequest.md @@ -0,0 +1,16 @@ +# UpdatePlanetRawRequest + +## Example Usage + +```typescript +import { UpdatePlanetRawRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +// No examples available for this model +``` + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | +| `planetId` | *number* | :heavy_check_mark: | The ID of the planet to get | 1 | +| `planet` | *ReadableStream* | :heavy_minus_sign: | New information about the planet | | \ No newline at end of file diff --git a/docs/models/operations/updateplanetrawresponse.md b/docs/models/operations/updateplanetrawresponse.md new file mode 100644 index 0000000..4c2548f --- /dev/null +++ b/docs/models/operations/updateplanetrawresponse.md @@ -0,0 +1,58 @@ +# UpdatePlanetRawResponse + + +## Supported Types + +### `components.Planet` + +```typescript +const value: components.Planet = { + id: 1, + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + id: 1, + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + lastUpdated: new Date("2024-01-15T14:30:00Z"), + callbackUrl: "https://example.com/webhook", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/models/operations/uploadimagerequest.md b/docs/models/operations/uploadimagerequest.md new file mode 100644 index 0000000..cc50b9e --- /dev/null +++ b/docs/models/operations/uploadimagerequest.md @@ -0,0 +1,16 @@ +# UploadImageRequest + +## Example Usage + +```typescript +import { UploadImageRequest } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +// No examples available for this model +``` + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `planetId` | *number* | :heavy_check_mark: | The ID of the planet to get | 1 | +| `requestBody` | [operations.UploadImageRequestBody](../../models/operations/uploadimagerequestbody.md) | :heavy_minus_sign: | Image to upload | | \ No newline at end of file diff --git a/docs/models/operations/uploadimagerequestbody.md b/docs/models/operations/uploadimagerequestbody.md new file mode 100644 index 0000000..c156860 --- /dev/null +++ b/docs/models/operations/uploadimagerequestbody.md @@ -0,0 +1,17 @@ +# UploadImageRequestBody + +Image to upload + +## Example Usage + +```typescript +import { UploadImageRequestBody } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/models/operations"; + +// No examples available for this model +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `image` | [File](https://developer.mozilla.org/en-US/docs/Web/API/File) \| [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) \| [operations.Image](../../models/operations/image.md) | :heavy_minus_sign: | The image file to upload | @mars.jpg | \ No newline at end of file diff --git a/docs/models/operations/uploadimageresponse.md b/docs/models/operations/uploadimageresponse.md new file mode 100644 index 0000000..30365e7 --- /dev/null +++ b/docs/models/operations/uploadimageresponse.md @@ -0,0 +1,24 @@ +# UploadImageResponse + + +## Supported Types + +### `components.ImageUploadedMessage` + +```typescript +const value: components.ImageUploadedMessage = { + message: "Image uploaded successfully", + imageUrl: + "https://cdn.scalar.com/images/8f47c132-9d1f-4f83-b5a4-91db5ee757ab.jpg", + uploadedAt: new Date("2024-01-15T14:30:00Z"), + fileSize: 1048576, + mimeType: "image/jpeg", +}; +``` + +### `Uint8Array` + +```typescript +const value: Uint8Array = new TextEncoder().encode("0xdC7D3f4be0"); +``` + diff --git a/docs/sdks/authentication/README.md b/docs/sdks/authentication/README.md new file mode 100644 index 0000000..1dec537 --- /dev/null +++ b/docs/sdks/authentication/README.md @@ -0,0 +1,347 @@ +# Authentication +(*authentication*) + +## Overview + +Some endpoints are public, but some require authentication. We provide all the required endpoints to create an account and authorize yourself. + +### Available Operations + +* [createUserJson](#createuserjson) - Create a user +* [createUserRaw](#createuserraw) - Create a user +* [getTokenJson](#gettokenjson) - Get a token +* [getTokenRaw](#gettokenraw) - Get a token +* [getMe](#getme) - Get authenticated user + +## createUserJson + +Time to create a user account, eh? + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.authentication.createUserJson({ + name: "Marc", + email: "marc@scalar.com", + password: "i-love-scalar", + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { authenticationCreateUserJson } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/authenticationCreateUserJson.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await authenticationCreateUserJson(scalarGalaxyTypescript, { + name: "Marc", + email: "marc@scalar.com", + password: "i-love-scalar", + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("authenticationCreateUserJson failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.CreateUserJsonRequestBody](../../models/operations/createuserjsonrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.CreateUserJsonResponse](../../models/operations/createuserjsonresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## createUserRaw + +Time to create a user account, eh? + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.authentication.createUserRaw(bytesToStream(new TextEncoder().encode("{\"name\":\"Marc\",\"email\":\"marc@scalar.com\",\"password\":\"i-love-scalar\"}"))); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { authenticationCreateUserRaw } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/authenticationCreateUserRaw.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await authenticationCreateUserRaw(scalarGalaxyTypescript, bytesToStream(new TextEncoder().encode("{\"name\":\"Marc\",\"email\":\"marc@scalar.com\",\"password\":\"i-love-scalar\"}"))); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("authenticationCreateUserRaw failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [ReadableStream](../../models/requestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.CreateUserRawResponse](../../models/operations/createuserrawresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## getTokenJson + +Yeah, this is the boring security stuff. Just get your super secret token and move on. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.authentication.getTokenJson({ + email: "marc@scalar.com", + password: "i-love-scalar", + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { authenticationGetTokenJson } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/authenticationGetTokenJson.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await authenticationGetTokenJson(scalarGalaxyTypescript, { + email: "marc@scalar.com", + password: "i-love-scalar", + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("authenticationGetTokenJson failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [components.Credentials](../../models/components/credentials.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.GetTokenJsonResponse](../../models/operations/gettokenjsonresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## getTokenRaw + +Yeah, this is the boring security stuff. Just get your super secret token and move on. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.authentication.getTokenRaw(bytesToStream(new TextEncoder().encode("{\"email\":\"marc@scalar.com\",\"password\":\"i-love-scalar\"}"))); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { authenticationGetTokenRaw } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/authenticationGetTokenRaw.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await authenticationGetTokenRaw(scalarGalaxyTypescript, bytesToStream(new TextEncoder().encode("{\"email\":\"marc@scalar.com\",\"password\":\"i-love-scalar\"}"))); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("authenticationGetTokenRaw failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [ReadableStream](../../models/credentials.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.GetTokenRawResponse](../../models/operations/gettokenrawresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## getMe + +Find yourself they say. Thatโ€™s what you can do here. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.authentication.getMe(); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { authenticationGetMe } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/authenticationGetMe.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await authenticationGetMe(scalarGalaxyTypescript); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("authenticationGetMe failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `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.GetMeResponse](../../models/operations/getmeresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/planets/README.md b/docs/sdks/planets/README.md new file mode 100644 index 0000000..94d82c0 --- /dev/null +++ b/docs/sdks/planets/README.md @@ -0,0 +1,713 @@ +# Planets +(*planets*) + +## Overview + +Everything about planets + +### Available Operations + +* [getAllData](#getalldata) - Get all planets +* [createPlanetJson](#createplanetjson) - Create a planet +* [createPlanetRaw](#createplanetraw) - Create a planet +* [getPlanet](#getplanet) - Get a planet +* [updatePlanetJson](#updateplanetjson) - Update a planet +* [updatePlanetRaw](#updateplanetraw) - Update a planet +* [deletePlanet](#deleteplanet) - Delete a planet +* [uploadImage](#uploadimage) - Upload an image to a planet + +## getAllData + +Itโ€™s easy to say you know them all, but do you really? Retrieve all the planets and check whether you missed one. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.getAllData({}); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsGetAllData } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsGetAllData.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsGetAllData(scalarGalaxyTypescript, {}); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsGetAllData failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetAllDataRequest](../../models/operations/getalldatarequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.GetAllDataResponse](../../models/operations/getalldataresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## createPlanetJson + +Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.createPlanetJson({ + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + callbackUrl: "https://example.com/webhook", + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsCreatePlanetJson } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsCreatePlanetJson.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsCreatePlanetJson(scalarGalaxyTypescript, { + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + callbackUrl: "https://example.com/webhook", + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsCreatePlanetJson failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [components.PlanetInput](../../models/components/planetinput.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.CreatePlanetJsonResponse](../../models/operations/createplanetjsonresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## createPlanetRaw + +Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.createPlanetRaw(bytesToStream(new TextEncoder().encode("{\"name\":\"Mars\",\"description\":\"The red planet\",\"type\":\"terrestrial\",\"habitabilityIndex\":0.68,\"physicalProperties\":{\"mass\":0.107,\"radius\":0.532,\"gravity\":0.378,\"temperature\":{\"min\":130,\"max\":308,\"average\":210}},\"atmosphere\":[{\"compound\":\"CO2\",\"percentage\":95.3}],\"discoveredAt\":\"1610-01-07T00:00:00Z\",\"image\":\"https://cdn.scalar.com/photos/mars.jpg\",\"satellites\":[{\"name\":\"Phobos\",\"diameter\":22.2}],\"creator\":{\"name\":\"Marc\"},\"tags\":[\"solar-system\",\"rocky\",\"explored\"],\"callbackUrl\":\"https://example.com/webhook\"}"))); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsCreatePlanetRaw } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsCreatePlanetRaw.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsCreatePlanetRaw(scalarGalaxyTypescript, bytesToStream(new TextEncoder().encode("{\"name\":\"Mars\",\"description\":\"The red planet\",\"type\":\"terrestrial\",\"habitabilityIndex\":0.68,\"physicalProperties\":{\"mass\":0.107,\"radius\":0.532,\"gravity\":0.378,\"temperature\":{\"min\":130,\"max\":308,\"average\":210}},\"atmosphere\":[{\"compound\":\"CO2\",\"percentage\":95.3}],\"discoveredAt\":\"1610-01-07T00:00:00Z\",\"image\":\"https://cdn.scalar.com/photos/mars.jpg\",\"satellites\":[{\"name\":\"Phobos\",\"diameter\":22.2}],\"creator\":{\"name\":\"Marc\"},\"tags\":[\"solar-system\",\"rocky\",\"explored\"],\"callbackUrl\":\"https://example.com/webhook\"}"))); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsCreatePlanetRaw failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [ReadableStream](../../models/planet.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.CreatePlanetRawResponse](../../models/operations/createplanetrawresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## getPlanet + +Youโ€™ll better learn a little bit more about the planets. It might come in handy once space travel is available for everyone. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.getPlanet({ + planetId: 1, + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsGetPlanet } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsGetPlanet.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsGetPlanet(scalarGalaxyTypescript, { + planetId: 1, + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsGetPlanet failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetPlanetRequest](../../models/operations/getplanetrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.GetPlanetResponse](../../models/operations/getplanetresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## updatePlanetJson + +Sometimes you make mistakes, that's fine. No worries, you can update all planets. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.updatePlanetJson({ + planetId: 1, + planet: { + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + callbackUrl: "https://example.com/webhook", + }, + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsUpdatePlanetJson } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsUpdatePlanetJson.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsUpdatePlanetJson(scalarGalaxyTypescript, { + planetId: 1, + planet: { + name: "Mars", + description: "The red planet", + type: "terrestrial", + habitabilityIndex: 0.68, + physicalProperties: { + mass: 0.107, + radius: 0.532, + gravity: 0.378, + temperature: { + min: 130, + max: 308, + average: 210, + }, + }, + atmosphere: [ + { + compound: "CO2", + percentage: 95.3, + }, + ], + discoveredAt: new Date("1610-01-07T00:00:00Z"), + image: "https://cdn.scalar.com/photos/mars.jpg", + satellites: [ + { + name: "Phobos", + diameter: 22.2, + }, + ], + creator: { + name: "Marc", + }, + tags: [ + "solar-system", + "rocky", + "explored", + ], + callbackUrl: "https://example.com/webhook", + }, + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsUpdatePlanetJson failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UpdatePlanetJsonRequest](../../models/operations/updateplanetjsonrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.UpdatePlanetJsonResponse](../../models/operations/updateplanetjsonresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## updatePlanetRaw + +Sometimes you make mistakes, that's fine. No worries, you can update all planets. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.updatePlanetRaw({ + planetId: 1, + planet: bytesToStream(new TextEncoder().encode("{\"name\":\"Mars\",\"description\":\"The red planet\",\"type\":\"terrestrial\",\"habitabilityIndex\":0.68,\"physicalProperties\":{\"mass\":0.107,\"radius\":0.532,\"gravity\":0.378,\"temperature\":{\"min\":130,\"max\":308,\"average\":210}},\"atmosphere\":[{\"compound\":\"CO2\",\"percentage\":95.3}],\"discoveredAt\":\"1610-01-07T00:00:00Z\",\"image\":\"https://cdn.scalar.com/photos/mars.jpg\",\"satellites\":[{\"name\":\"Phobos\",\"diameter\":22.2}],\"creator\":{\"name\":\"Marc\"},\"tags\":[\"solar-system\",\"rocky\",\"explored\"],\"callbackUrl\":\"https://example.com/webhook\"}")), + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsUpdatePlanetRaw } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsUpdatePlanetRaw.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsUpdatePlanetRaw(scalarGalaxyTypescript, { + planetId: 1, + planet: bytesToStream(new TextEncoder().encode("{\"name\":\"Mars\",\"description\":\"The red planet\",\"type\":\"terrestrial\",\"habitabilityIndex\":0.68,\"physicalProperties\":{\"mass\":0.107,\"radius\":0.532,\"gravity\":0.378,\"temperature\":{\"min\":130,\"max\":308,\"average\":210}},\"atmosphere\":[{\"compound\":\"CO2\",\"percentage\":95.3}],\"discoveredAt\":\"1610-01-07T00:00:00Z\",\"image\":\"https://cdn.scalar.com/photos/mars.jpg\",\"satellites\":[{\"name\":\"Phobos\",\"diameter\":22.2}],\"creator\":{\"name\":\"Marc\"},\"tags\":[\"solar-system\",\"rocky\",\"explored\"],\"callbackUrl\":\"https://example.com/webhook\"}")), + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsUpdatePlanetRaw failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UpdatePlanetRawRequest](../../models/operations/updateplanetrawrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.UpdatePlanetRawResponse](../../models/operations/updateplanetrawresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## deletePlanet + +This endpoint was used to delete planets. Unfortunately, that caused a lot of trouble for planets with life. So, this endpoint is now deprecated and should not be used anymore. + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + await scalarGalaxyTypescript.planets.deletePlanet({ + planetId: 1, + }); + + +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsDeletePlanet } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsDeletePlanet.js"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsDeletePlanet(scalarGalaxyTypescript, { + planetId: 1, + }); + if (res.ok) { + const { value: result } = res; + + } else { + console.log("planetsDeletePlanet failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.DeletePlanetRequest](../../models/operations/deleteplanetrequest.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 Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | + +## uploadImage + +Got a crazy good photo of a planet? Share it with the world! + +### Example Usage + +```typescript +import { ScalarGalaxyTypescript } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript"; +import { openAsBlob } from "node:fs"; + +const scalarGalaxyTypescript = new ScalarGalaxyTypescript(); + +async function run() { + const result = await scalarGalaxyTypescript.planets.uploadImage({ + planetId: 1, + requestBody: { + image: await openAsBlob("example.file"), + }, + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { ScalarGalaxyTypescriptCore } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/core.js"; +import { planetsUploadImage } from "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/funcs/planetsUploadImage.js"; +import { openAsBlob } from "node:fs"; + +// Use `ScalarGalaxyTypescriptCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const scalarGalaxyTypescript = new ScalarGalaxyTypescriptCore(); + +async function run() { + const res = await planetsUploadImage(scalarGalaxyTypescript, { + planetId: 1, + requestBody: { + image: await openAsBlob("example.file"), + }, + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("planetsUploadImage failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UploadImageRequest](../../models/operations/uploadimagerequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `options` | RequestOptions | :heavy_minus_sign: | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | :heavy_minus_sign: | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.md) | :heavy_minus_sign: | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[operations.UploadImageResponse](../../models/operations/uploadimageresponse.md)\>** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.APIError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/docs/sdks/scalargalaxytypescript/README.md b/docs/sdks/scalargalaxytypescript/README.md new file mode 100644 index 0000000..ff0a510 --- /dev/null +++ b/docs/sdks/scalargalaxytypescript/README.md @@ -0,0 +1,56 @@ +# ScalarGalaxyTypescript SDK + +## Overview + +Scalar Galaxy: The Scalar Galaxy is an example OpenAPI specification to test OpenAPI tools and libraries. Itโ€™s a fictional universe with fictional planets and fictional data. Get all the data for [all planets](#tag/planets/GET/planets). + +## Resources + +* https://github.com/scalar/scalar +* https://github.com/OAI/OpenAPI-Specification +* https://scalar.com + +## Markdown Support + +All descriptions *can* contain ~~tons of text~~ **Markdown**. [If GitHub supports the syntax](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax), chances are weโ€™re supporting it, too. You can even create [internal links to reference endpoints](#tag/authentication/POST/user/signup). + +
+ Examples + + **Blockquotes** + + > I love OpenAPI. <3 + + **Tables** + + | Feature | Availability | + | ---------------- | ------------ | + | Markdown Support | โœ“ | + + **Accordion** + + ```html +
+ Using Details Tags +

HTML Example

+
+ ``` + + **Images** + + Yes, thereโ€™s support for images, too! + + ![Empty placeholder image showing the width/height](https://images.placeholders.dev/?width=1280&height=720) + + **Alerts** + + > [!tip] + > You can now use markdown alerts in your descriptions. + +
+ + +Documentation + + +### Available Operations diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..67bccfe --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,22 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; +import tseslint from "typescript-eslint"; + +/** @type {import('eslint').Linter.Config[]} */ +export default [ + { files: ["**/*.{js,mjs,cjs,ts}"] }, + { languageOptions: { globals: globals.browser } }, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, + { + rules: { + "no-constant-condition": "off", + "no-useless-escape": "off", + // Handled by typescript compiler + "@typescript-eslint/no-unused-vars": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-object-type": "off", + "@typescript-eslint/no-namespace": "off", + }, + }, +]; diff --git a/jsr.json b/jsr.json new file mode 100644 index 0000000..e9cfa5e --- /dev/null +++ b/jsr.json @@ -0,0 +1,27 @@ + + +{ + "name": "@shariqnzr-gmail-com-team/scalar-galaxy-typescript", + "version": "1.0.0", + "exports": { + ".": "./src/index.ts", + "./models/errors": "./src/models/errors/index.ts", + "./models/components": "./src/models/components/index.ts", + "./models/operations": "./src/models/operations/index.ts", + "./lib/config": "./src/lib/config.ts", + "./lib/http": "./src/lib/http.ts", + "./lib/retries": "./src/lib/retries.ts", + "./lib/sdks": "./src/lib/sdks.ts", + "./types": "./src/types/index.ts" + }, + "publish": { + "include": [ + "LICENSE", + "README.md", + "RUNTIMES.md", + "USAGE.md", + "jsr.json", + "src/**/*.ts" + ] + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..a80aa3f --- /dev/null +++ b/package.json @@ -0,0 +1,42 @@ +{ + "name": "@shariqnzr-gmail-com-team/scalar-galaxy-typescript", + "version": "1.0.0", + "author": "ShariqnzrGmailComTeam", + "type": "module", + "tshy": { + "sourceDialects": [ + "@shariqnzr-gmail-com-team/scalar-galaxy-typescript/source" + ], + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json", + "./types": "./src/types/index.ts", + "./models/errors": "./src/models/errors/index.ts", + "./models/components": "./src/models/components/index.ts", + "./models/operations": "./src/models/operations/index.ts", + "./*.js": "./src/*.ts", + "./*": "./src/*.ts" + } + }, + "sideEffects": false, + "scripts": { + "lint": "eslint --cache --max-warnings=0 src", + "build": "tshy", + "prepublishOnly": "npm run build" + }, + "peerDependencies": { + "zod": ">= 3" + }, + "devDependencies": { + "@eslint/js": "^9.19.0", + "eslint": "^9.19.0", + "globals": "^15.14.0", + "tshy": "^2.0.0", + "typescript": "^5.4.5", + "typescript-eslint": "^8.22.0", + "zod": "^3.25.17" + }, + "dependencies": { + + } +} diff --git a/src/core.ts b/src/core.ts new file mode 100644 index 0000000..961c5f1 --- /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 ScalarGalaxyTypescriptCore extends ClientSDK {} diff --git a/src/funcs/authenticationCreateUserJson.ts b/src/funcs/authenticationCreateUserJson.ts new file mode 100644 index 0000000..f1d265c --- /dev/null +++ b/src/funcs/authenticationCreateUserJson.ts @@ -0,0 +1,177 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum CreateUserJsonAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Create a user + * + * @remarks + * Time to create a user account, eh? + */ +export function authenticationCreateUserJson( + client: ScalarGalaxyTypescriptCore, + request?: operations.CreateUserJsonRequestBody | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreateUserJsonAcceptEnum; + }, +): APIPromise< + Result< + operations.CreateUserJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: operations.CreateUserJsonRequestBody | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreateUserJsonAcceptEnum; + }, +): Promise< + [ + Result< + operations.CreateUserJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + operations.CreateUserJsonRequestBody$outboundSchema.optional().parse( + value, + ), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/user/signup")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "createUser_json", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "403", "409", "422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.CreateUserJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.CreateUserJsonResponse$inboundSchema), + M.bytes(201, operations.CreateUserJsonResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 401, 403, 409, 422, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/authenticationCreateUserRaw.ts b/src/funcs/authenticationCreateUserRaw.ts new file mode 100644 index 0000000..9efd9fa --- /dev/null +++ b/src/funcs/authenticationCreateUserRaw.ts @@ -0,0 +1,184 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { ScalarGalaxyTypescriptCore } from "../core.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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum CreateUserRawAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Create a user + * + * @remarks + * Time to create a user account, eh? + */ +export function authenticationCreateUserRaw( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { acceptHeaderOverride?: CreateUserRawAcceptEnum }, +): APIPromise< + Result< + operations.CreateUserRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { acceptHeaderOverride?: CreateUserRawAcceptEnum }, +): Promise< + [ + Result< + operations.CreateUserRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined ? null : payload; + + const path = pathToFunc("/user/signup")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/xml", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "createUser_raw", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "403", "409", "422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.CreateUserRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.CreateUserRawResponse$inboundSchema), + M.bytes(201, operations.CreateUserRawResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 401, 403, 409, 422, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/authenticationGetMe.ts b/src/funcs/authenticationGetMe.ts new file mode 100644 index 0000000..2cec857 --- /dev/null +++ b/src/funcs/authenticationGetMe.ts @@ -0,0 +1,150 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } from "../core.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { RequestOptions } from "../lib/sdks.js"; +import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum GetMeAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Get authenticated user + * + * @remarks + * Find yourself they say. Thatโ€™s what you can do here. + */ +export function authenticationGetMe( + client: ScalarGalaxyTypescriptCore, + options?: RequestOptions & { acceptHeaderOverride?: GetMeAcceptEnum }, +): APIPromise< + Result< + operations.GetMeResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + options?: RequestOptions & { acceptHeaderOverride?: GetMeAcceptEnum }, +): Promise< + [ + Result< + operations.GetMeResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const path = pathToFunc("/me")(); + + const headers = new Headers(compactMap({ + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "getMe", + oAuth2Scopes: ["read:account"], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["401", "403", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.GetMeResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.GetMeResponse$inboundSchema), + M.bytes(200, operations.GetMeResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([401, 403, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/authenticationGetTokenJson.ts b/src/funcs/authenticationGetTokenJson.ts new file mode 100644 index 0000000..65e214a --- /dev/null +++ b/src/funcs/authenticationGetTokenJson.ts @@ -0,0 +1,171 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import * as components from "../models/components/index.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum GetTokenJsonAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Get a token + * + * @remarks + * Yeah, this is the boring security stuff. Just get your super secret token and move on. + */ +export function authenticationGetTokenJson( + client: ScalarGalaxyTypescriptCore, + request?: components.Credentials | undefined, + options?: RequestOptions & { acceptHeaderOverride?: GetTokenJsonAcceptEnum }, +): APIPromise< + Result< + operations.GetTokenJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: components.Credentials | undefined, + options?: RequestOptions & { acceptHeaderOverride?: GetTokenJsonAcceptEnum }, +): Promise< + [ + Result< + operations.GetTokenJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => components.Credentials$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/auth/token")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "getToken_json", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "403", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.GetTokenJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.GetTokenJsonResponse$inboundSchema), + M.bytes(201, operations.GetTokenJsonResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 401, 403, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/authenticationGetTokenRaw.ts b/src/funcs/authenticationGetTokenRaw.ts new file mode 100644 index 0000000..6a1e005 --- /dev/null +++ b/src/funcs/authenticationGetTokenRaw.ts @@ -0,0 +1,184 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { ScalarGalaxyTypescriptCore } from "../core.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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum GetTokenRawAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Get a token + * + * @remarks + * Yeah, this is the boring security stuff. Just get your super secret token and move on. + */ +export function authenticationGetTokenRaw( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { acceptHeaderOverride?: GetTokenRawAcceptEnum }, +): APIPromise< + Result< + operations.GetTokenRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { acceptHeaderOverride?: GetTokenRawAcceptEnum }, +): Promise< + [ + Result< + operations.GetTokenRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined ? null : payload; + + const path = pathToFunc("/auth/token")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/xml", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "getToken_raw", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "401", "403", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.GetTokenRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.GetTokenRawResponse$inboundSchema), + M.bytes(201, operations.GetTokenRawResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 401, 403, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsCreatePlanetJson.ts b/src/funcs/planetsCreatePlanetJson.ts new file mode 100644 index 0000000..4e46be1 --- /dev/null +++ b/src/funcs/planetsCreatePlanetJson.ts @@ -0,0 +1,175 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import * as components from "../models/components/index.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum CreatePlanetJsonAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Create a planet + * + * @remarks + * Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + */ +export function planetsCreatePlanetJson( + client: ScalarGalaxyTypescriptCore, + request?: components.PlanetInput | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetJsonAcceptEnum; + }, +): APIPromise< + Result< + operations.CreatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: components.PlanetInput | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetJsonAcceptEnum; + }, +): Promise< + [ + Result< + operations.CreatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => components.PlanetInput$outboundSchema.optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined + ? null + : encodeJSON("body", payload, { explode: true }); + + const path = pathToFunc("/planets")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "createPlanet_json", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "403", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.CreatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.CreatePlanetJsonResponse$inboundSchema), + M.bytes(201, operations.CreatePlanetJsonResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 403, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsCreatePlanetRaw.ts b/src/funcs/planetsCreatePlanetRaw.ts new file mode 100644 index 0000000..932558a --- /dev/null +++ b/src/funcs/planetsCreatePlanetRaw.ts @@ -0,0 +1,188 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { ScalarGalaxyTypescriptCore } from "../core.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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum CreatePlanetRawAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Create a planet + * + * @remarks + * Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + */ +export function planetsCreatePlanetRaw( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetRawAcceptEnum; + }, +): APIPromise< + Result< + operations.CreatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetRawAcceptEnum; + }, +): Promise< + [ + Result< + operations.CreatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => + z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional().parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload === undefined ? null : payload; + + const path = pathToFunc("/planets")(); + + const headers = new Headers(compactMap({ + "Content-Type": "application/xml", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "createPlanet_raw", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "403", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.CreatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(201, operations.CreatePlanetRawResponse$inboundSchema), + M.bytes(201, operations.CreatePlanetRawResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 403, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsDeletePlanet.ts b/src/funcs/planetsDeletePlanet.ts new file mode 100644 index 0000000..b8d78a2 --- /dev/null +++ b/src/funcs/planetsDeletePlanet.ts @@ -0,0 +1,166 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +/** + * Delete a planet + * + * @remarks + * This endpoint was used to delete planets. Unfortunately, that caused a lot of trouble for planets with life. So, this endpoint is now deprecated and should not be used anymore. + */ +export function planetsDeletePlanet( + client: ScalarGalaxyTypescriptCore, + request: operations.DeletePlanetRequest, + options?: RequestOptions, +): APIPromise< + Result< + void, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.DeletePlanetRequest, + options?: RequestOptions, +): Promise< + [ + Result< + void, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.DeletePlanetRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + planetId: encodeSimple("planetId", payload.planetId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/planets/{planetId}")(pathParams); + + const headers = new Headers(compactMap({ + Accept: "*/*", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "deletePlanet", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + void, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.nil(204, z.void()), + M.fail([404, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsGetAllData.ts b/src/funcs/planetsGetAllData.ts new file mode 100644 index 0000000..a7a9f66 --- /dev/null +++ b/src/funcs/planetsGetAllData.ts @@ -0,0 +1,173 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum GetAllDataAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Get all planets + * + * @remarks + * Itโ€™s easy to say you know them all, but do you really? Retrieve all the planets and check whether you missed one. + */ +export function planetsGetAllData( + client: ScalarGalaxyTypescriptCore, + request: operations.GetAllDataRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetAllDataAcceptEnum }, +): APIPromise< + Result< + operations.GetAllDataResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.GetAllDataRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetAllDataAcceptEnum }, +): Promise< + [ + Result< + operations.GetAllDataResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.GetAllDataRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + + const path = pathToFunc("/planets")(); + + const query = encodeFormQuery({ + "limit": payload.limit, + "offset": payload.offset, + }); + + const headers = new Headers(compactMap({ + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "getAllData", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + query: query, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + 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, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.GetAllDataResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.GetAllDataResponse$inboundSchema), + M.bytes(200, operations.GetAllDataResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail("4XX"), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsGetPlanet.ts b/src/funcs/planetsGetPlanet.ts new file mode 100644 index 0000000..12d749b --- /dev/null +++ b/src/funcs/planetsGetPlanet.ts @@ -0,0 +1,174 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum GetPlanetAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Get a planet + * + * @remarks + * Youโ€™ll better learn a little bit more about the planets. It might come in handy once space travel is available for everyone. + */ +export function planetsGetPlanet( + client: ScalarGalaxyTypescriptCore, + request: operations.GetPlanetRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetPlanetAcceptEnum }, +): APIPromise< + Result< + operations.GetPlanetResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.GetPlanetRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetPlanetAcceptEnum }, +): Promise< + [ + Result< + operations.GetPlanetResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.GetPlanetRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + planetId: encodeSimple("planetId", payload.planetId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/planets/{planetId}")(pathParams); + + const headers = new Headers(compactMap({ + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "getPlanet", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.GetPlanetResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.GetPlanetResponse$inboundSchema), + M.bytes(200, operations.GetPlanetResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([404, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsUpdatePlanetJson.ts b/src/funcs/planetsUpdatePlanetJson.ts new file mode 100644 index 0000000..ddb87ec --- /dev/null +++ b/src/funcs/planetsUpdatePlanetJson.ts @@ -0,0 +1,179 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum UpdatePlanetJsonAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Update a planet + * + * @remarks + * Sometimes you make mistakes, that's fine. No worries, you can update all planets. + */ +export function planetsUpdatePlanetJson( + client: ScalarGalaxyTypescriptCore, + request: operations.UpdatePlanetJsonRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetJsonAcceptEnum; + }, +): APIPromise< + Result< + operations.UpdatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.UpdatePlanetJsonRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetJsonAcceptEnum; + }, +): Promise< + [ + Result< + operations.UpdatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.UpdatePlanetJsonRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = encodeJSON("body", payload.Planet, { explode: true }); + + const pathParams = { + planetId: encodeSimple("planetId", payload.planetId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/planets/{planetId}")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/json", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "updatePlanet_json", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "403", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.UpdatePlanetJsonResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.UpdatePlanetJsonResponse$inboundSchema), + M.bytes(200, operations.UpdatePlanetJsonResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 403, 404, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsUpdatePlanetRaw.ts b/src/funcs/planetsUpdatePlanetRaw.ts new file mode 100644 index 0000000..a545c12 --- /dev/null +++ b/src/funcs/planetsUpdatePlanetRaw.ts @@ -0,0 +1,179 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } 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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +export enum UpdatePlanetRawAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Update a planet + * + * @remarks + * Sometimes you make mistakes, that's fine. No worries, you can update all planets. + */ +export function planetsUpdatePlanetRaw( + client: ScalarGalaxyTypescriptCore, + request: operations.UpdatePlanetRawRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetRawAcceptEnum; + }, +): APIPromise< + Result< + operations.UpdatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.UpdatePlanetRawRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetRawAcceptEnum; + }, +): Promise< + [ + Result< + operations.UpdatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.UpdatePlanetRawRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = payload.Planet; + + const pathParams = { + planetId: encodeSimple("planetId", payload.planetId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/planets/{planetId}")(pathParams); + + const headers = new Headers(compactMap({ + "Content-Type": "application/xml", + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "updatePlanet_raw", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "403", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.UpdatePlanetRawResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.UpdatePlanetRawResponse$inboundSchema), + M.bytes(200, operations.UpdatePlanetRawResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 403, 404, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/planetsUploadImage.ts b/src/funcs/planetsUploadImage.ts new file mode 100644 index 0000000..b978ba0 --- /dev/null +++ b/src/funcs/planetsUploadImage.ts @@ -0,0 +1,206 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptCore } from "../core.js"; +import { appendForm, encodeSimple } from "../lib/encodings.js"; +import { + getContentTypeFromFileName, + readableStreamToArrayBuffer, +} from "../lib/files.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 { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ScalarGalaxyTypescriptError } from "../models/errors/scalargalaxytypescripterror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { isBlobLike } from "../types/blobs.js"; +import { Result } from "../types/fp.js"; +import { isReadableStream } from "../types/streams.js"; + +export enum UploadImageAcceptEnum { + applicationJson = "application/json", + applicationXml = "application/xml", +} + +/** + * Upload an image to a planet + * + * @remarks + * Got a crazy good photo of a planet? Share it with the world! + */ +export function planetsUploadImage( + client: ScalarGalaxyTypescriptCore, + request: operations.UploadImageRequest, + options?: RequestOptions & { acceptHeaderOverride?: UploadImageAcceptEnum }, +): APIPromise< + Result< + operations.UploadImageResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: ScalarGalaxyTypescriptCore, + request: operations.UploadImageRequest, + options?: RequestOptions & { acceptHeaderOverride?: UploadImageAcceptEnum }, +): Promise< + [ + Result< + operations.UploadImageResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.UploadImageRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + if (payload.RequestBody != null) { + if (payload.RequestBody.image !== undefined) { + if (isBlobLike(payload.RequestBody.image)) { + appendForm(body, "image", payload.RequestBody.image); + } else if (isReadableStream(payload.RequestBody.image.content)) { + const buffer = await readableStreamToArrayBuffer( + payload.RequestBody.image.content, + ); + const contentType = + getContentTypeFromFileName(payload.RequestBody.image.fileName) + || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + appendForm(body, "image", blob, payload.RequestBody.image.fileName); + } else { + const contentType = + getContentTypeFromFileName(payload.RequestBody.image.fileName) + || "application/octet-stream"; + appendForm( + body, + "image", + new Blob([payload.RequestBody.image.content], { type: contentType }), + payload.RequestBody.image.fileName, + ); + } + } + } + + const pathParams = { + planetId: encodeSimple("planetId", payload.planetId, { + explode: false, + charEncoding: "percent", + }), + }; + + const path = pathToFunc("/planets/{planetId}/image")(pathParams); + + const headers = new Headers(compactMap({ + Accept: options?.acceptHeaderOverride + || "application/json;q=1, application/xml;q=0", + })); + + const securityInput = await extractSecurity(client._options.security); + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "uploadImage", + oAuth2Scopes: [], + + resolvedSecurity: requestSecurity, + + securitySource: client._options.security, + retryConfig: options?.retries + || client._options.retryConfig + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + errorCodes: ["400", "403", "404", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const [result] = await M.match< + operations.UploadImageResponse, + | ScalarGalaxyTypescriptError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, operations.UploadImageResponse$inboundSchema), + M.bytes(200, operations.UploadImageResponse$inboundSchema, { + ctype: "application/xml", + }), + M.fail([400, 403, 404, "4XX"]), + M.fail("5XX"), + )(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/hooks/clientcredentials.ts b/src/hooks/clientcredentials.ts new file mode 100644 index 0000000..fc2525a --- /dev/null +++ b/src/hooks/clientcredentials.ts @@ -0,0 +1,224 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { stringToBase64 } from "../lib/base64.js"; +import { SDKOptions } from "../lib/config.js"; +import { HTTPClient } from "../lib/http.js"; +import { parse } from "../lib/schemas.js"; +import * as components from "../models/components/index.js"; +import { + AfterErrorContext, + AfterErrorHook, + BeforeRequestContext, + BeforeRequestHook, + HookContext, + SDKInitHook, +} from "./types.js"; + +type Credentials = { + clientID: string; + clientSecret: string; + tokenURL: string | undefined; +}; + +type Session = { + credentials: Credentials; + token: string; + expiresAt?: number; + scopes: string[]; +}; + +export class ClientCredentialsHook + implements SDKInitHook, BeforeRequestHook, AfterErrorHook +{ + private client?: HTTPClient; + private sessions: Record = {}; + + sdkInit(opts: SDKOptions): SDKOptions { + this.client = opts.httpClient || new HTTPClient(); + + return opts; + } + + async beforeRequest( + hookCtx: BeforeRequestContext, + request: Request, + ): Promise { + if (!hookCtx.oAuth2Scopes) { + // OAuth2 not in use + return request; + } + + const credentials = await this.getCredentials(hookCtx); + if (!credentials || Object.values(credentials).some(v => v === "")) { + return request; + } + + const sessionKey = this.getSessionKey(credentials); + + let session = this.sessions[sessionKey]; + if ( + !session + || !this.hasRequiredScopes(session.scopes, hookCtx.oAuth2Scopes) + || this.hasTokenExpired(session.expiresAt) + ) { + session = await this.doTokenRequest( + hookCtx, + credentials, + this.getScopes(hookCtx.oAuth2Scopes, session), + ); + + this.sessions[sessionKey] = session; + } + + request.headers.set("Authorization", `Bearer ${session.token}`); + + return request; + } + + async afterError( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ): Promise<{ response: Response | null; error: unknown }> { + if (!hookCtx.oAuth2Scopes) { + // OAuth2 not in use + return { response, error }; + } + + if (error) { + return { response, error }; + } + + const credentials = await this.getCredentials(hookCtx); + if (!credentials || Object.values(credentials).some(v => v === "")) { + return { response, error }; + } + + if (response && response?.status === 401) { + const sessionKey = this.getSessionKey(credentials); + delete this.sessions[sessionKey]; + } + + return { response, error }; + } + + private async doTokenRequest( + hookCtx: HookContext, + credentials: Credentials, + scopes: string[], + ): Promise { + const formData = new URLSearchParams(); + formData.append("grant_type", "client_credentials"); + + const headers: Record = { + "Content-Type": "application/x-www-form-urlencoded", + }; + + formData.append("client_id", credentials.clientID); + formData.append("client_secret", credentials.clientSecret); + + if (scopes.length > 0) { + formData.append("scope", scopes.join(" ")); + } + + if (!hookCtx.baseURL?.toString()) { + throw new Error("Assertion error: Base URL cannot be empty"); + } + const tokenURL = new URL(credentials.tokenURL ?? "", hookCtx.baseURL); + + const request = new Request(tokenURL, { + method: "POST", + headers, + body: formData, + }); + + const res = await this.client?.request(request); + if (!res) { + throw new Error("Failed to fetch token"); + } + + if (res.status < 200 || res.status >= 300) { + throw new Error("Unexpected status code"); + } + + const data = await res.json(); + if (!data || typeof data !== "object") { + throw new Error("Unexpected response format"); + } + + if (data.token_type !== "Bearer") { + throw new Error("Unexpected token type"); + } + + let expiresAt: number | undefined; + if (data.expires_in) { + expiresAt = Date.now() + data.expires_in * 1000; + } + + const sess: Session = { + credentials, + token: data.access_token, + scopes, + }; + + if (expiresAt !== undefined) { + sess.expiresAt = expiresAt; + } + + return sess; + } + private async getCredentials( + hookCtx: HookContext, + ): Promise { + const source = hookCtx.securitySource; + + if (!source) { + return null; + } + + let security = source; + if (typeof source === "function") { + security = await source(); + } + + return this.getCredentialsGlobal(security); + } + + private async getCredentialsGlobal( + security: unknown, + ): Promise { + const out = parse( + security, + (val) => components.Security$outboundSchema.parse(val), + "unexpected security type", + ); + + return { + clientID: out?.oAuth2?.clientID ?? "", + clientSecret: out?.oAuth2?.clientSecret ?? "", + tokenURL: out?.oAuth2?.tokenURL ?? "", + }; + } + + private getSessionKey(credentials: Credentials): string { + const key = `${credentials.clientID}:${credentials.clientSecret}`; + return stringToBase64(key); + } + + private hasRequiredScopes( + scopes: string[], + requiredScopes: string[], + ): boolean { + return requiredScopes.every((scope) => scopes.includes(scope)); + } + + private getScopes(requiredScopes: string[], sess?: Session): string[] { + return [...new Set((sess?.scopes ?? []).concat(requiredScopes))]; + } + + private hasTokenExpired(expiresAt?: number): boolean { + return !expiresAt || Date.now() + 60000 > expiresAt; + } +} diff --git a/src/hooks/hooks.ts b/src/hooks/hooks.ts new file mode 100644 index 0000000..c177922 --- /dev/null +++ b/src/hooks/hooks.ts @@ -0,0 +1,135 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { SDKOptions } from "../lib/config.js"; +import { RequestInput } from "../lib/http.js"; +import { ClientCredentialsHook } from "./clientcredentials.js"; +import { + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeCreateRequestContext, + BeforeCreateRequestHook, + BeforeRequestContext, + BeforeRequestHook, + Hook, + Hooks, + SDKInitHook, +} from "./types.js"; + +import { initHooks } from "./registration.js"; + +export class SDKHooks implements Hooks { + sdkInitHooks: SDKInitHook[] = []; + beforeCreateRequestHooks: BeforeCreateRequestHook[] = []; + beforeRequestHooks: BeforeRequestHook[] = []; + afterSuccessHooks: AfterSuccessHook[] = []; + afterErrorHooks: AfterErrorHook[] = []; + + constructor() { + const presetHooks: Array = [ + new ClientCredentialsHook(), + ]; + + 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); + } + } + initHooks(this); + } + + registerSDKInitHook(hook: SDKInitHook) { + this.sdkInitHooks.push(hook); + } + + registerBeforeCreateRequestHook(hook: BeforeCreateRequestHook) { + this.beforeCreateRequestHooks.push(hook); + } + + registerBeforeRequestHook(hook: BeforeRequestHook) { + this.beforeRequestHooks.push(hook); + } + + registerAfterSuccessHook(hook: AfterSuccessHook) { + this.afterSuccessHooks.push(hook); + } + + registerAfterErrorHook(hook: AfterErrorHook) { + this.afterErrorHooks.push(hook); + } + + sdkInit(opts: SDKOptions): SDKOptions { + return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts); + } + + beforeCreateRequest( + hookCtx: BeforeCreateRequestContext, + input: RequestInput, + ): RequestInput { + let inp = input; + + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); + } + + return inp; + } + + async beforeRequest( + hookCtx: BeforeRequestContext, + request: Request, + ): Promise { + let req = request; + + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); + } + + return req; + } + + async afterSuccess( + hookCtx: AfterSuccessContext, + response: Response, + ): Promise { + let res = response; + + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); + } + + return res; + } + + async afterError( + hookCtx: AfterErrorContext, + response: Response | null, + error: unknown, + ): Promise<{ response: Response | null; error: unknown }> { + let res = response; + let err = error; + + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; + } + + return { response: res, error: err }; + } +} diff --git a/src/hooks/index.ts b/src/hooks/index.ts new file mode 100644 index 0000000..f60ec7a --- /dev/null +++ b/src/hooks/index.ts @@ -0,0 +1,6 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./hooks.js"; +export * from "./types.js"; diff --git a/src/hooks/registration.ts b/src/hooks/registration.ts new file mode 100644 index 0000000..7064973 --- /dev/null +++ b/src/hooks/registration.ts @@ -0,0 +1,14 @@ +import { Hooks } from "./types.js"; + +/* + * This file is only ever generated once on the first generation and then is free to be modified. + * Any hooks you wish to add should be registered in the initHooks function. Feel free to define them + * in this file or in separate files in the hooks folder. + */ + +// @ts-expect-error remove this line when you add your first hook and hooks is used +export function initHooks(hooks: Hooks) { + // Add hooks by calling hooks.register{ClientInit/BeforeCreateRequest/BeforeRequest/AfterSuccess/AfterError}Hook + // with an instance of a hook that implements that specific Hook interface + // Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance +} diff --git a/src/hooks/types.ts b/src/hooks/types.ts new file mode 100644 index 0000000..8ecd1e8 --- /dev/null +++ b/src/hooks/types.ts @@ -0,0 +1,109 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { SDKOptions } from "../lib/config.js"; +import { RequestInput } from "../lib/http.js"; +import { RetryConfig } from "../lib/retries.js"; +import { SecurityState } from "../lib/security.js"; +import { WebhookRecipient } from "../types/webhooks.js"; + +export type HookContext = { + baseURL: string | URL; + operationID: string; + oAuth2Scopes: string[] | null; + webhookRecipient?: WebhookRecipient; + securitySource?: any | (() => Promise); + retryConfig: RetryConfig; + resolvedSecurity: SecurityState | null; + options: SDKOptions; +}; + +export type Awaitable = T | Promise; + +export type BeforeCreateRequestContext = HookContext & {}; +export type BeforeRequestContext = HookContext & {}; +export type AfterSuccessContext = HookContext & {}; +export type AfterErrorContext = HookContext & {}; + +/** + * SDKInitHook is called when the SDK is initializing. The + * hook can return a new baseURL and HTTP client to be used by the SDK. + */ +export interface SDKInitHook { + sdkInit: (opts: SDKOptions) => SDKOptions; +} + +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; +} + +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; +} + +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; +} + +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; + }>; +} + +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; +} + +export type Hook = + | SDKInitHook + | BeforeCreateRequestHook + | BeforeRequestHook + | AfterSuccessHook + | AfterErrorHook; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..dbcba16 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,9 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./lib/config.js"; +export * as files from "./lib/files.js"; +export { HTTPClient } from "./lib/http.js"; +export type { Fetcher, HTTPClientOptions } from "./lib/http.js"; +export * from "./sdk/sdk.js"; diff --git a/src/lib/base64.ts b/src/lib/base64.ts new file mode 100644 index 0000000..c2d5b38 --- /dev/null +++ b/src/lib/base64.ts @@ -0,0 +1,37 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; + +export function bytesToBase64(u8arr: Uint8Array): string { + return btoa(String.fromCodePoint(...u8arr)); +} + +export function bytesFromBase64(encoded: string): Uint8Array { + return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0)); +} + +export function stringToBytes(str: string): Uint8Array { + return new TextEncoder().encode(str); +} + +export function stringFromBytes(u8arr: Uint8Array): string { + return new TextDecoder().decode(u8arr); +} + +export function stringToBase64(str: string): string { + return bytesToBase64(stringToBytes(str)); +} + +export function stringFromBase64(b64str: string): string { + return stringFromBytes(bytesFromBase64(b64str)); +} + +export const zodOutbound = z + .instanceof(Uint8Array) + .or(z.string().transform(stringToBytes)); + +export const zodInbound = z + .instanceof(Uint8Array) + .or(z.string().transform(bytesFromBase64)); diff --git a/src/lib/config.ts b/src/lib/config.ts new file mode 100644 index 0000000..b518960 --- /dev/null +++ b/src/lib/config.ts @@ -0,0 +1,98 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as components from "../models/components/index.js"; +import { ClosedEnum } from "../types/enums.js"; +import { HTTPClient } from "./http.js"; +import { Logger } from "./logger.js"; +import { RetryConfig } from "./retries.js"; +import { Params, pathToFunc } from "./url.js"; + +/** + * Contains the list of servers available to the SDK + */ +export const ServerList = [ + "https://galaxy.scalar.com", + /** + * Responds with your request data + */ + "{protocol}://void.scalar.com/{path}", +] as const; + +export const ServerProtocol = { + Https: "https", +} as const; +export type ServerProtocol = ClosedEnum; + +export type SDKOptions = { + /** + * The security details required to authenticate the SDK + */ + security?: + | components.Security + | (() => Promise) + | undefined; + + httpClient?: HTTPClient; + /** + * Allows overriding the default server used by the SDK + */ + serverIdx?: number | undefined; + /** + * Sets the protocol variable for url substitution + */ + protocol?: ServerProtocol | undefined; + /** + * Sets the path variable for url substitution + */ + path?: string | undefined; + /** + * Allows overriding the default server URL used by the SDK + */ + serverURL?: string | undefined; + /** + * Allows overriding the default user agent used by the SDK + */ + userAgent?: string | undefined; + /** + * 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; + + const serverParams: Params[] = [ + {}, + { + "protocol": options.protocol ?? "https", + "path": options.path ?? "", + }, + ]; + let params: Params = {}; + + if (!serverURL) { + const serverIdx = options.serverIdx ?? 0; + if (serverIdx < 0 || serverIdx >= ServerList.length) { + throw new Error(`Invalid server index ${serverIdx}`); + } + serverURL = ServerList[serverIdx] || ""; + params = serverParams[serverIdx] || {}; + } + + const u = pathToFunc(serverURL)(params); + return new URL(u); +} + +export const SDK_METADATA = { + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "1.0.0", + genVersion: "2.634.2", + userAgent: + "speakeasy-sdk/typescript 1.0.0 2.634.2 1.0.0 @shariqnzr-gmail-com-team/scalar-galaxy-typescript", +} 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 new file mode 100644 index 0000000..25c9dcb --- /dev/null +++ b/src/lib/encodings.ts @@ -0,0 +1,483 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { bytesToBase64 } from "./base64.js"; +import { isPlainObject } from "./is-plain-object.js"; + +export class EncodingError extends Error { + constructor(message: string) { + super(message); + this.name = "EncodingError"; + } +} + +export function encodeMatrix( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +): 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 encValue: string | null | undefined = null; + + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); + } else if (isPlainObject(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + return `,${encodeString(k)},${encodeValue(v)}`; + }); + 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 + if (tmp === `${keyPrefix}=`) { + tmp = tmp.slice(0, -1); + } + + // If we end up with the nothing then skip forward + if (!tmp) { + return; + } + + out += `;${tmp}`; + }); + + return out; +} + +export function encodeLabel( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +): 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: string | null | undefined = ""; + + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join("."); + } else if (isPlainObject(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + return `.${encodeString(k)}.${encodeValue(v)}`; + }); + encValue = mapped?.join("").slice(1); + } else { + const k = + options?.explode && isPlainObject(value) ? `${encodeString(pk)}=` : ""; + encValue = `${k}${encodeValue(pv)}`; + } + + out += encValue == null ? "" : `.${encValue}`; + }); + + return out; +} + +type FormEncoder = ( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +) => string | undefined; + +function formEncoder(sep: string): FormEncoder { + return ( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, + ) => { + 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)); + + const encodedSep = encodeString(sep); + + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue: string | null | undefined = null; + + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + 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); + } else { + encValue = `${encodeValue(pv)}`; + } + + if (encValue == null) { + return; + } + + tmp = `${encodeString(pk)}=${encValue}`; + + // If we end up with the nothing then skip forward + if (!tmp || tmp === "=") { + return; + } + + out += `&${tmp}`; + }); + + return out.slice(1); + }; +} + +export const encodeForm = formEncoder(","); +export const encodeSpaceDelimited = formEncoder(" "); +export const encodePipeDelimited = formEncoder("|"); + +export function encodeBodyForm( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +): string { + let out = ""; + const pairs: [string, unknown][] = options?.explode + ? explode(key, value) + : [[key, value]]; + + 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 encValue = ""; + + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else if (isPlainObject(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else { + encValue = `${encodeValue(pv)}`; + } + + tmp = `${encodeString(pk)}=${encValue}`; + + // If we end up with the nothing then skip forward + if (!tmp || tmp === "=") { + return; + } + + out += `&${tmp}`; + }); + + return out.slice(1); +} + +export function encodeDeepObject( + key: string, + value: unknown, + options?: { charEncoding?: "percent" | "none" }, +): string | undefined { + if (value == null) { + 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 = ""; + + const encodeString = (v: string) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + }; + + if (!isPlainObject(value)) { + throw new EncodingError(`Expected parameter '${key}' to be an object.`); + } + + Object.entries(value).forEach(([ck, cv]) => { + if (cv == null) { + return; + } + + const pk = `${key}[${ck}]`; + + if (isPlainObject(cv)) { + const objOut = encodeDeepObjectObject(pk, cv, options); + + out += objOut == null ? "" : `&${objOut}`; + + return; + } + + const pairs: unknown[] = Array.isArray(cv) ? cv : [cv]; + const encoded = mapDefined(pairs, (v) => { + return `${encodeString(pk)}=${encodeString(serializeValue(v))}`; + })?.join("&"); + + out += encoded == null ? "" : `&${encoded}`; + }); + + return out.slice(1); +} + +export function encodeJSON( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +): string | undefined { + if (typeof value === "undefined") { + return; + } + + const encodeString = (v: string) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v) : v; + }; + + const encVal = encodeString(JSON.stringify(value, jsonReplacer)); + + return options?.explode ? encVal : `${encodeString(key)}=${encVal}`; +} + +export const encodeSimple = ( + key: string, + value: unknown, + options?: { explode?: boolean; charEncoding?: "percent" | "none" }, +): 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: string | null | undefined = ""; + + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + tmp = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(","); + } else if (isPlainObject(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k, v]) => { + return `,${encodeString(k)},${encodeValue(v)}`; + }); + tmp = mapped?.join("").slice(1); + } else { + const k = options?.explode && isPlainObject(value) ? `${pk}=` : ""; + tmp = `${k}${encodeValue(pv)}`; + } + + out += tmp ? `,${tmp}` : ""; + }); + + return out.slice(1); +}; + +function explode(key: string, value: unknown): [string, unknown][] { + if (Array.isArray(value)) { + return value.map((v) => [key, v]); + } else if (isPlainObject(value)) { + const o = value ?? {}; + return Object.entries(o).map(([k, v]) => [k, v]); + } else { + return [[key, value]]; + } +} + +function serializeValue(value: unknown): string { + if (value == null) { + return ""; + } else if (value instanceof Date) { + return value.toISOString(); + } else if (value instanceof Uint8Array) { + return bytesToBase64(value); + } else if (typeof value === "object") { + return JSON.stringify(value, jsonReplacer); + } + + return `${value}`; +} + +function jsonReplacer(_: string, value: unknown): unknown { + if (value instanceof Uint8Array) { + return bytesToBase64(value); + } else { + return value; + } +} + +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 == null) { + return acc; + } + + acc.push(m); + + return acc; + }, []); + + return res.length ? res : null; +} + +function mapDefinedEntries( + inp: Iterable<[K, V]>, + mapper: (v: [K, V]) => R, +): R[] | null { + const acc: R[] = []; + for (const [k, v] of inp) { + if (v == null) { + continue; + } + + const m = mapper([k, v]); + if (m == null) { + continue; + } + + acc.push(m); + } + + return acc.length ? acc : null; +} + +export function queryJoin(...args: (string | undefined)[]): string { + return args.filter(Boolean).join("&"); +} + +type QueryEncoderOptions = { + explode?: boolean; + charEncoding?: "percent" | "none"; +}; + +type QueryEncoder = ( + key: string, + value: unknown, + options?: QueryEncoderOptions, +) => string | undefined; + +type BulkQueryEncoder = ( + values: Record, + options?: QueryEncoderOptions, +) => string; + +export function queryEncoder(f: QueryEncoder): BulkQueryEncoder { + const bulkEncode = function ( + values: Record, + options?: QueryEncoderOptions, + ): string { + const opts: QueryEncoderOptions = { + ...options, + explode: options?.explode ?? true, + charEncoding: options?.charEncoding ?? "percent", + }; + + const encoded = Object.entries(values).map(([key, value]) => { + return f(key, value, opts); + }); + return queryJoin(...encoded); + }; + + return bulkEncode; +} + +export const encodeJSONQuery = queryEncoder(encodeJSON); +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..0344cd0 --- /dev/null +++ b/src/lib/files.ts @@ -0,0 +1,82 @@ +/* + * 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 as ArrayBuffer; +} + +/** + * Determines the MIME content type based on a file's extension. + * Returns null if the extension is not recognized. + */ +export function getContentTypeFromFileName(fileName: string): string | null { + if (!fileName) return null; + + const ext = fileName.toLowerCase().split(".").pop(); + if (!ext) return null; + + const mimeTypes: Record = { + json: "application/json", + xml: "application/xml", + html: "text/html", + htm: "text/html", + txt: "text/plain", + csv: "text/csv", + pdf: "application/pdf", + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + svg: "image/svg+xml", + js: "application/javascript", + css: "text/css", + zip: "application/zip", + tar: "application/x-tar", + gz: "application/gzip", + mp4: "video/mp4", + mp3: "audio/mpeg", + wav: "audio/wav", + webp: "image/webp", + ico: "image/x-icon", + woff: "font/woff", + woff2: "font/woff2", + ttf: "font/ttf", + otf: "font/otf", + }; + + return mimeTypes[ext] || null; +} diff --git a/src/lib/http.ts b/src/lib/http.ts new file mode 100644 index 0000000..13cf1fd --- /dev/null +++ b/src/lib/http.ts @@ -0,0 +1,323 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +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); + } +}; + +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; +}; + +export interface HTTPClientOptions { + fetcher?: Fetcher; +} + +export type BeforeRequestHook = (req: Request) => Awaitable; +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; + } + + 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; + } + } + + /** + * 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]}`); + } + + const index = target.findIndex((v) => v === args[1]); + if (index >= 0) { + target.splice(index, 1); + } + + return this; + } + + 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)[]; + +// A semicolon surrounded by optional whitespace characters is used to separate +// segments in a media type string. +const mediaParamSeparator = /\s*;\s*/g; + +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; + } + } + + 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; + }); +} + +export function matchResponse( + response: Response, + code: StatusCodePredicate, + contentTypePattern: string, +): boolean { + return ( + matchStatusCode(response, code) && + matchContentType(response, contentTypePattern) + ); +} + +/** + * 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; + } + + // 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; +} + +/** + * Uses various heurisitics to determine if an error is a timeout error. + */ +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; +} + +/** + * 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 new file mode 100644 index 0000000..61070d3 --- /dev/null +++ b/src/lib/is-plain-object.ts @@ -0,0 +1,43 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/* +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.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. +*/ + +// Taken from https://github.com/sindresorhus/is-plain-obj/blob/97f38e8836f86a642cce98fc6ab3058bc36df181/index.js + +export function isPlainObject(value: unknown): value is object { + if (typeof value !== "object" || value === null) { + return false; + } + + const prototype = Object.getPrototypeOf(value); + return ( + (prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(Symbol.toStringTag in value) && + !(Symbol.iterator in value) + ); +} 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..77d4108 --- /dev/null +++ b/src/lib/matchers.ts @@ -0,0 +1,345 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { APIError } from "../models/errors/apierror.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { ERR, OK, Result } from "../types/fp.js"; +import { matchResponse, matchStatusCode, StatusCodePredicate } from "./http.js"; +import { isPlainObject } from "./is-plain-object.js"; + +export type Encoding = + | "jsonl" + | "json" + | "text" + | "bytes" + | "stream" + | "sse" + | "nil" + | "fail"; + +const DEFAULT_CONTENT_TYPES: Record = { + jsonl: "application/jsonl", + 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 jsonl( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, +): ValueMatcher { + return { ...options, enc: "jsonl", codes, schema }; +} + +export function jsonlErr( + codes: StatusCodePredicate, + schema: Schema, + options?: MatchOptions, +): ErrorMatcher { + return { ...options, err: true, enc: "jsonl", 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, + request: Request, + options?: { resultKey?: string; extraFields?: Record }, +) => Promise<[result: Result, raw: unknown]>; + +export function match( + ...matchers: Array> +): MatchFunc { + return async function matchFunc( + response: Response, + request: Request, + 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) { + return [{ + ok: false, + error: new APIError("Unexpected Status or Content-Type", { + response, + request, + body: await response.text().catch(() => ""), + }), + }, raw]; + } + + const encoding = matcher.enc; + let body = ""; + switch (encoding) { + case "json": + body = await response.text(); + raw = JSON.parse(body); + break; + case "jsonl": + raw = response.body; + break; + case "bytes": + raw = new Uint8Array(await response.arrayBuffer()); + break; + case "stream": + raw = response.body; + break; + case "text": + body = await response.text(); + raw = body; + break; + case "sse": + raw = response.body; + break; + case "nil": + body = await response.text(); + raw = undefined; + break; + case "fail": + body = await response.text(); + raw = body; + break; + default: + encoding satisfies never; + throw new Error(`Unsupported response type: ${encoding}`); + } + + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new APIError("API error occurred", { request, response, body }), + }, 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), + request$: request, + response$: response, + body$: body, + }; + } 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 = safeParseResponse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + { request, response, body }, + ); + return [result.ok ? { ok: false, error: result.value } : result, raw]; + } else { + return [ + safeParseResponse( + data, + (v: unknown) => matcher.schema.parse(v), + "Response validation failed", + { request, response, body }, + ), + 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; +} + +function safeParseResponse( + rawValue: Inp, + fn: (value: Inp) => Out, + errorMessage: string, + httpMeta: { response: Response; request: Request; body: string }, +): Result { + try { + return OK(fn(rawValue)); + } catch (err) { + return ERR( + new ResponseValidationError(errorMessage, { + cause: err, + rawValue, + rawMessage: errorMessage, + ...httpMeta, + }), + ); + } +} diff --git a/src/lib/primitives.ts b/src/lib/primitives.ts new file mode 100644 index 0000000..d21f1dc --- /dev/null +++ b/src/lib/primitives.ts @@ -0,0 +1,150 @@ +/* + * 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] + : Mapping[k] extends null /* if the mapping is to `null` then drop the key */ + ? never + : k /* otherwise keep the key as-is */]: Inp[k]; +}; + +/** + * Converts or omits an object's keys according to a mapping. + * + * @param inp An object whose keys will be remapped + * @param mappings A mapping of original keys to new keys. If a key is not present in the mapping, it will be left as is. If a key is mapped to `null`, it will be removed in the resulting object. + * @returns A new object with keys remapped or omitted according to the mappings + */ +export function remap< + Inp extends Record, + const Mapping extends { [k in keyof Inp]?: string | null }, +>(inp: Inp, mappings: Mapping): Remap { + let out: any = {}; + + if (!Object.keys(mappings).length) { + out = inp; + return out; + } + + for (const [k, v] of Object.entries(inp)) { + const j = mappings[k]; + if (j === null) { + continue; + } + out[j ?? k] = v; + } + + 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; +} + +export function allRequired>( + v: V, +): + | { + [K in keyof V]: NonNullable; + } + | undefined { + if (Object.values(v).every((x) => x == null)) { + return void 0; + } + + return v as ReturnType>; +} diff --git a/src/lib/retries.ts b/src/lib/retries.ts new file mode 100644 index 0000000..e3ce9ab --- /dev/null +++ b/src/lib/retries.ts @@ -0,0 +1,218 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { isConnectionError, isTimeoutError } from "./http.js"; + +export type BackoffStrategy = { + initialInterval: number; + maxInterval: number; + exponent: number; + maxElapsedTime: number; +}; + +const defaultBackoff: BackoffStrategy = { + initialInterval: 500, + maxInterval: 60000, + exponent: 1.5, + maxElapsedTime: 3600000, +}; + +export type RetryConfig = + | { strategy: "none" } + | { + strategy: "backoff"; + backoff?: BackoffStrategy; + retryConnectionErrors?: boolean; + }; + +/** + * 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}`; + } + + 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); + } +} + +/** + * 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(message: string, response: Response) { + super(message); + this.response = response; + this.name = "TemporaryError"; + + Object.setPrototypeOf(this, TemporaryError.prototype); + } +} + +export async function retry( + fetchFn: () => Promise, + options: { + config: RetryConfig; + statusCodes: string[]; + }, +): Promise { + switch (options.config.strategy) { + case "backoff": + return retryBackoff( + wrapFetcher(fetchFn, { + statusCodes: options.statusCodes, + retryConnectionErrors: !!options.config.retryConnectionErrors, + }), + options.config.backoff ?? defaultBackoff, + ); + default: + return await fetchFn(); + } +} + +function wrapFetcher( + fn: () => Promise, + options: { + statusCodes: string[]; + retryConnectionErrors: boolean; + }, +): () => Promise { + return async () => { + try { + const res = await fn(); + if (isRetryableResponse(res, options.statusCodes)) { + throw new TemporaryError( + "Response failed with retryable status code", + res, + ); + } + + return res; + } catch (err: unknown) { + if (err instanceof TemporaryError) { + throw err; + } + + if ( + options.retryConnectionErrors && + (isTimeoutError(err) || isConnectionError(err)) + ) { + throw err; + } + + throw new PermanentError("Permanent error", { cause: err }); + } + }; +} + +const codeRangeRE = new RegExp("^[0-9]xx$", "i"); + +function isRetryableResponse(res: Response, statusCodes: string[]): boolean { + const actual = `${res.status}`; + + return statusCodes.some((code) => { + 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; + }); +} + +async function retryBackoff( + fn: () => Promise, + strategy: BackoffStrategy, +): Promise { + const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy; + + const start = Date.now(); + let x = 0; + + while (true) { + try { + const res = await fn(); + return res; + } catch (err: unknown) { + if (err instanceof PermanentError) { + throw err.cause; + } + const elapsed = Date.now() - start; + if (elapsed > maxElapsedTime) { + if (err instanceof TemporaryError) { + return err.response; + } + + throw err; + } + + let retryInterval = 0; + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); + } + + if (retryInterval <= 0) { + retryInterval = + initialInterval * Math.pow(x, exponent) + Math.random() * 1000; + } + + const d = Math.min(retryInterval, maxInterval); + + await delay(d); + x++; + } + } +} + +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 new file mode 100644 index 0000000..0e340b7 --- /dev/null +++ b/src/lib/schemas.ts @@ -0,0 +1,91 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { + output, + ZodEffects, + ZodError, + ZodObject, + ZodRawShape, + ZodTypeAny, +} from "zod"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import { ERR, OK, Result } from "../types/fp.js"; + +/** + * Utility function that executes some code which may throw a ZodError. It + * 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; + } +} + +/** + * 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, +>( + obj: ZodObject, + extrasKey: K, + optional: boolean, +): ZodEffects< + 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]; + } + + 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 new file mode 100644 index 0000000..fb7e9ac --- /dev/null +++ b/src/lib/sdks.ts @@ -0,0 +1,402 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +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 = { + /** + * 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; + /** + * @deprecated `fetchOptions` has been flattened into `RequestOptions`. + * + * 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; +} & Omit; + +type RequestConfig = { + method: string; + path: string; + baseURL?: string | URL | undefined; + query?: string; + body?: RequestInit["body"]; + headers?: HeadersInit; + security?: SecurityState | null; + uaHeader?: string; + userAgent?: string | undefined; + 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 { + readonly #httpClient: HTTPClient; + readonly #hooks: SDKHooks; + readonly #logger?: Logger | undefined; + public readonly _baseURL: URL | null; + public readonly _options: SDKOptions & { hooks?: SDKHooks }; + + constructor(options: SDKOptions = {}) { + const opt = options as unknown; + if ( + typeof opt === "object" + && opt != null + && "hooks" in opt + && opt.hooks instanceof SDKHooks + ) { + this.#hooks = opt.hooks; + } else { + this.#hooks = new SDKHooks(); + } + const defaultHttpClient = new HTTPClient(); + options.httpClient = options.httpClient || defaultHttpClient; + options = this.#hooks.sdkInit(options); + + const url = serverURLFromOptions(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + this._baseURL = url; + this.#httpClient = options.httpClient || defaultHttpClient; + + this._options = { ...options, hooks: this.#hooks }; + + this.#logger = this._options.debugLogger; + } + + public _createRequest( + context: HookContext, + conf: RequestConfig, + options?: RequestOptions, + ): Result { + const { method, path, query, headers: opHeaders, security } = conf; + + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return ERR(new InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path, reqURL); + + if (path) { + reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/"; + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } + + let finalQuery = query || ""; + + 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("&")}`; + } + + if (finalQuery) { + const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q}`; + } + + const headers = new Headers(opHeaders); + + 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 securityHeaders = new Headers(security?.headers || {}); + for (const [k, v] of securityHeaders) { + 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 userHeaders = new Headers( + options?.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", + conf.userAgent ?? SDK_METADATA.userAgent, + ); + } + + const fetchOptions: Omit = { + ...options?.fetchOptions, + ...options, + }; + if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { + const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); + fetchOptions.signal = timeoutSignal; + } + + if (conf.body instanceof ReadableStream) { + Object.assign(fetchOptions, { duplex: "half" }); + } + + let input; + try { + input = this.#hooks.beforeCreateRequest(context, { + url: reqURL, + options: { + ...fetchOptions, + body: conf.body ?? null, + headers, + method, + }, + }); + } catch (err: unknown) { + return ERR( + new UnexpectedClientError("Create request hook failed to execute", { + cause: err, + }), + ); + } + + return OK(new Request(input.url, input.options)); + } + + 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; + + return retry( + async () => { + const req = await this.#hooks.beforeRequest(context, request.clone()); + await logRequest(this.#logger, req).catch((e) => + this.#logger?.log("Failed to log request:", e) + ); + + let response = await this.#httpClient.request(req); + + try { + if (matchStatusCode(response, errorCodes)) { + const result = await this.#hooks.afterError( + context, + response, + null, + ); + if (result.error) { + throw result.error; + } + response = result.response || response; + } else { + response = await this.#hooks.afterSuccess(context, response); + } + } 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|text)\/.*?\+*json.*/; +const jsonlLikeContentTypeRE = + /(application|text)\/(.*?\+*\bjsonl\b.*|.*?\+*\bx-ndjson\b.*)/; +async function logRequest(logger: Logger | undefined, req: Request) { + if (!logger) { + return; + } + + const contentType = req.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + + logger.group(`> Request: ${req.method} ${req.url}`); + + logger.group("Headers:"); + for (const [k, v] of req.headers.entries()) { + logger.log(`${k}: ${v}`); + } + logger.groupEnd(); + + logger.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k, v] of body) { + const vlabel = v instanceof Blob ? "" : v; + logger.log(`${k}: ${vlabel}`); + } + break; + } + default: + logger.log(`<${contentType}>`); + break; + } + logger.groupEnd(); + + 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] || ""; + + 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) && !jsonlLikeContentTypeRE.test(ct): + logger.log(await res.clone().json()); + break; + case matchContentType(res, "application/jsonl") + || jsonlLikeContentTypeRE.test(ct): + logger.log(await res.clone().text()); + 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(); + + logger.groupEnd(); +} diff --git a/src/lib/security.ts b/src/lib/security.ts new file mode 100644 index 0000000..f781657 --- /dev/null +++ b/src/lib/security.ts @@ -0,0 +1,306 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as components from "../models/components/index.js"; + +type OAuth2PasswordFlow = { + username: string; + password: string; + clientID?: string | undefined; + clientSecret?: string | undefined; + tokenURL: string; +}; + +export enum SecurityErrorCode { + 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}`, + ); + } +} + +export type SecurityState = { + 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 SecurityInputBearer = { + 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 SecurityInputOIDC = { + type: "openIdConnect"; + value: string | null | undefined; + fieldName: string; +}; + +type SecurityInputOAuth2 = { + type: "oauth2"; + value: string | null | undefined; + fieldName: string; +}; + +type SecurityInputOAuth2ClientCredentials = { + type: "oauth2:client_credentials"; + value: + | { clientID?: string | undefined; clientSecret?: string | undefined } + | null + | string + | undefined; + fieldName?: string; +}; + +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 + | 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") { + if (typeof o.value == "string") { + return !!o.value; + } + 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; + } + + 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; +} + +function applyBasic( + state: SecurityState, + spec: SecurityInputBasic, +) { + if (spec.value == null) { + return; + } + + state.basic = spec.value; +} + +function applyBearer( + state: SecurityState, + spec: + | SecurityInputBearer + | SecurityInputOAuth2 + | SecurityInputOIDC + | SecurityInputOAuth2PasswordCredentials, +) { + if (typeof spec.value !== "string" || !spec.value) { + return; + } + + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } + + if (spec.fieldName !== undefined) { + state.headers[spec.fieldName] = value; + } +} + +export function resolveGlobalSecurity( + security: Partial | null | undefined, +): SecurityState | null { + return resolveSecurity( + [ + { + fieldName: "Authorization", + type: "http:bearer", + value: security?.bearerAuth, + }, + ], + [ + { + type: "http:basic", + value: { + username: security?.basicAuth?.username, + password: security?.basicAuth?.password, + }, + }, + ], + [ + { + fieldName: "api_key", + type: "apiKey:query", + value: security?.apiKeyQuery, + }, + ], + [ + { + fieldName: "X-API-Key", + type: "apiKey:header", + value: security?.apiKeyHeader, + }, + ], + [ + { + fieldName: "api_key", + type: "apiKey:cookie", + value: security?.apiKeyCookie, + }, + ], + [ + { + type: "oauth2:client_credentials", + value: { + clientID: security?.oAuth2?.clientID, + clientSecret: security?.oAuth2?.clientSecret, + }, + }, + ], + [ + { + fieldName: "Authorization", + type: "openIdConnect", + value: security?.openIdConnect, + }, + ], + ); +} + +export async function extractSecurity< + T extends string | Record, +>(sec: T | (() => Promise) | undefined): Promise { + if (sec == null) { + return; + } + + return typeof sec === "function" ? sec() : sec; +} diff --git a/src/lib/url.ts b/src/lib/url.ts new file mode 100644 index 0000000..6bc6356 --- /dev/null +++ b/src/lib/url.ts @@ -0,0 +1,33 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +const hasOwn = Object.prototype.hasOwnProperty; + +export type Params = Partial>; + +export function pathToFunc( + pathPattern: string, + options?: { charEncoding?: "percent" | "none" }, +): (params?: Params) => string { + const paramRE = /\{([a-zA-Z0-9_]+?)\}/g; + + return function buildURLPath(params: Record = {}): string { + return pathPattern.replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error( + `Parameter '${placeholder}' must be a string or number`, + ); + } + + return options?.charEncoding === "percent" + ? encodeURIComponent(`${value}`) + : `${value}`; + }); + }; +} diff --git a/src/models/components/credentials.ts b/src/models/components/credentials.ts new file mode 100644 index 0000000..29ad541 --- /dev/null +++ b/src/models/components/credentials.ts @@ -0,0 +1,69 @@ +/* + * 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"; + +/** + * Credentials to authenticate a user + */ +export type Credentials = { + email: string; + password: string; +}; + +/** @internal */ +export const Credentials$inboundSchema: z.ZodType< + Credentials, + z.ZodTypeDef, + unknown +> = z.object({ + email: z.string(), + password: z.string(), +}); + +/** @internal */ +export type Credentials$Outbound = { + email: string; + password: string; +}; + +/** @internal */ +export const Credentials$outboundSchema: z.ZodType< + Credentials$Outbound, + z.ZodTypeDef, + Credentials +> = z.object({ + email: z.string(), + password: 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 Credentials$ { + /** @deprecated use `Credentials$inboundSchema` instead. */ + export const inboundSchema = Credentials$inboundSchema; + /** @deprecated use `Credentials$outboundSchema` instead. */ + export const outboundSchema = Credentials$outboundSchema; + /** @deprecated use `Credentials$Outbound` instead. */ + export type Outbound = Credentials$Outbound; +} + +export function credentialsToJSON(credentials: Credentials): string { + return JSON.stringify(Credentials$outboundSchema.parse(credentials)); +} + +export function credentialsFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Credentials$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Credentials' from JSON`, + ); +} diff --git a/src/models/components/imageuploadedmessage.ts b/src/models/components/imageuploadedmessage.ts new file mode 100644 index 0000000..0f18ffd --- /dev/null +++ b/src/models/components/imageuploadedmessage.ts @@ -0,0 +1,98 @@ +/* + * 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"; + +/** + * Message about an image upload + */ +export type ImageUploadedMessage = { + message?: string | undefined; + /** + * The URL where the uploaded image can be accessed + */ + imageUrl?: string | undefined; + /** + * Timestamp when the image was uploaded + */ + uploadedAt?: Date | undefined; + /** + * Size of the uploaded image in bytes + */ + fileSize?: number | undefined; + /** + * The content type of the uploaded image + */ + mimeType?: string | undefined; +}; + +/** @internal */ +export const ImageUploadedMessage$inboundSchema: z.ZodType< + ImageUploadedMessage, + z.ZodTypeDef, + unknown +> = z.object({ + message: z.string().optional(), + imageUrl: z.string().optional(), + uploadedAt: z.string().datetime({ offset: true }).transform(v => new Date(v)) + .optional(), + fileSize: z.number().int().optional(), + mimeType: z.string().optional(), +}); + +/** @internal */ +export type ImageUploadedMessage$Outbound = { + message?: string | undefined; + imageUrl?: string | undefined; + uploadedAt?: string | undefined; + fileSize?: number | undefined; + mimeType?: string | undefined; +}; + +/** @internal */ +export const ImageUploadedMessage$outboundSchema: z.ZodType< + ImageUploadedMessage$Outbound, + z.ZodTypeDef, + ImageUploadedMessage +> = z.object({ + message: z.string().optional(), + imageUrl: z.string().optional(), + uploadedAt: z.date().transform(v => v.toISOString()).optional(), + fileSize: z.number().int().optional(), + mimeType: 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 ImageUploadedMessage$ { + /** @deprecated use `ImageUploadedMessage$inboundSchema` instead. */ + export const inboundSchema = ImageUploadedMessage$inboundSchema; + /** @deprecated use `ImageUploadedMessage$outboundSchema` instead. */ + export const outboundSchema = ImageUploadedMessage$outboundSchema; + /** @deprecated use `ImageUploadedMessage$Outbound` instead. */ + export type Outbound = ImageUploadedMessage$Outbound; +} + +export function imageUploadedMessageToJSON( + imageUploadedMessage: ImageUploadedMessage, +): string { + return JSON.stringify( + ImageUploadedMessage$outboundSchema.parse(imageUploadedMessage), + ); +} + +export function imageUploadedMessageFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => ImageUploadedMessage$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'ImageUploadedMessage' from JSON`, + ); +} diff --git a/src/models/components/index.ts b/src/models/components/index.ts new file mode 100644 index 0000000..7b08b5f --- /dev/null +++ b/src/models/components/index.ts @@ -0,0 +1,14 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./credentials.js"; +export * from "./imageuploadedmessage.js"; +export * from "./planet.js"; +export * from "./satellite.js"; +export * from "./schemebasicauth.js"; +export * from "./schemeoauth2.js"; +export * from "./security.js"; +export * from "./token.js"; +export * from "./user.js"; +export * from "./userinput.js"; diff --git a/src/models/components/planet.ts b/src/models/components/planet.ts new file mode 100644 index 0000000..60d4336 --- /dev/null +++ b/src/models/components/planet.ts @@ -0,0 +1,504 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { safeParse } from "../../lib/schemas.js"; +import { ClosedEnum } from "../../types/enums.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; +import { + Satellite, + Satellite$inboundSchema, + Satellite$Outbound, + Satellite$outboundSchema, +} from "./satellite.js"; +import { + User, + User$inboundSchema, + User$Outbound, + User$outboundSchema, +} from "./user.js"; +import { + UserInput, + UserInput$inboundSchema, + UserInput$Outbound, + UserInput$outboundSchema, +} from "./userinput.js"; + +export const Type = { + Terrestrial: "terrestrial", + GasGiant: "gas_giant", + IceGiant: "ice_giant", + Dwarf: "dwarf", + SuperEarth: "super_earth", +} as const; +export type Type = ClosedEnum; + +export type Temperature = { + /** + * Minimum temperature in Kelvin + */ + min?: number | undefined; + /** + * Maximum temperature in Kelvin + */ + max?: number | undefined; + /** + * Average temperature in Kelvin + */ + average?: number | undefined; +}; + +export type PhysicalProperties = { + /** + * Mass in Earth masses + */ + mass?: number | undefined; + /** + * Radius in Earth radii + */ + radius?: number | undefined; + /** + * Surface gravity in Earth g + */ + gravity?: number | undefined; + temperature?: Temperature | undefined; +}; + +export type Atmosphere = { + compound?: string | undefined; + percentage?: number | undefined; +}; + +/** + * A planet in the Scalar Galaxy + */ +export type Planet = { + id: number; + name: string; + description?: string | null | undefined; + type?: Type | undefined; + /** + * A score from 0 to 1 indicating potential habitability + */ + habitabilityIndex?: number | undefined; + physicalProperties?: PhysicalProperties | undefined; + /** + * Atmospheric composition + */ + atmosphere?: Array | undefined; + discoveredAt?: Date | undefined; + image?: string | null | undefined; + satellites?: Array | undefined; + /** + * A user + */ + creator?: User | undefined; + tags?: Array | undefined; + lastUpdated?: Date | undefined; + /** + * URL to receive notifications about this planet + */ + callbackUrl?: string | undefined; +}; + +/** + * A planet in the Scalar Galaxy + */ +export type PlanetInput = { + name: string; + description?: string | null | undefined; + type?: Type | undefined; + /** + * A score from 0 to 1 indicating potential habitability + */ + habitabilityIndex?: number | undefined; + physicalProperties?: PhysicalProperties | undefined; + /** + * Atmospheric composition + */ + atmosphere?: Array | undefined; + discoveredAt?: Date | undefined; + image?: string | null | undefined; + satellites?: Array | undefined; + /** + * A user + */ + creator?: UserInput | undefined; + tags?: Array | undefined; + /** + * URL to receive notifications about this planet + */ + callbackUrl?: string | undefined; +}; + +/** @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$ { + /** @deprecated use `Type$inboundSchema` instead. */ + export const inboundSchema = Type$inboundSchema; + /** @deprecated use `Type$outboundSchema` instead. */ + export const outboundSchema = Type$outboundSchema; +} + +/** @internal */ +export const Temperature$inboundSchema: z.ZodType< + Temperature, + z.ZodTypeDef, + unknown +> = z.object({ + min: z.number().optional(), + max: z.number().optional(), + average: z.number().optional(), +}); + +/** @internal */ +export type Temperature$Outbound = { + min?: number | undefined; + max?: number | undefined; + average?: number | undefined; +}; + +/** @internal */ +export const Temperature$outboundSchema: z.ZodType< + Temperature$Outbound, + z.ZodTypeDef, + Temperature +> = z.object({ + min: z.number().optional(), + max: z.number().optional(), + average: z.number().optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace Temperature$ { + /** @deprecated use `Temperature$inboundSchema` instead. */ + export const inboundSchema = Temperature$inboundSchema; + /** @deprecated use `Temperature$outboundSchema` instead. */ + export const outboundSchema = Temperature$outboundSchema; + /** @deprecated use `Temperature$Outbound` instead. */ + export type Outbound = Temperature$Outbound; +} + +export function temperatureToJSON(temperature: Temperature): string { + return JSON.stringify(Temperature$outboundSchema.parse(temperature)); +} + +export function temperatureFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Temperature$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Temperature' from JSON`, + ); +} + +/** @internal */ +export const PhysicalProperties$inboundSchema: z.ZodType< + PhysicalProperties, + z.ZodTypeDef, + unknown +> = z.object({ + mass: z.number().optional(), + radius: z.number().optional(), + gravity: z.number().optional(), + temperature: z.lazy(() => Temperature$inboundSchema).optional(), +}); + +/** @internal */ +export type PhysicalProperties$Outbound = { + mass?: number | undefined; + radius?: number | undefined; + gravity?: number | undefined; + temperature?: Temperature$Outbound | undefined; +}; + +/** @internal */ +export const PhysicalProperties$outboundSchema: z.ZodType< + PhysicalProperties$Outbound, + z.ZodTypeDef, + PhysicalProperties +> = z.object({ + mass: z.number().optional(), + radius: z.number().optional(), + gravity: z.number().optional(), + temperature: z.lazy(() => Temperature$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 PhysicalProperties$ { + /** @deprecated use `PhysicalProperties$inboundSchema` instead. */ + export const inboundSchema = PhysicalProperties$inboundSchema; + /** @deprecated use `PhysicalProperties$outboundSchema` instead. */ + export const outboundSchema = PhysicalProperties$outboundSchema; + /** @deprecated use `PhysicalProperties$Outbound` instead. */ + export type Outbound = PhysicalProperties$Outbound; +} + +export function physicalPropertiesToJSON( + physicalProperties: PhysicalProperties, +): string { + return JSON.stringify( + PhysicalProperties$outboundSchema.parse(physicalProperties), + ); +} + +export function physicalPropertiesFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PhysicalProperties$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PhysicalProperties' from JSON`, + ); +} + +/** @internal */ +export const Atmosphere$inboundSchema: z.ZodType< + Atmosphere, + z.ZodTypeDef, + unknown +> = z.object({ + compound: z.string().optional(), + percentage: z.number().optional(), +}); + +/** @internal */ +export type Atmosphere$Outbound = { + compound?: string | undefined; + percentage?: number | undefined; +}; + +/** @internal */ +export const Atmosphere$outboundSchema: z.ZodType< + Atmosphere$Outbound, + z.ZodTypeDef, + Atmosphere +> = z.object({ + compound: z.string().optional(), + percentage: z.number().optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace Atmosphere$ { + /** @deprecated use `Atmosphere$inboundSchema` instead. */ + export const inboundSchema = Atmosphere$inboundSchema; + /** @deprecated use `Atmosphere$outboundSchema` instead. */ + export const outboundSchema = Atmosphere$outboundSchema; + /** @deprecated use `Atmosphere$Outbound` instead. */ + export type Outbound = Atmosphere$Outbound; +} + +export function atmosphereToJSON(atmosphere: Atmosphere): string { + return JSON.stringify(Atmosphere$outboundSchema.parse(atmosphere)); +} + +export function atmosphereFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Atmosphere$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Atmosphere' from JSON`, + ); +} + +/** @internal */ +export const Planet$inboundSchema: z.ZodType = z + .object({ + id: z.number().int(), + name: z.string(), + description: z.nullable(z.string()).optional(), + type: Type$inboundSchema.optional(), + habitabilityIndex: z.number().optional(), + physicalProperties: z.lazy(() => PhysicalProperties$inboundSchema) + .optional(), + atmosphere: z.array(z.lazy(() => Atmosphere$inboundSchema)).optional(), + discoveredAt: z.string().datetime({ offset: true }).transform(v => + new Date(v) + ).optional(), + image: z.nullable(z.string()).optional(), + satellites: z.array(Satellite$inboundSchema).optional(), + creator: User$inboundSchema.optional(), + tags: z.array(z.string()).optional(), + lastUpdated: z.string().datetime({ offset: true }).transform(v => + new Date(v) + ).optional(), + callbackUrl: z.string().optional(), + }); + +/** @internal */ +export type Planet$Outbound = { + id: number; + name: string; + description?: string | null | undefined; + type?: string | undefined; + habitabilityIndex?: number | undefined; + physicalProperties?: PhysicalProperties$Outbound | undefined; + atmosphere?: Array | undefined; + discoveredAt?: string | undefined; + image?: string | null | undefined; + satellites?: Array | undefined; + creator?: User$Outbound | undefined; + tags?: Array | undefined; + lastUpdated?: string | undefined; + callbackUrl?: string | undefined; +}; + +/** @internal */ +export const Planet$outboundSchema: z.ZodType< + Planet$Outbound, + z.ZodTypeDef, + Planet +> = z.object({ + id: z.number().int(), + name: z.string(), + description: z.nullable(z.string()).optional(), + type: Type$outboundSchema.optional(), + habitabilityIndex: z.number().optional(), + physicalProperties: z.lazy(() => PhysicalProperties$outboundSchema) + .optional(), + atmosphere: z.array(z.lazy(() => Atmosphere$outboundSchema)).optional(), + discoveredAt: z.date().transform(v => v.toISOString()).optional(), + image: z.nullable(z.string()).optional(), + satellites: z.array(Satellite$outboundSchema).optional(), + creator: User$outboundSchema.optional(), + tags: z.array(z.string()).optional(), + lastUpdated: z.date().transform(v => v.toISOString()).optional(), + callbackUrl: 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 Planet$ { + /** @deprecated use `Planet$inboundSchema` instead. */ + export const inboundSchema = Planet$inboundSchema; + /** @deprecated use `Planet$outboundSchema` instead. */ + export const outboundSchema = Planet$outboundSchema; + /** @deprecated use `Planet$Outbound` instead. */ + export type Outbound = Planet$Outbound; +} + +export function planetToJSON(planet: Planet): string { + return JSON.stringify(Planet$outboundSchema.parse(planet)); +} + +export function planetFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Planet$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Planet' from JSON`, + ); +} + +/** @internal */ +export const PlanetInput$inboundSchema: z.ZodType< + PlanetInput, + z.ZodTypeDef, + unknown +> = z.object({ + name: z.string(), + description: z.nullable(z.string()).optional(), + type: Type$inboundSchema.optional(), + habitabilityIndex: z.number().optional(), + physicalProperties: z.lazy(() => PhysicalProperties$inboundSchema).optional(), + atmosphere: z.array(z.lazy(() => Atmosphere$inboundSchema)).optional(), + discoveredAt: z.string().datetime({ offset: true }).transform(v => + new Date(v) + ).optional(), + image: z.nullable(z.string()).optional(), + satellites: z.array(Satellite$inboundSchema).optional(), + creator: UserInput$inboundSchema.optional(), + tags: z.array(z.string()).optional(), + callbackUrl: z.string().optional(), +}); + +/** @internal */ +export type PlanetInput$Outbound = { + name: string; + description?: string | null | undefined; + type?: string | undefined; + habitabilityIndex?: number | undefined; + physicalProperties?: PhysicalProperties$Outbound | undefined; + atmosphere?: Array | undefined; + discoveredAt?: string | undefined; + image?: string | null | undefined; + satellites?: Array | undefined; + creator?: UserInput$Outbound | undefined; + tags?: Array | undefined; + callbackUrl?: string | undefined; +}; + +/** @internal */ +export const PlanetInput$outboundSchema: z.ZodType< + PlanetInput$Outbound, + z.ZodTypeDef, + PlanetInput +> = z.object({ + name: z.string(), + description: z.nullable(z.string()).optional(), + type: Type$outboundSchema.optional(), + habitabilityIndex: z.number().optional(), + physicalProperties: z.lazy(() => PhysicalProperties$outboundSchema) + .optional(), + atmosphere: z.array(z.lazy(() => Atmosphere$outboundSchema)).optional(), + discoveredAt: z.date().transform(v => v.toISOString()).optional(), + image: z.nullable(z.string()).optional(), + satellites: z.array(Satellite$outboundSchema).optional(), + creator: UserInput$outboundSchema.optional(), + tags: z.array(z.string()).optional(), + callbackUrl: 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 PlanetInput$ { + /** @deprecated use `PlanetInput$inboundSchema` instead. */ + export const inboundSchema = PlanetInput$inboundSchema; + /** @deprecated use `PlanetInput$outboundSchema` instead. */ + export const outboundSchema = PlanetInput$outboundSchema; + /** @deprecated use `PlanetInput$Outbound` instead. */ + export type Outbound = PlanetInput$Outbound; +} + +export function planetInputToJSON(planetInput: PlanetInput): string { + return JSON.stringify(PlanetInput$outboundSchema.parse(planetInput)); +} + +export function planetInputFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => PlanetInput$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'PlanetInput' from JSON`, + ); +} diff --git a/src/models/components/satellite.ts b/src/models/components/satellite.ts new file mode 100644 index 0000000..9938913 --- /dev/null +++ b/src/models/components/satellite.ts @@ -0,0 +1,72 @@ +/* + * 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"; + +/** + * A natural satellite (moon) orbiting a planet + */ +export type Satellite = { + name: string; + /** + * Diameter in kilometers + */ + diameter?: number | undefined; +}; + +/** @internal */ +export const Satellite$inboundSchema: z.ZodType< + Satellite, + z.ZodTypeDef, + unknown +> = z.object({ + name: z.string(), + diameter: z.number().optional(), +}); + +/** @internal */ +export type Satellite$Outbound = { + name: string; + diameter?: number | undefined; +}; + +/** @internal */ +export const Satellite$outboundSchema: z.ZodType< + Satellite$Outbound, + z.ZodTypeDef, + Satellite +> = z.object({ + name: z.string(), + diameter: z.number().optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace Satellite$ { + /** @deprecated use `Satellite$inboundSchema` instead. */ + export const inboundSchema = Satellite$inboundSchema; + /** @deprecated use `Satellite$outboundSchema` instead. */ + export const outboundSchema = Satellite$outboundSchema; + /** @deprecated use `Satellite$Outbound` instead. */ + export type Outbound = Satellite$Outbound; +} + +export function satelliteToJSON(satellite: Satellite): string { + return JSON.stringify(Satellite$outboundSchema.parse(satellite)); +} + +export function satelliteFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Satellite$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Satellite' from JSON`, + ); +} diff --git a/src/models/components/schemebasicauth.ts b/src/models/components/schemebasicauth.ts new file mode 100644 index 0000000..0e124ee --- /dev/null +++ b/src/models/components/schemebasicauth.ts @@ -0,0 +1,68 @@ +/* + * 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 SchemeBasicAuth = { + username: string; + password: string; +}; + +/** @internal */ +export const SchemeBasicAuth$inboundSchema: z.ZodType< + SchemeBasicAuth, + z.ZodTypeDef, + unknown +> = z.object({ + username: z.string(), + password: z.string(), +}); + +/** @internal */ +export type SchemeBasicAuth$Outbound = { + username: string; + password: string; +}; + +/** @internal */ +export const SchemeBasicAuth$outboundSchema: z.ZodType< + SchemeBasicAuth$Outbound, + z.ZodTypeDef, + SchemeBasicAuth +> = z.object({ + username: z.string(), + password: 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 SchemeBasicAuth$ { + /** @deprecated use `SchemeBasicAuth$inboundSchema` instead. */ + export const inboundSchema = SchemeBasicAuth$inboundSchema; + /** @deprecated use `SchemeBasicAuth$outboundSchema` instead. */ + export const outboundSchema = SchemeBasicAuth$outboundSchema; + /** @deprecated use `SchemeBasicAuth$Outbound` instead. */ + export type Outbound = SchemeBasicAuth$Outbound; +} + +export function schemeBasicAuthToJSON( + schemeBasicAuth: SchemeBasicAuth, +): string { + return JSON.stringify(SchemeBasicAuth$outboundSchema.parse(schemeBasicAuth)); +} + +export function schemeBasicAuthFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => SchemeBasicAuth$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'SchemeBasicAuth' from JSON`, + ); +} diff --git a/src/models/components/schemeoauth2.ts b/src/models/components/schemeoauth2.ts new file mode 100644 index 0000000..88b0a05 --- /dev/null +++ b/src/models/components/schemeoauth2.ts @@ -0,0 +1,70 @@ +/* + * 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 SchemeOAuth2 = { + clientID: string; + clientSecret: string; + tokenURL?: string | undefined; +}; + +/** @internal */ +export const SchemeOAuth2$inboundSchema: z.ZodType< + SchemeOAuth2, + z.ZodTypeDef, + unknown +> = z.object({ + clientID: z.string(), + clientSecret: z.string(), + tokenURL: z.string().default("https://galaxy.scalar.com/oauth/token"), +}); + +/** @internal */ +export type SchemeOAuth2$Outbound = { + clientID: string; + clientSecret: string; + tokenURL: string; +}; + +/** @internal */ +export const SchemeOAuth2$outboundSchema: z.ZodType< + SchemeOAuth2$Outbound, + z.ZodTypeDef, + SchemeOAuth2 +> = z.object({ + clientID: z.string(), + clientSecret: z.string(), + tokenURL: z.string().default("https://galaxy.scalar.com/oauth/token"), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace SchemeOAuth2$ { + /** @deprecated use `SchemeOAuth2$inboundSchema` instead. */ + export const inboundSchema = SchemeOAuth2$inboundSchema; + /** @deprecated use `SchemeOAuth2$outboundSchema` instead. */ + export const outboundSchema = SchemeOAuth2$outboundSchema; + /** @deprecated use `SchemeOAuth2$Outbound` instead. */ + export type Outbound = SchemeOAuth2$Outbound; +} + +export function schemeOAuth2ToJSON(schemeOAuth2: SchemeOAuth2): string { + return JSON.stringify(SchemeOAuth2$outboundSchema.parse(schemeOAuth2)); +} + +export function schemeOAuth2FromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => SchemeOAuth2$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'SchemeOAuth2' from JSON`, + ); +} diff --git a/src/models/components/security.ts b/src/models/components/security.ts new file mode 100644 index 0000000..9847d48 --- /dev/null +++ b/src/models/components/security.ts @@ -0,0 +1,98 @@ +/* + * 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"; +import { + SchemeBasicAuth, + SchemeBasicAuth$inboundSchema, + SchemeBasicAuth$Outbound, + SchemeBasicAuth$outboundSchema, +} from "./schemebasicauth.js"; +import { + SchemeOAuth2, + SchemeOAuth2$inboundSchema, + SchemeOAuth2$Outbound, + SchemeOAuth2$outboundSchema, +} from "./schemeoauth2.js"; + +export type Security = { + bearerAuth?: string | undefined; + basicAuth?: SchemeBasicAuth | undefined; + apiKeyQuery?: string | undefined; + apiKeyHeader?: string | undefined; + apiKeyCookie?: string | undefined; + oAuth2?: SchemeOAuth2 | undefined; + openIdConnect?: string | undefined; +}; + +/** @internal */ +export const Security$inboundSchema: z.ZodType< + Security, + z.ZodTypeDef, + unknown +> = z.object({ + bearerAuth: z.string().optional(), + basicAuth: SchemeBasicAuth$inboundSchema.optional(), + apiKeyQuery: z.string().optional(), + apiKeyHeader: z.string().optional(), + apiKeyCookie: z.string().optional(), + oAuth2: SchemeOAuth2$inboundSchema.optional(), + openIdConnect: z.string().optional(), +}); + +/** @internal */ +export type Security$Outbound = { + bearerAuth?: string | undefined; + basicAuth?: SchemeBasicAuth$Outbound | undefined; + apiKeyQuery?: string | undefined; + apiKeyHeader?: string | undefined; + apiKeyCookie?: string | undefined; + oAuth2?: SchemeOAuth2$Outbound | undefined; + openIdConnect?: string | undefined; +}; + +/** @internal */ +export const Security$outboundSchema: z.ZodType< + Security$Outbound, + z.ZodTypeDef, + Security +> = z.object({ + bearerAuth: z.string().optional(), + basicAuth: SchemeBasicAuth$outboundSchema.optional(), + apiKeyQuery: z.string().optional(), + apiKeyHeader: z.string().optional(), + apiKeyCookie: z.string().optional(), + oAuth2: SchemeOAuth2$outboundSchema.optional(), + openIdConnect: 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 Security$ { + /** @deprecated use `Security$inboundSchema` instead. */ + export const inboundSchema = Security$inboundSchema; + /** @deprecated use `Security$outboundSchema` instead. */ + export const outboundSchema = Security$outboundSchema; + /** @deprecated use `Security$Outbound` instead. */ + export type Outbound = Security$Outbound; +} + +export function securityToJSON(security: Security): string { + return JSON.stringify(Security$outboundSchema.parse(security)); +} + +export function securityFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Security$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Security' from JSON`, + ); +} diff --git a/src/models/components/token.ts b/src/models/components/token.ts new file mode 100644 index 0000000..852b957 --- /dev/null +++ b/src/models/components/token.ts @@ -0,0 +1,62 @@ +/* + * 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"; + +/** + * A token to authenticate a user + */ +export type Token = { + token?: string | undefined; +}; + +/** @internal */ +export const Token$inboundSchema: z.ZodType = z + .object({ + token: z.string().optional(), + }); + +/** @internal */ +export type Token$Outbound = { + token?: string | undefined; +}; + +/** @internal */ +export const Token$outboundSchema: z.ZodType< + Token$Outbound, + z.ZodTypeDef, + Token +> = z.object({ + token: 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 Token$ { + /** @deprecated use `Token$inboundSchema` instead. */ + export const inboundSchema = Token$inboundSchema; + /** @deprecated use `Token$outboundSchema` instead. */ + export const outboundSchema = Token$outboundSchema; + /** @deprecated use `Token$Outbound` instead. */ + export type Outbound = Token$Outbound; +} + +export function tokenToJSON(token: Token): string { + return JSON.stringify(Token$outboundSchema.parse(token)); +} + +export function tokenFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Token$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Token' from JSON`, + ); +} diff --git a/src/models/components/user.ts b/src/models/components/user.ts new file mode 100644 index 0000000..4c72f42 --- /dev/null +++ b/src/models/components/user.ts @@ -0,0 +1,63 @@ +/* + * 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"; + +/** + * A user + */ +export type User = { + id?: number | undefined; + name?: string | undefined; +}; + +/** @internal */ +export const User$inboundSchema: z.ZodType = z + .object({ + id: z.number().int().optional(), + name: z.string().optional(), + }); + +/** @internal */ +export type User$Outbound = { + id?: number | undefined; + name?: string | undefined; +}; + +/** @internal */ +export const User$outboundSchema: z.ZodType = + z.object({ + id: z.number().int().optional(), + name: z.string().optional(), + }); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace User$ { + /** @deprecated use `User$inboundSchema` instead. */ + export const inboundSchema = User$inboundSchema; + /** @deprecated use `User$outboundSchema` instead. */ + export const outboundSchema = User$outboundSchema; + /** @deprecated use `User$Outbound` instead. */ + export type Outbound = User$Outbound; +} + +export function userToJSON(user: User): string { + return JSON.stringify(User$outboundSchema.parse(user)); +} + +export function userFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => User$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'User' from JSON`, + ); +} diff --git a/src/models/components/userinput.ts b/src/models/components/userinput.ts new file mode 100644 index 0000000..6025b9c --- /dev/null +++ b/src/models/components/userinput.ts @@ -0,0 +1,65 @@ +/* + * 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"; + +/** + * A user + */ +export type UserInput = { + name?: string | undefined; +}; + +/** @internal */ +export const UserInput$inboundSchema: z.ZodType< + UserInput, + z.ZodTypeDef, + unknown +> = z.object({ + name: z.string().optional(), +}); + +/** @internal */ +export type UserInput$Outbound = { + name?: string | undefined; +}; + +/** @internal */ +export const UserInput$outboundSchema: z.ZodType< + UserInput$Outbound, + z.ZodTypeDef, + UserInput +> = z.object({ + name: z.string().optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UserInput$ { + /** @deprecated use `UserInput$inboundSchema` instead. */ + export const inboundSchema = UserInput$inboundSchema; + /** @deprecated use `UserInput$outboundSchema` instead. */ + export const outboundSchema = UserInput$outboundSchema; + /** @deprecated use `UserInput$Outbound` instead. */ + export type Outbound = UserInput$Outbound; +} + +export function userInputToJSON(userInput: UserInput): string { + return JSON.stringify(UserInput$outboundSchema.parse(userInput)); +} + +export function userInputFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UserInput$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UserInput' from JSON`, + ); +} diff --git a/src/models/errors/apierror.ts b/src/models/errors/apierror.ts new file mode 100644 index 0000000..53eb82d --- /dev/null +++ b/src/models/errors/apierror.ts @@ -0,0 +1,34 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ScalarGalaxyTypescriptError } from "./scalargalaxytypescripterror.js"; + +/** The fallback error class if no more specific error class is matched */ +export class APIError extends ScalarGalaxyTypescriptError { + constructor( + message: string, + httpMeta: { + response: Response; + request: Request; + body: string; + }, + ) { + if (message) { + message += `: `; + } + message += `Status ${httpMeta.response.status}`; + const contentType = httpMeta.response.headers.get("content-type") || `""`; + if (contentType !== "application/json") { + message += ` Content-Type ${ + contentType.includes(" ") ? `"${contentType}"` : contentType + }`; + } + const body = httpMeta.body || `""`; + message += body.length > 100 ? "\n" : " "; + message += `Body ${body}`; + message = message.trim(); + super(message, httpMeta); + this.name = "APIError"; + } +} 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 new file mode 100644 index 0000000..8fae157 --- /dev/null +++ b/src/models/errors/index.ts @@ -0,0 +1,8 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./apierror.js"; +export * from "./httpclienterrors.js"; +export * from "./responsevalidationerror.js"; +export * from "./sdkvalidationerror.js"; diff --git a/src/models/errors/responsevalidationerror.ts b/src/models/errors/responsevalidationerror.ts new file mode 100644 index 0000000..5a9103a --- /dev/null +++ b/src/models/errors/responsevalidationerror.ts @@ -0,0 +1,50 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import { ScalarGalaxyTypescriptError } from "./scalargalaxytypescripterror.js"; +import { formatZodError } from "./sdkvalidationerror.js"; + +export class ResponseValidationError extends ScalarGalaxyTypescriptError { + /** + * The raw value that failed validation. + */ + public readonly rawValue: unknown; + + /** + * The raw message that failed validation. + */ + public readonly rawMessage: unknown; + + constructor( + message: string, + extra: { + response: Response; + request: Request; + body: string; + cause: unknown; + rawValue: unknown; + rawMessage: unknown; + }, + ) { + super(message, extra); + this.name = "ResponseValidationError"; + this.cause = extra.cause; + this.rawValue = extra.rawValue; + this.rawMessage = extra.rawMessage; + } + + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + public pretty(): string { + if (this.cause instanceof z.ZodError) { + return `${this.rawMessage}\n${formatZodError(this.cause)}`; + } else { + return this.toString(); + } + } +} diff --git a/src/models/errors/scalargalaxytypescripterror.ts b/src/models/errors/scalargalaxytypescripterror.ts new file mode 100644 index 0000000..2d56cb5 --- /dev/null +++ b/src/models/errors/scalargalaxytypescripterror.ts @@ -0,0 +1,35 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +/** The base class for all HTTP error responses */ +export class ScalarGalaxyTypescriptError extends Error { + /** HTTP status code */ + public readonly statusCode: number; + /** HTTP body */ + public readonly body: string; + /** HTTP headers */ + public readonly headers: Headers; + /** HTTP content type */ + public readonly contentType: string; + /** Raw response */ + public readonly rawResponse: Response; + + constructor( + message: string, + httpMeta: { + response: Response; + request: Request; + body: string; + }, + ) { + super(message); + this.statusCode = httpMeta.response.status; + this.body = httpMeta.body; + this.headers = httpMeta.response.headers; + this.contentType = httpMeta.response.headers.get("content-type") || ""; + this.rawResponse = httpMeta.response; + + this.name = "ScalarGalaxyTypescriptError"; + } +} diff --git a/src/models/errors/sdkvalidationerror.ts b/src/models/errors/sdkvalidationerror.ts new file mode 100644 index 0000000..37face8 --- /dev/null +++ b/src/models/errors/sdkvalidationerror.ts @@ -0,0 +1,109 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; + +export class SDKValidationError extends Error { + /** + * The raw value that failed validation. + */ + public readonly rawValue: unknown; + + /** + * The raw message that failed validation. + */ + public readonly rawMessage: unknown; + + // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError` + static override [Symbol.hasInstance]( + instance: unknown, + ): instance is SDKValidationError { + if (!(instance instanceof Error)) return false; + if (!("rawValue" in instance)) return false; + if (!("rawMessage" in instance)) return false; + if (!("pretty" in instance)) return false; + if (typeof instance.pretty !== "function") return false; + return true; + } + + constructor(message: string, cause: unknown, rawValue: unknown) { + super(`${message}: ${cause}`); + this.name = "SDKValidationError"; + this.cause = cause; + this.rawValue = rawValue; + this.rawMessage = message; + } + + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + public pretty(): string { + if (this.cause instanceof z.ZodError) { + return `${this.rawMessage}\n${formatZodError(this.cause)}`; + } else { + return this.toString(); + } + } +} + +export function formatZodError(err: z.ZodError, level = 0): string { + let pre = " ".repeat(level); + pre = level > 0 ? `โ”‚${pre}` : pre; + pre += " ".repeat(level); + + let message = ""; + const append = (str: string) => (message += `\n${pre}${str}`); + + const len = err.issues.length; + const headline = len === 1 ? `${len} issue found` : `${len} issues found`; + + if (len) { + append(`โ”Œ ${headline}:`); + } + + for (const issue of err.issues) { + let path = issue.path.join("."); + path = path ? `.${path}` : ""; + append(`โ”‚ โ€ข [${path}]: ${issue.message} (${issue.code})`); + switch (issue.code) { + case "invalid_literal": + case "invalid_type": { + append(`โ”‚ Want: ${issue.expected}`); + append(`โ”‚ Got: ${issue.received}`); + break; + } + case "unrecognized_keys": { + append(`โ”‚ Keys: ${issue.keys.join(", ")}`); + break; + } + case "invalid_enum_value": { + append(`โ”‚ Allowed: ${issue.options.join(", ")}`); + append(`โ”‚ Got: ${issue.received}`); + break; + } + case "invalid_union_discriminator": { + append(`โ”‚ Allowed: ${issue.options.join(", ")}`); + break; + } + case "invalid_union": { + const len = issue.unionErrors.length; + append( + `โ”‚ โœ–๏ธŽ Attemped to deserialize into one of ${len} union members:`, + ); + issue.unionErrors.forEach((err, i) => { + append(`โ”‚ โœ–๏ธŽ Member ${i + 1} of ${len}`); + append(`${formatZodError(err, level + 1)}`); + }); + } + } + } + + if (err.issues.length) { + append(`โ””โ”€*`); + } + + return message.slice(1); +} diff --git a/src/models/operations/createplanetjson.ts b/src/models/operations/createplanetjson.ts new file mode 100644 index 0000000..d44001e --- /dev/null +++ b/src/models/operations/createplanetjson.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type CreatePlanetJsonResponse = components.Planet | Uint8Array | string; + +/** @internal */ +export const CreatePlanetJsonResponse$inboundSchema: z.ZodType< + CreatePlanetJsonResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Planet$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type CreatePlanetJsonResponse$Outbound = + | components.Planet$Outbound + | Uint8Array; + +/** @internal */ +export const CreatePlanetJsonResponse$outboundSchema: z.ZodType< + CreatePlanetJsonResponse$Outbound, + z.ZodTypeDef, + CreatePlanetJsonResponse +> = z.union([components.Planet$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace CreatePlanetJsonResponse$ { + /** @deprecated use `CreatePlanetJsonResponse$inboundSchema` instead. */ + export const inboundSchema = CreatePlanetJsonResponse$inboundSchema; + /** @deprecated use `CreatePlanetJsonResponse$outboundSchema` instead. */ + export const outboundSchema = CreatePlanetJsonResponse$outboundSchema; + /** @deprecated use `CreatePlanetJsonResponse$Outbound` instead. */ + export type Outbound = CreatePlanetJsonResponse$Outbound; +} + +export function createPlanetJsonResponseToJSON( + createPlanetJsonResponse: CreatePlanetJsonResponse, +): string { + return JSON.stringify( + CreatePlanetJsonResponse$outboundSchema.parse(createPlanetJsonResponse), + ); +} + +export function createPlanetJsonResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreatePlanetJsonResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreatePlanetJsonResponse' from JSON`, + ); +} diff --git a/src/models/operations/createplanetraw.ts b/src/models/operations/createplanetraw.ts new file mode 100644 index 0000000..6858294 --- /dev/null +++ b/src/models/operations/createplanetraw.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type CreatePlanetRawResponse = components.Planet | Uint8Array | string; + +/** @internal */ +export const CreatePlanetRawResponse$inboundSchema: z.ZodType< + CreatePlanetRawResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Planet$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type CreatePlanetRawResponse$Outbound = + | components.Planet$Outbound + | Uint8Array; + +/** @internal */ +export const CreatePlanetRawResponse$outboundSchema: z.ZodType< + CreatePlanetRawResponse$Outbound, + z.ZodTypeDef, + CreatePlanetRawResponse +> = z.union([components.Planet$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace CreatePlanetRawResponse$ { + /** @deprecated use `CreatePlanetRawResponse$inboundSchema` instead. */ + export const inboundSchema = CreatePlanetRawResponse$inboundSchema; + /** @deprecated use `CreatePlanetRawResponse$outboundSchema` instead. */ + export const outboundSchema = CreatePlanetRawResponse$outboundSchema; + /** @deprecated use `CreatePlanetRawResponse$Outbound` instead. */ + export type Outbound = CreatePlanetRawResponse$Outbound; +} + +export function createPlanetRawResponseToJSON( + createPlanetRawResponse: CreatePlanetRawResponse, +): string { + return JSON.stringify( + CreatePlanetRawResponse$outboundSchema.parse(createPlanetRawResponse), + ); +} + +export function createPlanetRawResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreatePlanetRawResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreatePlanetRawResponse' from JSON`, + ); +} diff --git a/src/models/operations/createuserjson.ts b/src/models/operations/createuserjson.ts new file mode 100644 index 0000000..793b3c8 --- /dev/null +++ b/src/models/operations/createuserjson.ts @@ -0,0 +1,131 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +/** + * Credentials to authenticate a user + */ +export type CreateUserJsonRequestBody = { + name?: string | undefined; + email: string; + password: string; +}; + +export type CreateUserJsonResponse = components.User | Uint8Array | string; + +/** @internal */ +export const CreateUserJsonRequestBody$inboundSchema: z.ZodType< + CreateUserJsonRequestBody, + z.ZodTypeDef, + unknown +> = z.object({ + name: z.string().optional(), + email: z.string(), + password: z.string(), +}); + +/** @internal */ +export type CreateUserJsonRequestBody$Outbound = { + name?: string | undefined; + email: string; + password: string; +}; + +/** @internal */ +export const CreateUserJsonRequestBody$outboundSchema: z.ZodType< + CreateUserJsonRequestBody$Outbound, + z.ZodTypeDef, + CreateUserJsonRequestBody +> = z.object({ + name: z.string().optional(), + email: z.string(), + password: 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 CreateUserJsonRequestBody$ { + /** @deprecated use `CreateUserJsonRequestBody$inboundSchema` instead. */ + export const inboundSchema = CreateUserJsonRequestBody$inboundSchema; + /** @deprecated use `CreateUserJsonRequestBody$outboundSchema` instead. */ + export const outboundSchema = CreateUserJsonRequestBody$outboundSchema; + /** @deprecated use `CreateUserJsonRequestBody$Outbound` instead. */ + export type Outbound = CreateUserJsonRequestBody$Outbound; +} + +export function createUserJsonRequestBodyToJSON( + createUserJsonRequestBody: CreateUserJsonRequestBody, +): string { + return JSON.stringify( + CreateUserJsonRequestBody$outboundSchema.parse(createUserJsonRequestBody), + ); +} + +export function createUserJsonRequestBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateUserJsonRequestBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateUserJsonRequestBody' from JSON`, + ); +} + +/** @internal */ +export const CreateUserJsonResponse$inboundSchema: z.ZodType< + CreateUserJsonResponse, + z.ZodTypeDef, + unknown +> = z.union([components.User$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type CreateUserJsonResponse$Outbound = + | components.User$Outbound + | Uint8Array; + +/** @internal */ +export const CreateUserJsonResponse$outboundSchema: z.ZodType< + CreateUserJsonResponse$Outbound, + z.ZodTypeDef, + CreateUserJsonResponse +> = z.union([components.User$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace CreateUserJsonResponse$ { + /** @deprecated use `CreateUserJsonResponse$inboundSchema` instead. */ + export const inboundSchema = CreateUserJsonResponse$inboundSchema; + /** @deprecated use `CreateUserJsonResponse$outboundSchema` instead. */ + export const outboundSchema = CreateUserJsonResponse$outboundSchema; + /** @deprecated use `CreateUserJsonResponse$Outbound` instead. */ + export type Outbound = CreateUserJsonResponse$Outbound; +} + +export function createUserJsonResponseToJSON( + createUserJsonResponse: CreateUserJsonResponse, +): string { + return JSON.stringify( + CreateUserJsonResponse$outboundSchema.parse(createUserJsonResponse), + ); +} + +export function createUserJsonResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateUserJsonResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateUserJsonResponse' from JSON`, + ); +} diff --git a/src/models/operations/createuserraw.ts b/src/models/operations/createuserraw.ts new file mode 100644 index 0000000..ce0cff4 --- /dev/null +++ b/src/models/operations/createuserraw.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type CreateUserRawResponse = components.User | Uint8Array | string; + +/** @internal */ +export const CreateUserRawResponse$inboundSchema: z.ZodType< + CreateUserRawResponse, + z.ZodTypeDef, + unknown +> = z.union([components.User$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type CreateUserRawResponse$Outbound = + | components.User$Outbound + | Uint8Array; + +/** @internal */ +export const CreateUserRawResponse$outboundSchema: z.ZodType< + CreateUserRawResponse$Outbound, + z.ZodTypeDef, + CreateUserRawResponse +> = z.union([components.User$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace CreateUserRawResponse$ { + /** @deprecated use `CreateUserRawResponse$inboundSchema` instead. */ + export const inboundSchema = CreateUserRawResponse$inboundSchema; + /** @deprecated use `CreateUserRawResponse$outboundSchema` instead. */ + export const outboundSchema = CreateUserRawResponse$outboundSchema; + /** @deprecated use `CreateUserRawResponse$Outbound` instead. */ + export type Outbound = CreateUserRawResponse$Outbound; +} + +export function createUserRawResponseToJSON( + createUserRawResponse: CreateUserRawResponse, +): string { + return JSON.stringify( + CreateUserRawResponse$outboundSchema.parse(createUserRawResponse), + ); +} + +export function createUserRawResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => CreateUserRawResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'CreateUserRawResponse' from JSON`, + ); +} diff --git a/src/models/operations/deleteplanet.ts b/src/models/operations/deleteplanet.ts new file mode 100644 index 0000000..cc0d629 --- /dev/null +++ b/src/models/operations/deleteplanet.ts @@ -0,0 +1,69 @@ +/* + * 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 DeletePlanetRequest = { + /** + * The ID of the planet to get + */ + planetId: number; +}; + +/** @internal */ +export const DeletePlanetRequest$inboundSchema: z.ZodType< + DeletePlanetRequest, + z.ZodTypeDef, + unknown +> = z.object({ + planetId: z.number().int(), +}); + +/** @internal */ +export type DeletePlanetRequest$Outbound = { + planetId: number; +}; + +/** @internal */ +export const DeletePlanetRequest$outboundSchema: z.ZodType< + DeletePlanetRequest$Outbound, + z.ZodTypeDef, + DeletePlanetRequest +> = z.object({ + planetId: z.number().int(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace DeletePlanetRequest$ { + /** @deprecated use `DeletePlanetRequest$inboundSchema` instead. */ + export const inboundSchema = DeletePlanetRequest$inboundSchema; + /** @deprecated use `DeletePlanetRequest$outboundSchema` instead. */ + export const outboundSchema = DeletePlanetRequest$outboundSchema; + /** @deprecated use `DeletePlanetRequest$Outbound` instead. */ + export type Outbound = DeletePlanetRequest$Outbound; +} + +export function deletePlanetRequestToJSON( + deletePlanetRequest: DeletePlanetRequest, +): string { + return JSON.stringify( + DeletePlanetRequest$outboundSchema.parse(deletePlanetRequest), + ); +} + +export function deletePlanetRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => DeletePlanetRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'DeletePlanetRequest' from JSON`, + ); +} diff --git a/src/models/operations/getalldata.ts b/src/models/operations/getalldata.ts new file mode 100644 index 0000000..6adc610 --- /dev/null +++ b/src/models/operations/getalldata.ts @@ -0,0 +1,394 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type GetAllDataRequest = { + /** + * The number of items to return + */ + limit?: number | undefined; + /** + * The number of items to skip before starting to collect the result set + */ + offset?: number | undefined; +}; + +export type GetAllDataMeta = { + limit?: number | undefined; + offset?: number | undefined; + total?: number | undefined; + next?: string | null | undefined; +}; + +/** + * A paginated resource + */ +export type GetAllDataPlanetsResponseBody = { + data?: Array | undefined; + meta?: GetAllDataMeta | undefined; +}; + +export type Meta = { + limit?: number | undefined; + offset?: number | undefined; + total?: number | undefined; + next?: string | null | undefined; +}; + +/** + * A paginated resource + */ +export type GetAllDataResponseBody = { + data?: Array | undefined; + meta?: Meta | undefined; +}; + +export type GetAllDataResponse = GetAllDataResponseBody | Uint8Array | string; + +/** @internal */ +export const GetAllDataRequest$inboundSchema: z.ZodType< + GetAllDataRequest, + z.ZodTypeDef, + unknown +> = z.object({ + limit: z.number().int().default(10), + offset: z.number().int().default(0), +}); + +/** @internal */ +export type GetAllDataRequest$Outbound = { + limit: number; + offset: number; +}; + +/** @internal */ +export const GetAllDataRequest$outboundSchema: z.ZodType< + GetAllDataRequest$Outbound, + z.ZodTypeDef, + GetAllDataRequest +> = z.object({ + limit: z.number().int().default(10), + offset: z.number().int().default(0), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetAllDataRequest$ { + /** @deprecated use `GetAllDataRequest$inboundSchema` instead. */ + export const inboundSchema = GetAllDataRequest$inboundSchema; + /** @deprecated use `GetAllDataRequest$outboundSchema` instead. */ + export const outboundSchema = GetAllDataRequest$outboundSchema; + /** @deprecated use `GetAllDataRequest$Outbound` instead. */ + export type Outbound = GetAllDataRequest$Outbound; +} + +export function getAllDataRequestToJSON( + getAllDataRequest: GetAllDataRequest, +): string { + return JSON.stringify( + GetAllDataRequest$outboundSchema.parse(getAllDataRequest), + ); +} + +export function getAllDataRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetAllDataRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetAllDataRequest' from JSON`, + ); +} + +/** @internal */ +export const GetAllDataMeta$inboundSchema: z.ZodType< + GetAllDataMeta, + z.ZodTypeDef, + unknown +> = z.object({ + limit: z.number().int().optional(), + offset: z.number().int().optional(), + total: z.number().int().optional(), + next: z.nullable(z.string()).optional(), +}); + +/** @internal */ +export type GetAllDataMeta$Outbound = { + limit?: number | undefined; + offset?: number | undefined; + total?: number | undefined; + next?: string | null | undefined; +}; + +/** @internal */ +export const GetAllDataMeta$outboundSchema: z.ZodType< + GetAllDataMeta$Outbound, + z.ZodTypeDef, + GetAllDataMeta +> = z.object({ + limit: z.number().int().optional(), + offset: z.number().int().optional(), + total: z.number().int().optional(), + next: z.nullable(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 GetAllDataMeta$ { + /** @deprecated use `GetAllDataMeta$inboundSchema` instead. */ + export const inboundSchema = GetAllDataMeta$inboundSchema; + /** @deprecated use `GetAllDataMeta$outboundSchema` instead. */ + export const outboundSchema = GetAllDataMeta$outboundSchema; + /** @deprecated use `GetAllDataMeta$Outbound` instead. */ + export type Outbound = GetAllDataMeta$Outbound; +} + +export function getAllDataMetaToJSON(getAllDataMeta: GetAllDataMeta): string { + return JSON.stringify(GetAllDataMeta$outboundSchema.parse(getAllDataMeta)); +} + +export function getAllDataMetaFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetAllDataMeta$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetAllDataMeta' from JSON`, + ); +} + +/** @internal */ +export const GetAllDataPlanetsResponseBody$inboundSchema: z.ZodType< + GetAllDataPlanetsResponseBody, + z.ZodTypeDef, + unknown +> = z.object({ + data: z.array(components.Planet$inboundSchema).optional(), + meta: z.lazy(() => GetAllDataMeta$inboundSchema).optional(), +}); + +/** @internal */ +export type GetAllDataPlanetsResponseBody$Outbound = { + data?: Array | undefined; + meta?: GetAllDataMeta$Outbound | undefined; +}; + +/** @internal */ +export const GetAllDataPlanetsResponseBody$outboundSchema: z.ZodType< + GetAllDataPlanetsResponseBody$Outbound, + z.ZodTypeDef, + GetAllDataPlanetsResponseBody +> = z.object({ + data: z.array(components.Planet$outboundSchema).optional(), + meta: z.lazy(() => GetAllDataMeta$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 GetAllDataPlanetsResponseBody$ { + /** @deprecated use `GetAllDataPlanetsResponseBody$inboundSchema` instead. */ + export const inboundSchema = GetAllDataPlanetsResponseBody$inboundSchema; + /** @deprecated use `GetAllDataPlanetsResponseBody$outboundSchema` instead. */ + export const outboundSchema = GetAllDataPlanetsResponseBody$outboundSchema; + /** @deprecated use `GetAllDataPlanetsResponseBody$Outbound` instead. */ + export type Outbound = GetAllDataPlanetsResponseBody$Outbound; +} + +export function getAllDataPlanetsResponseBodyToJSON( + getAllDataPlanetsResponseBody: GetAllDataPlanetsResponseBody, +): string { + return JSON.stringify( + GetAllDataPlanetsResponseBody$outboundSchema.parse( + getAllDataPlanetsResponseBody, + ), + ); +} + +export function getAllDataPlanetsResponseBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetAllDataPlanetsResponseBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetAllDataPlanetsResponseBody' from JSON`, + ); +} + +/** @internal */ +export const Meta$inboundSchema: z.ZodType = z + .object({ + limit: z.number().int().optional(), + offset: z.number().int().optional(), + total: z.number().int().optional(), + next: z.nullable(z.string()).optional(), + }); + +/** @internal */ +export type Meta$Outbound = { + limit?: number | undefined; + offset?: number | undefined; + total?: number | undefined; + next?: string | null | undefined; +}; + +/** @internal */ +export const Meta$outboundSchema: z.ZodType = + z.object({ + limit: z.number().int().optional(), + offset: z.number().int().optional(), + total: z.number().int().optional(), + next: z.nullable(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 Meta$ { + /** @deprecated use `Meta$inboundSchema` instead. */ + export const inboundSchema = Meta$inboundSchema; + /** @deprecated use `Meta$outboundSchema` instead. */ + export const outboundSchema = Meta$outboundSchema; + /** @deprecated use `Meta$Outbound` instead. */ + export type Outbound = Meta$Outbound; +} + +export function metaToJSON(meta: Meta): string { + return JSON.stringify(Meta$outboundSchema.parse(meta)); +} + +export function metaFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Meta$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Meta' from JSON`, + ); +} + +/** @internal */ +export const GetAllDataResponseBody$inboundSchema: z.ZodType< + GetAllDataResponseBody, + z.ZodTypeDef, + unknown +> = z.object({ + data: z.array(components.Planet$inboundSchema).optional(), + meta: z.lazy(() => Meta$inboundSchema).optional(), +}); + +/** @internal */ +export type GetAllDataResponseBody$Outbound = { + data?: Array | undefined; + meta?: Meta$Outbound | undefined; +}; + +/** @internal */ +export const GetAllDataResponseBody$outboundSchema: z.ZodType< + GetAllDataResponseBody$Outbound, + z.ZodTypeDef, + GetAllDataResponseBody +> = z.object({ + data: z.array(components.Planet$outboundSchema).optional(), + meta: z.lazy(() => Meta$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 GetAllDataResponseBody$ { + /** @deprecated use `GetAllDataResponseBody$inboundSchema` instead. */ + export const inboundSchema = GetAllDataResponseBody$inboundSchema; + /** @deprecated use `GetAllDataResponseBody$outboundSchema` instead. */ + export const outboundSchema = GetAllDataResponseBody$outboundSchema; + /** @deprecated use `GetAllDataResponseBody$Outbound` instead. */ + export type Outbound = GetAllDataResponseBody$Outbound; +} + +export function getAllDataResponseBodyToJSON( + getAllDataResponseBody: GetAllDataResponseBody, +): string { + return JSON.stringify( + GetAllDataResponseBody$outboundSchema.parse(getAllDataResponseBody), + ); +} + +export function getAllDataResponseBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetAllDataResponseBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetAllDataResponseBody' from JSON`, + ); +} + +/** @internal */ +export const GetAllDataResponse$inboundSchema: z.ZodType< + GetAllDataResponse, + z.ZodTypeDef, + unknown +> = z.union([ + z.lazy(() => GetAllDataResponseBody$inboundSchema), + b64$.zodInbound, +]); + +/** @internal */ +export type GetAllDataResponse$Outbound = + | GetAllDataResponseBody$Outbound + | Uint8Array; + +/** @internal */ +export const GetAllDataResponse$outboundSchema: z.ZodType< + GetAllDataResponse$Outbound, + z.ZodTypeDef, + GetAllDataResponse +> = z.union([ + z.lazy(() => GetAllDataResponseBody$outboundSchema), + b64$.zodOutbound, +]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetAllDataResponse$ { + /** @deprecated use `GetAllDataResponse$inboundSchema` instead. */ + export const inboundSchema = GetAllDataResponse$inboundSchema; + /** @deprecated use `GetAllDataResponse$outboundSchema` instead. */ + export const outboundSchema = GetAllDataResponse$outboundSchema; + /** @deprecated use `GetAllDataResponse$Outbound` instead. */ + export type Outbound = GetAllDataResponse$Outbound; +} + +export function getAllDataResponseToJSON( + getAllDataResponse: GetAllDataResponse, +): string { + return JSON.stringify( + GetAllDataResponse$outboundSchema.parse(getAllDataResponse), + ); +} + +export function getAllDataResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetAllDataResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetAllDataResponse' from JSON`, + ); +} diff --git a/src/models/operations/getme.ts b/src/models/operations/getme.ts new file mode 100644 index 0000000..678781f --- /dev/null +++ b/src/models/operations/getme.ts @@ -0,0 +1,56 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type GetMeResponse = components.User | Uint8Array | string; + +/** @internal */ +export const GetMeResponse$inboundSchema: z.ZodType< + GetMeResponse, + z.ZodTypeDef, + unknown +> = z.union([components.User$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type GetMeResponse$Outbound = components.User$Outbound | Uint8Array; + +/** @internal */ +export const GetMeResponse$outboundSchema: z.ZodType< + GetMeResponse$Outbound, + z.ZodTypeDef, + GetMeResponse +> = z.union([components.User$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetMeResponse$ { + /** @deprecated use `GetMeResponse$inboundSchema` instead. */ + export const inboundSchema = GetMeResponse$inboundSchema; + /** @deprecated use `GetMeResponse$outboundSchema` instead. */ + export const outboundSchema = GetMeResponse$outboundSchema; + /** @deprecated use `GetMeResponse$Outbound` instead. */ + export type Outbound = GetMeResponse$Outbound; +} + +export function getMeResponseToJSON(getMeResponse: GetMeResponse): string { + return JSON.stringify(GetMeResponse$outboundSchema.parse(getMeResponse)); +} + +export function getMeResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetMeResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetMeResponse' from JSON`, + ); +} diff --git a/src/models/operations/getplanet.ts b/src/models/operations/getplanet.ts new file mode 100644 index 0000000..1051a61 --- /dev/null +++ b/src/models/operations/getplanet.ts @@ -0,0 +1,123 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type GetPlanetRequest = { + /** + * The ID of the planet to get + */ + planetId: number; +}; + +export type GetPlanetResponse = components.Planet | Uint8Array | string; + +/** @internal */ +export const GetPlanetRequest$inboundSchema: z.ZodType< + GetPlanetRequest, + z.ZodTypeDef, + unknown +> = z.object({ + planetId: z.number().int(), +}); + +/** @internal */ +export type GetPlanetRequest$Outbound = { + planetId: number; +}; + +/** @internal */ +export const GetPlanetRequest$outboundSchema: z.ZodType< + GetPlanetRequest$Outbound, + z.ZodTypeDef, + GetPlanetRequest +> = z.object({ + planetId: z.number().int(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetPlanetRequest$ { + /** @deprecated use `GetPlanetRequest$inboundSchema` instead. */ + export const inboundSchema = GetPlanetRequest$inboundSchema; + /** @deprecated use `GetPlanetRequest$outboundSchema` instead. */ + export const outboundSchema = GetPlanetRequest$outboundSchema; + /** @deprecated use `GetPlanetRequest$Outbound` instead. */ + export type Outbound = GetPlanetRequest$Outbound; +} + +export function getPlanetRequestToJSON( + getPlanetRequest: GetPlanetRequest, +): string { + return JSON.stringify( + GetPlanetRequest$outboundSchema.parse(getPlanetRequest), + ); +} + +export function getPlanetRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetPlanetRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetPlanetRequest' from JSON`, + ); +} + +/** @internal */ +export const GetPlanetResponse$inboundSchema: z.ZodType< + GetPlanetResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Planet$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type GetPlanetResponse$Outbound = + | components.Planet$Outbound + | Uint8Array; + +/** @internal */ +export const GetPlanetResponse$outboundSchema: z.ZodType< + GetPlanetResponse$Outbound, + z.ZodTypeDef, + GetPlanetResponse +> = z.union([components.Planet$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetPlanetResponse$ { + /** @deprecated use `GetPlanetResponse$inboundSchema` instead. */ + export const inboundSchema = GetPlanetResponse$inboundSchema; + /** @deprecated use `GetPlanetResponse$outboundSchema` instead. */ + export const outboundSchema = GetPlanetResponse$outboundSchema; + /** @deprecated use `GetPlanetResponse$Outbound` instead. */ + export type Outbound = GetPlanetResponse$Outbound; +} + +export function getPlanetResponseToJSON( + getPlanetResponse: GetPlanetResponse, +): string { + return JSON.stringify( + GetPlanetResponse$outboundSchema.parse(getPlanetResponse), + ); +} + +export function getPlanetResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetPlanetResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetPlanetResponse' from JSON`, + ); +} diff --git a/src/models/operations/gettokenjson.ts b/src/models/operations/gettokenjson.ts new file mode 100644 index 0000000..8021d8e --- /dev/null +++ b/src/models/operations/gettokenjson.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type GetTokenJsonResponse = components.Token | Uint8Array | string; + +/** @internal */ +export const GetTokenJsonResponse$inboundSchema: z.ZodType< + GetTokenJsonResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Token$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type GetTokenJsonResponse$Outbound = + | components.Token$Outbound + | Uint8Array; + +/** @internal */ +export const GetTokenJsonResponse$outboundSchema: z.ZodType< + GetTokenJsonResponse$Outbound, + z.ZodTypeDef, + GetTokenJsonResponse +> = z.union([components.Token$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetTokenJsonResponse$ { + /** @deprecated use `GetTokenJsonResponse$inboundSchema` instead. */ + export const inboundSchema = GetTokenJsonResponse$inboundSchema; + /** @deprecated use `GetTokenJsonResponse$outboundSchema` instead. */ + export const outboundSchema = GetTokenJsonResponse$outboundSchema; + /** @deprecated use `GetTokenJsonResponse$Outbound` instead. */ + export type Outbound = GetTokenJsonResponse$Outbound; +} + +export function getTokenJsonResponseToJSON( + getTokenJsonResponse: GetTokenJsonResponse, +): string { + return JSON.stringify( + GetTokenJsonResponse$outboundSchema.parse(getTokenJsonResponse), + ); +} + +export function getTokenJsonResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetTokenJsonResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetTokenJsonResponse' from JSON`, + ); +} diff --git a/src/models/operations/gettokenraw.ts b/src/models/operations/gettokenraw.ts new file mode 100644 index 0000000..e1eb720 --- /dev/null +++ b/src/models/operations/gettokenraw.ts @@ -0,0 +1,62 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { safeParse } from "../../lib/schemas.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type GetTokenRawResponse = components.Token | Uint8Array | string; + +/** @internal */ +export const GetTokenRawResponse$inboundSchema: z.ZodType< + GetTokenRawResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Token$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type GetTokenRawResponse$Outbound = + | components.Token$Outbound + | Uint8Array; + +/** @internal */ +export const GetTokenRawResponse$outboundSchema: z.ZodType< + GetTokenRawResponse$Outbound, + z.ZodTypeDef, + GetTokenRawResponse +> = z.union([components.Token$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace GetTokenRawResponse$ { + /** @deprecated use `GetTokenRawResponse$inboundSchema` instead. */ + export const inboundSchema = GetTokenRawResponse$inboundSchema; + /** @deprecated use `GetTokenRawResponse$outboundSchema` instead. */ + export const outboundSchema = GetTokenRawResponse$outboundSchema; + /** @deprecated use `GetTokenRawResponse$Outbound` instead. */ + export type Outbound = GetTokenRawResponse$Outbound; +} + +export function getTokenRawResponseToJSON( + getTokenRawResponse: GetTokenRawResponse, +): string { + return JSON.stringify( + GetTokenRawResponse$outboundSchema.parse(getTokenRawResponse), + ); +} + +export function getTokenRawResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => GetTokenRawResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'GetTokenRawResponse' from JSON`, + ); +} diff --git a/src/models/operations/index.ts b/src/models/operations/index.ts new file mode 100644 index 0000000..16e9dcf --- /dev/null +++ b/src/models/operations/index.ts @@ -0,0 +1,17 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./createplanetjson.js"; +export * from "./createplanetraw.js"; +export * from "./createuserjson.js"; +export * from "./createuserraw.js"; +export * from "./deleteplanet.js"; +export * from "./getalldata.js"; +export * from "./getme.js"; +export * from "./getplanet.js"; +export * from "./gettokenjson.js"; +export * from "./gettokenraw.js"; +export * from "./updateplanetjson.js"; +export * from "./updateplanetraw.js"; +export * from "./uploadimage.js"; diff --git a/src/models/operations/updateplanetjson.ts b/src/models/operations/updateplanetjson.ts new file mode 100644 index 0000000..73e83e0 --- /dev/null +++ b/src/models/operations/updateplanetjson.ts @@ -0,0 +1,139 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +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 { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type UpdatePlanetJsonRequest = { + /** + * The ID of the planet to get + */ + planetId: number; + /** + * New information about the planet + */ + planet?: components.PlanetInput | undefined; +}; + +export type UpdatePlanetJsonResponse = components.Planet | Uint8Array | string; + +/** @internal */ +export const UpdatePlanetJsonRequest$inboundSchema: z.ZodType< + UpdatePlanetJsonRequest, + z.ZodTypeDef, + unknown +> = z.object({ + planetId: z.number().int(), + Planet: components.PlanetInput$inboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + "Planet": "planet", + }); +}); + +/** @internal */ +export type UpdatePlanetJsonRequest$Outbound = { + planetId: number; + Planet?: components.PlanetInput$Outbound | undefined; +}; + +/** @internal */ +export const UpdatePlanetJsonRequest$outboundSchema: z.ZodType< + UpdatePlanetJsonRequest$Outbound, + z.ZodTypeDef, + UpdatePlanetJsonRequest +> = z.object({ + planetId: z.number().int(), + planet: components.PlanetInput$outboundSchema.optional(), +}).transform((v) => { + return remap$(v, { + planet: "Planet", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UpdatePlanetJsonRequest$ { + /** @deprecated use `UpdatePlanetJsonRequest$inboundSchema` instead. */ + export const inboundSchema = UpdatePlanetJsonRequest$inboundSchema; + /** @deprecated use `UpdatePlanetJsonRequest$outboundSchema` instead. */ + export const outboundSchema = UpdatePlanetJsonRequest$outboundSchema; + /** @deprecated use `UpdatePlanetJsonRequest$Outbound` instead. */ + export type Outbound = UpdatePlanetJsonRequest$Outbound; +} + +export function updatePlanetJsonRequestToJSON( + updatePlanetJsonRequest: UpdatePlanetJsonRequest, +): string { + return JSON.stringify( + UpdatePlanetJsonRequest$outboundSchema.parse(updatePlanetJsonRequest), + ); +} + +export function updatePlanetJsonRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdatePlanetJsonRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdatePlanetJsonRequest' from JSON`, + ); +} + +/** @internal */ +export const UpdatePlanetJsonResponse$inboundSchema: z.ZodType< + UpdatePlanetJsonResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Planet$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type UpdatePlanetJsonResponse$Outbound = + | components.Planet$Outbound + | Uint8Array; + +/** @internal */ +export const UpdatePlanetJsonResponse$outboundSchema: z.ZodType< + UpdatePlanetJsonResponse$Outbound, + z.ZodTypeDef, + UpdatePlanetJsonResponse +> = z.union([components.Planet$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UpdatePlanetJsonResponse$ { + /** @deprecated use `UpdatePlanetJsonResponse$inboundSchema` instead. */ + export const inboundSchema = UpdatePlanetJsonResponse$inboundSchema; + /** @deprecated use `UpdatePlanetJsonResponse$outboundSchema` instead. */ + export const outboundSchema = UpdatePlanetJsonResponse$outboundSchema; + /** @deprecated use `UpdatePlanetJsonResponse$Outbound` instead. */ + export type Outbound = UpdatePlanetJsonResponse$Outbound; +} + +export function updatePlanetJsonResponseToJSON( + updatePlanetJsonResponse: UpdatePlanetJsonResponse, +): string { + return JSON.stringify( + UpdatePlanetJsonResponse$outboundSchema.parse(updatePlanetJsonResponse), + ); +} + +export function updatePlanetJsonResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdatePlanetJsonResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdatePlanetJsonResponse' from JSON`, + ); +} diff --git a/src/models/operations/updateplanetraw.ts b/src/models/operations/updateplanetraw.ts new file mode 100644 index 0000000..852d2e8 --- /dev/null +++ b/src/models/operations/updateplanetraw.ts @@ -0,0 +1,159 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +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 { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type UpdatePlanetRawRequest = { + /** + * The ID of the planet to get + */ + planetId: number; + /** + * New information about the planet + */ + planet?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined; +}; + +export type UpdatePlanetRawResponse = components.Planet | Uint8Array | string; + +/** @internal */ +export const UpdatePlanetRawRequest$inboundSchema: z.ZodType< + UpdatePlanetRawRequest, + z.ZodTypeDef, + unknown +> = z.object({ + planetId: z.number().int(), + Planet: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional(), +}).transform((v) => { + return remap$(v, { + "Planet": "planet", + }); +}); + +/** @internal */ +export type UpdatePlanetRawRequest$Outbound = { + planetId: number; + Planet?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined; +}; + +/** @internal */ +export const UpdatePlanetRawRequest$outboundSchema: z.ZodType< + UpdatePlanetRawRequest$Outbound, + z.ZodTypeDef, + UpdatePlanetRawRequest +> = z.object({ + planetId: z.number().int(), + planet: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]).optional(), +}).transform((v) => { + return remap$(v, { + planet: "Planet", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UpdatePlanetRawRequest$ { + /** @deprecated use `UpdatePlanetRawRequest$inboundSchema` instead. */ + export const inboundSchema = UpdatePlanetRawRequest$inboundSchema; + /** @deprecated use `UpdatePlanetRawRequest$outboundSchema` instead. */ + export const outboundSchema = UpdatePlanetRawRequest$outboundSchema; + /** @deprecated use `UpdatePlanetRawRequest$Outbound` instead. */ + export type Outbound = UpdatePlanetRawRequest$Outbound; +} + +export function updatePlanetRawRequestToJSON( + updatePlanetRawRequest: UpdatePlanetRawRequest, +): string { + return JSON.stringify( + UpdatePlanetRawRequest$outboundSchema.parse(updatePlanetRawRequest), + ); +} + +export function updatePlanetRawRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdatePlanetRawRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdatePlanetRawRequest' from JSON`, + ); +} + +/** @internal */ +export const UpdatePlanetRawResponse$inboundSchema: z.ZodType< + UpdatePlanetRawResponse, + z.ZodTypeDef, + unknown +> = z.union([components.Planet$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type UpdatePlanetRawResponse$Outbound = + | components.Planet$Outbound + | Uint8Array; + +/** @internal */ +export const UpdatePlanetRawResponse$outboundSchema: z.ZodType< + UpdatePlanetRawResponse$Outbound, + z.ZodTypeDef, + UpdatePlanetRawResponse +> = z.union([components.Planet$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UpdatePlanetRawResponse$ { + /** @deprecated use `UpdatePlanetRawResponse$inboundSchema` instead. */ + export const inboundSchema = UpdatePlanetRawResponse$inboundSchema; + /** @deprecated use `UpdatePlanetRawResponse$outboundSchema` instead. */ + export const outboundSchema = UpdatePlanetRawResponse$outboundSchema; + /** @deprecated use `UpdatePlanetRawResponse$Outbound` instead. */ + export type Outbound = UpdatePlanetRawResponse$Outbound; +} + +export function updatePlanetRawResponseToJSON( + updatePlanetRawResponse: UpdatePlanetRawResponse, +): string { + return JSON.stringify( + UpdatePlanetRawResponse$outboundSchema.parse(updatePlanetRawResponse), + ); +} + +export function updatePlanetRawResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UpdatePlanetRawResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UpdatePlanetRawResponse' from JSON`, + ); +} diff --git a/src/models/operations/uploadimage.ts b/src/models/operations/uploadimage.ts new file mode 100644 index 0000000..d50fe1e --- /dev/null +++ b/src/models/operations/uploadimage.ts @@ -0,0 +1,272 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; +import * as b64$ from "../../lib/base64.js"; +import { remap as remap$ } from "../../lib/primitives.js"; +import { safeParse } from "../../lib/schemas.js"; +import { blobLikeSchema } from "../../types/blobs.js"; +import { Result as SafeParseResult } from "../../types/fp.js"; +import * as components from "../components/index.js"; +import { SDKValidationError } from "../errors/sdkvalidationerror.js"; + +export type Image = { + fileName: string; + content: ReadableStream | Blob | ArrayBuffer | Uint8Array; +}; + +/** + * Image to upload + */ +export type UploadImageRequestBody = { + /** + * The image file to upload + */ + image?: Image | Blob | undefined; +}; + +export type UploadImageRequest = { + /** + * The ID of the planet to get + */ + planetId: number; + /** + * Image to upload + */ + requestBody?: UploadImageRequestBody | undefined; +}; + +export type UploadImageResponse = + | components.ImageUploadedMessage + | Uint8Array + | string; + +/** @internal */ +export const Image$inboundSchema: z.ZodType = z + .object({ + fileName: z.string(), + content: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]), + }); + +/** @internal */ +export type Image$Outbound = { + fileName: string; + content: ReadableStream | Blob | ArrayBuffer | Uint8Array; +}; + +/** @internal */ +export const Image$outboundSchema: z.ZodType< + Image$Outbound, + z.ZodTypeDef, + Image +> = z.object({ + fileName: z.string(), + content: z.union([ + z.instanceof(ReadableStream), + z.instanceof(Blob), + z.instanceof(ArrayBuffer), + z.instanceof(Uint8Array), + ]), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace Image$ { + /** @deprecated use `Image$inboundSchema` instead. */ + export const inboundSchema = Image$inboundSchema; + /** @deprecated use `Image$outboundSchema` instead. */ + export const outboundSchema = Image$outboundSchema; + /** @deprecated use `Image$Outbound` instead. */ + export type Outbound = Image$Outbound; +} + +export function imageToJSON(image: Image): string { + return JSON.stringify(Image$outboundSchema.parse(image)); +} + +export function imageFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => Image$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'Image' from JSON`, + ); +} + +/** @internal */ +export const UploadImageRequestBody$inboundSchema: z.ZodType< + UploadImageRequestBody, + z.ZodTypeDef, + unknown +> = z.object({ + image: z.lazy(() => Image$inboundSchema).optional(), +}); + +/** @internal */ +export type UploadImageRequestBody$Outbound = { + image?: Image$Outbound | Blob | undefined; +}; + +/** @internal */ +export const UploadImageRequestBody$outboundSchema: z.ZodType< + UploadImageRequestBody$Outbound, + z.ZodTypeDef, + UploadImageRequestBody +> = z.object({ + image: z.lazy(() => Image$outboundSchema).or(blobLikeSchema).optional(), +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UploadImageRequestBody$ { + /** @deprecated use `UploadImageRequestBody$inboundSchema` instead. */ + export const inboundSchema = UploadImageRequestBody$inboundSchema; + /** @deprecated use `UploadImageRequestBody$outboundSchema` instead. */ + export const outboundSchema = UploadImageRequestBody$outboundSchema; + /** @deprecated use `UploadImageRequestBody$Outbound` instead. */ + export type Outbound = UploadImageRequestBody$Outbound; +} + +export function uploadImageRequestBodyToJSON( + uploadImageRequestBody: UploadImageRequestBody, +): string { + return JSON.stringify( + UploadImageRequestBody$outboundSchema.parse(uploadImageRequestBody), + ); +} + +export function uploadImageRequestBodyFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UploadImageRequestBody$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UploadImageRequestBody' from JSON`, + ); +} + +/** @internal */ +export const UploadImageRequest$inboundSchema: z.ZodType< + UploadImageRequest, + z.ZodTypeDef, + unknown +> = z.object({ + planetId: z.number().int(), + RequestBody: z.lazy(() => UploadImageRequestBody$inboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + "RequestBody": "requestBody", + }); +}); + +/** @internal */ +export type UploadImageRequest$Outbound = { + planetId: number; + RequestBody?: UploadImageRequestBody$Outbound | undefined; +}; + +/** @internal */ +export const UploadImageRequest$outboundSchema: z.ZodType< + UploadImageRequest$Outbound, + z.ZodTypeDef, + UploadImageRequest +> = z.object({ + planetId: z.number().int(), + requestBody: z.lazy(() => UploadImageRequestBody$outboundSchema).optional(), +}).transform((v) => { + return remap$(v, { + requestBody: "RequestBody", + }); +}); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UploadImageRequest$ { + /** @deprecated use `UploadImageRequest$inboundSchema` instead. */ + export const inboundSchema = UploadImageRequest$inboundSchema; + /** @deprecated use `UploadImageRequest$outboundSchema` instead. */ + export const outboundSchema = UploadImageRequest$outboundSchema; + /** @deprecated use `UploadImageRequest$Outbound` instead. */ + export type Outbound = UploadImageRequest$Outbound; +} + +export function uploadImageRequestToJSON( + uploadImageRequest: UploadImageRequest, +): string { + return JSON.stringify( + UploadImageRequest$outboundSchema.parse(uploadImageRequest), + ); +} + +export function uploadImageRequestFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UploadImageRequest$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UploadImageRequest' from JSON`, + ); +} + +/** @internal */ +export const UploadImageResponse$inboundSchema: z.ZodType< + UploadImageResponse, + z.ZodTypeDef, + unknown +> = z.union([components.ImageUploadedMessage$inboundSchema, b64$.zodInbound]); + +/** @internal */ +export type UploadImageResponse$Outbound = + | components.ImageUploadedMessage$Outbound + | Uint8Array; + +/** @internal */ +export const UploadImageResponse$outboundSchema: z.ZodType< + UploadImageResponse$Outbound, + z.ZodTypeDef, + UploadImageResponse +> = z.union([components.ImageUploadedMessage$outboundSchema, b64$.zodOutbound]); + +/** + * @internal + * @deprecated This namespace will be removed in future versions. Use schemas and types that are exported directly from this module. + */ +export namespace UploadImageResponse$ { + /** @deprecated use `UploadImageResponse$inboundSchema` instead. */ + export const inboundSchema = UploadImageResponse$inboundSchema; + /** @deprecated use `UploadImageResponse$outboundSchema` instead. */ + export const outboundSchema = UploadImageResponse$outboundSchema; + /** @deprecated use `UploadImageResponse$Outbound` instead. */ + export type Outbound = UploadImageResponse$Outbound; +} + +export function uploadImageResponseToJSON( + uploadImageResponse: UploadImageResponse, +): string { + return JSON.stringify( + UploadImageResponse$outboundSchema.parse(uploadImageResponse), + ); +} + +export function uploadImageResponseFromJSON( + jsonString: string, +): SafeParseResult { + return safeParse( + jsonString, + (x) => UploadImageResponse$inboundSchema.parse(JSON.parse(x)), + `Failed to parse 'UploadImageResponse' from JSON`, + ); +} diff --git a/src/sdk/authentication.ts b/src/sdk/authentication.ts new file mode 100644 index 0000000..623b066 --- /dev/null +++ b/src/sdk/authentication.ts @@ -0,0 +1,139 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { + authenticationCreateUserJson, + CreateUserJsonAcceptEnum, +} from "../funcs/authenticationCreateUserJson.js"; +import { + authenticationCreateUserRaw, + CreateUserRawAcceptEnum, +} from "../funcs/authenticationCreateUserRaw.js"; +import { + authenticationGetMe, + GetMeAcceptEnum, +} from "../funcs/authenticationGetMe.js"; +import { + authenticationGetTokenJson, + GetTokenJsonAcceptEnum, +} from "../funcs/authenticationGetTokenJson.js"; +import { + authenticationGetTokenRaw, + GetTokenRawAcceptEnum, +} from "../funcs/authenticationGetTokenRaw.js"; +import { ClientSDK, RequestOptions } from "../lib/sdks.js"; +import * as components from "../models/components/index.js"; +import * as operations from "../models/operations/index.js"; +import { unwrapAsync } from "../types/fp.js"; + +export { CreateUserJsonAcceptEnum } from "../funcs/authenticationCreateUserJson.js"; + +export { CreateUserRawAcceptEnum } from "../funcs/authenticationCreateUserRaw.js"; + +export { GetTokenJsonAcceptEnum } from "../funcs/authenticationGetTokenJson.js"; + +export { GetTokenRawAcceptEnum } from "../funcs/authenticationGetTokenRaw.js"; + +export { GetMeAcceptEnum } from "../funcs/authenticationGetMe.js"; + +export class Authentication extends ClientSDK { + /** + * Create a user + * + * @remarks + * Time to create a user account, eh? + */ + async createUserJson( + request?: operations.CreateUserJsonRequestBody | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreateUserJsonAcceptEnum; + }, + ): Promise { + return unwrapAsync(authenticationCreateUserJson( + this, + request, + options, + )); + } + + /** + * Create a user + * + * @remarks + * Time to create a user account, eh? + */ + async createUserRaw( + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreateUserRawAcceptEnum; + }, + ): Promise { + return unwrapAsync(authenticationCreateUserRaw( + this, + request, + options, + )); + } + + /** + * Get a token + * + * @remarks + * Yeah, this is the boring security stuff. Just get your super secret token and move on. + */ + async getTokenJson( + request?: components.Credentials | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: GetTokenJsonAcceptEnum; + }, + ): Promise { + return unwrapAsync(authenticationGetTokenJson( + this, + request, + options, + )); + } + + /** + * Get a token + * + * @remarks + * Yeah, this is the boring security stuff. Just get your super secret token and move on. + */ + async getTokenRaw( + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { acceptHeaderOverride?: GetTokenRawAcceptEnum }, + ): Promise { + return unwrapAsync(authenticationGetTokenRaw( + this, + request, + options, + )); + } + + /** + * Get authenticated user + * + * @remarks + * Find yourself they say. Thatโ€™s what you can do here. + */ + async getMe( + options?: RequestOptions & { acceptHeaderOverride?: GetMeAcceptEnum }, + ): Promise { + return unwrapAsync(authenticationGetMe( + this, + options, + )); + } +} diff --git a/src/sdk/index.ts b/src/sdk/index.ts new file mode 100644 index 0000000..ecac226 --- /dev/null +++ b/src/sdk/index.ts @@ -0,0 +1,5 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export * from "./sdk.js"; diff --git a/src/sdk/planets.ts b/src/sdk/planets.ts new file mode 100644 index 0000000..cee426e --- /dev/null +++ b/src/sdk/planets.ts @@ -0,0 +1,202 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { + CreatePlanetJsonAcceptEnum, + planetsCreatePlanetJson, +} from "../funcs/planetsCreatePlanetJson.js"; +import { + CreatePlanetRawAcceptEnum, + planetsCreatePlanetRaw, +} from "../funcs/planetsCreatePlanetRaw.js"; +import { planetsDeletePlanet } from "../funcs/planetsDeletePlanet.js"; +import { + GetAllDataAcceptEnum, + planetsGetAllData, +} from "../funcs/planetsGetAllData.js"; +import { + GetPlanetAcceptEnum, + planetsGetPlanet, +} from "../funcs/planetsGetPlanet.js"; +import { + planetsUpdatePlanetJson, + UpdatePlanetJsonAcceptEnum, +} from "../funcs/planetsUpdatePlanetJson.js"; +import { + planetsUpdatePlanetRaw, + UpdatePlanetRawAcceptEnum, +} from "../funcs/planetsUpdatePlanetRaw.js"; +import { + planetsUploadImage, + UploadImageAcceptEnum, +} from "../funcs/planetsUploadImage.js"; +import { ClientSDK, RequestOptions } from "../lib/sdks.js"; +import * as components from "../models/components/index.js"; +import * as operations from "../models/operations/index.js"; +import { unwrapAsync } from "../types/fp.js"; + +export { GetAllDataAcceptEnum } from "../funcs/planetsGetAllData.js"; + +export { CreatePlanetJsonAcceptEnum } from "../funcs/planetsCreatePlanetJson.js"; + +export { CreatePlanetRawAcceptEnum } from "../funcs/planetsCreatePlanetRaw.js"; + +export { GetPlanetAcceptEnum } from "../funcs/planetsGetPlanet.js"; + +export { UpdatePlanetJsonAcceptEnum } from "../funcs/planetsUpdatePlanetJson.js"; + +export { UpdatePlanetRawAcceptEnum } from "../funcs/planetsUpdatePlanetRaw.js"; + +export { UploadImageAcceptEnum } from "../funcs/planetsUploadImage.js"; + +export class Planets extends ClientSDK { + /** + * Get all planets + * + * @remarks + * Itโ€™s easy to say you know them all, but do you really? Retrieve all the planets and check whether you missed one. + */ + async getAllData( + request: operations.GetAllDataRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetAllDataAcceptEnum }, + ): Promise { + return unwrapAsync(planetsGetAllData( + this, + request, + options, + )); + } + + /** + * Create a planet + * + * @remarks + * Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + */ + async createPlanetJson( + request?: components.PlanetInput | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetJsonAcceptEnum; + }, + ): Promise { + return unwrapAsync(planetsCreatePlanetJson( + this, + request, + options, + )); + } + + /** + * Create a planet + * + * @remarks + * Time to play god and create a new planet. What do you think? Ah, donโ€™t think too much. What could go wrong anyway? + */ + async createPlanetRaw( + request?: + | ReadableStream + | Blob + | ArrayBuffer + | Uint8Array + | undefined, + options?: RequestOptions & { + acceptHeaderOverride?: CreatePlanetRawAcceptEnum; + }, + ): Promise { + return unwrapAsync(planetsCreatePlanetRaw( + this, + request, + options, + )); + } + + /** + * Get a planet + * + * @remarks + * Youโ€™ll better learn a little bit more about the planets. It might come in handy once space travel is available for everyone. + */ + async getPlanet( + request: operations.GetPlanetRequest, + options?: RequestOptions & { acceptHeaderOverride?: GetPlanetAcceptEnum }, + ): Promise { + return unwrapAsync(planetsGetPlanet( + this, + request, + options, + )); + } + + /** + * Update a planet + * + * @remarks + * Sometimes you make mistakes, that's fine. No worries, you can update all planets. + */ + async updatePlanetJson( + request: operations.UpdatePlanetJsonRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetJsonAcceptEnum; + }, + ): Promise { + return unwrapAsync(planetsUpdatePlanetJson( + this, + request, + options, + )); + } + + /** + * Update a planet + * + * @remarks + * Sometimes you make mistakes, that's fine. No worries, you can update all planets. + */ + async updatePlanetRaw( + request: operations.UpdatePlanetRawRequest, + options?: RequestOptions & { + acceptHeaderOverride?: UpdatePlanetRawAcceptEnum; + }, + ): Promise { + return unwrapAsync(planetsUpdatePlanetRaw( + this, + request, + options, + )); + } + + /** + * Delete a planet + * + * @remarks + * This endpoint was used to delete planets. Unfortunately, that caused a lot of trouble for planets with life. So, this endpoint is now deprecated and should not be used anymore. + */ + async deletePlanet( + request: operations.DeletePlanetRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(planetsDeletePlanet( + this, + request, + options, + )); + } + + /** + * Upload an image to a planet + * + * @remarks + * Got a crazy good photo of a planet? Share it with the world! + */ + async uploadImage( + request: operations.UploadImageRequest, + options?: RequestOptions & { acceptHeaderOverride?: UploadImageAcceptEnum }, + ): Promise { + return unwrapAsync(planetsUploadImage( + this, + request, + options, + )); + } +} diff --git a/src/sdk/sdk.ts b/src/sdk/sdk.ts new file mode 100644 index 0000000..db4e56b --- /dev/null +++ b/src/sdk/sdk.ts @@ -0,0 +1,19 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { ClientSDK } from "../lib/sdks.js"; +import { Authentication } from "./authentication.js"; +import { Planets } from "./planets.js"; + +export class ScalarGalaxyTypescript extends ClientSDK { + private _planets?: Planets; + get planets(): Planets { + return (this._planets ??= new Planets(this._options)); + } + + private _authentication?: Authentication; + get authentication(): Authentication { + return (this._authentication ??= new Authentication(this._options)); + } +} diff --git a/src/types/async.ts b/src/types/async.ts new file mode 100644 index 0000000..689dba5 --- /dev/null +++ b/src/types/async.ts @@ -0,0 +1,68 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export type APICall = + | { + status: "complete"; + request: Request; + response: Response; + } + | { + status: "request-error"; + request: Request; + response?: undefined; + } + | { + status: "invalid"; + request?: undefined; + response?: undefined; + }; + +export class APIPromise implements Promise { + readonly #promise: Promise<[T, APICall]>; + readonly #unwrapped: Promise; + + readonly [Symbol.toStringTag] = "APIPromise"; + + constructor(p: [T, APICall] | Promise<[T, APICall]>) { + this.#promise = p instanceof Promise ? p : Promise.resolve(p); + this.#unwrapped = + p instanceof Promise + ? this.#promise.then(([value]) => value) + : Promise.resolve(p[0]); + } + + then( + onfulfilled?: + | ((value: T) => TResult1 | PromiseLike) + | null + | undefined, + onrejected?: + | ((reason: any) => TResult2 | PromiseLike) + | null + | undefined, + ): Promise { + return this.#promise.then( + onfulfilled ? ([value]) => onfulfilled(value) : void 0, + onrejected, + ); + } + + catch( + onrejected?: + | ((reason: any) => TResult | PromiseLike) + | null + | undefined, + ): Promise { + return this.#unwrapped.catch(onrejected); + } + + finally(onfinally?: (() => void) | null | undefined): Promise { + return this.#unwrapped.finally(onfinally); + } + + $inspect(): Promise<[T, APICall]> { + return this.#promise; + } +} diff --git a/src/types/blobs.ts b/src/types/blobs.ts new file mode 100644 index 0000000..4ce8460 --- /dev/null +++ b/src/types/blobs.ts @@ -0,0 +1,31 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod"; + +export const blobLikeSchema: z.ZodType = + z.custom(isBlobLike, { + message: "expected a Blob, File or Blob-like object", + fatal: true, + }); + +export function isBlobLike(val: unknown): val is Blob { + if (val instanceof Blob) { + return true; + } + + if (typeof val !== "object" || val == null || !(Symbol.toStringTag in val)) { + return false; + } + + const name = val[Symbol.toStringTag]; + if (typeof name !== "string") { + return false; + } + if (name !== "Blob" && name !== "File") { + return false; + } + + return "stream" in val && typeof val.stream === "function"; +} diff --git a/src/types/constdatetime.ts b/src/types/constdatetime.ts new file mode 100644 index 0000000..eeff4dd --- /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 equivalent to ${val}`); +} diff --git a/src/types/enums.ts b/src/types/enums.ts new file mode 100644 index 0000000..6fb6d91 --- /dev/null +++ b/src/types/enums.ts @@ -0,0 +1,16 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +declare const __brand: unique symbol; +export type Unrecognized = T & { [__brand]: "unrecognized" }; + +export function catchUnrecognizedEnum(value: T): Unrecognized { + return value as Unrecognized; +} + +type Prettify = { [K in keyof T]: T[K] } & {}; +export type ClosedEnum = T[keyof T]; +export type OpenEnum = + | Prettify + | Unrecognized; 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 new file mode 100644 index 0000000..74ee06c --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,12 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export { blobLikeSchema, isBlobLike } from "./blobs.js"; +export { catchUnrecognizedEnum } 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"; +export type { WebhookRecipient } from "./webhooks.js"; diff --git a/src/types/operations.ts b/src/types/operations.ts new file mode 100644 index 0000000..beb81e1 --- /dev/null +++ b/src/types/operations.ts @@ -0,0 +1,105 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { Result } from "./fp.js"; + +export type Paginator = () => Promise }> | null; + +export type PageIterator = V & { + next: Paginator; + [Symbol.asyncIterator]: () => AsyncIterableIterator; + "~next"?: PageState | undefined; +}; + +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 new file mode 100644 index 0000000..c79b3f5 --- /dev/null +++ b/src/types/rfcdate.ts @@ -0,0 +1,54 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +const dateRE = /^\d{4}-\d{2}-\d{2}$/; + +export class RFCDate { + private serialized: string; + + /** + * Creates a new RFCDate instance using today's date. + */ + static today(): RFCDate { + return new RFCDate(new Date()); + } + + /** + * Creates a new RFCDate instance using the provided input. + * If a string is used then in must be in the format YYYY-MM-DD. + * + * @param date A Date object or a date string in YYYY-MM-DD format + * @example + * new RFCDate("2022-01-01") + * @example + * new RFCDate(new Date()) + */ + constructor(date: Date | string) { + if (typeof date === "string" && !dateRE.test(date)) { + throw new RangeError( + "RFCDate: date strings must be in the format YYYY-MM-DD: " + date, + ); + } + + const value = new Date(date); + if (isNaN(+value)) { + throw new RangeError("RFCDate: invalid date provided: " + date); + } + + this.serialized = value.toISOString().slice(0, "YYYY-MM-DD".length); + if (!dateRE.test(this.serialized)) { + throw new TypeError( + `RFCDate: failed to build valid date with given value: ${date} serialized to ${this.serialized}`, + ); + } + } + + toJSON(): string { + return this.toString(); + } + + toString(): string { + return this.serialized; + } +} 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/src/types/webhooks.ts b/src/types/webhooks.ts new file mode 100644 index 0000000..9510d20 --- /dev/null +++ b/src/types/webhooks.ts @@ -0,0 +1,7 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +export type WebhookRecipient = { + url: string; +}; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..94d81a3 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,41 @@ +{ + "compilerOptions": { + "incremental": true, + "tsBuildInfoFile": ".tsbuildinfo", + "target": "ES2020", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "jsx": "react-jsx", + + "module": "Node16", + "moduleResolution": "Node16", + + "allowJs": true, + + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "outDir": ".", + + + // https://github.com/tsconfig/bases/blob/a1bf7c0fa2e094b068ca3e1448ca2ece4157977e/bases/strictest.json + "strict": true, + "allowUnusedLabels": false, + "allowUnreachableCode": false, + "exactOptionalPropertyTypes": true, + "useUnknownInCatchVariables": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noPropertyAccessFromIndexSignature": true, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "isolatedModules": true, + "checkJs": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src"], + "exclude": ["node_modules"] +}