@kosli/sdk
v0.4.0
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *@kosli/sdk* API.
Readme
@kosli/sdk
Developer-friendly & type-safe Typescript SDK specifically catered to leverage @kosli/sdk API.
[!CAUTION] Do not use in production. This SDK is an early work in progress, is unsupported, and may break or be removed without notice. Provided for evaluation only.
Summary
Kosli API: The API for communicating with Kosli
Authentication
When making requests against Kosli API, you can authenticate your requests using a bearer token. Set the bearer token in the request Authorization header to a valid API key. API Keys can be personal or for service accounts. Check the service accounts documentation for details.
Curl example
curl -H "Authorization: Bearer <<your-api-key>>" https://app.kosli.com/api/v2/environments/<<your-org-name>>Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @kosli/sdkPNPM
pnpm add @kosli/sdkBun
bun add @kosli/sdkYarn
yarn add @kosli/sdk[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import("@kosli/sdk")to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli();
async function run() {
const result = await kosli.actions.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| ------------ | ---- | ----------- | -------------------- |
| httpBearer | http | HTTP Bearer | KOSLI_HTTP_BEARER |
To authenticate with the API the httpBearer parameter must be set when initializing the SDK client instance. For example:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
});
async function run() {
const result = await kosli.schemas.getEnvironmentPolicyV1();
console.log(result);
}
run();
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli();
async function run() {
const result = await kosli.actions.list({}, {
org: "<value>",
});
console.log(result);
}
run();
Available Resources and Operations
Actions
- list - List actions
- updateEnvironment - Create or update environment action
- createOrUpdateFlow - Create or update flow action
- get - Get action
- delete - Delete an action
Allowlists
- list - List allowlist
- allowArtifactForEnv - Allow artifact for environment
Approval
- get - Get approval
Approvals
- list - List approvals
- create - Create approval
- getArtifactCommit - Get commit of running artifact
Artifacts
- listInOrg - List artifacts
- create - Report artifact
- ~~list~~ - List artifacts in flow :warning: Deprecated
- getByCommitSHA - Get artifacts by commit SHA
- getByFingerprint - Get artifact by fingerprint
- listApprovals - List artifact approvals
- getAuditPackage - Get artifact audit package
- getLatestCommit - Get latest artifact commit
Asserts
- getArtifact - Assert artifact
Attestation
- listFlow - List flow attestations
Attestations
- list - List attestations
- listForCriteria - List attestations for criteria
- getArtifact - Get artifact attestation
- getEvidence - Get attestation evidence file
- attestCustom - Attest custom
- attestGeneric - Attest generic
- addJira - Attest Jira issue
- attestJUnit - Attest JUnit test results
- overrideAttestation - Override attestation
- attestPullRequest - Attest pull request
- addSnyk - Attest Snyk scan
- addSonar - Attest Sonar scan
- getTrail - Get trail attestation
Builds
- list - List Builds
CustomAttestationTypes
- list - List custom attestation types
- createOrUpdate - Create or update custom attestation type
- get - Get custom attestation type
- archive - Archive custom attestation type
Deployments
EnvDiff
- getDiff - Get environment diff
Environments
- createOrUpdate - Create or update environment
- list - List environments
- update - Update environment
- get - Get environment
- archive - Archive environment
- getAuditLog - Get environment audit log
- listEvents - List environment events
- joinPhysicalToLogical - Add environment to logical environment
- attachPolicy - Attach policy to environment
- detachPolicy - Detach policy from environment
- rename - Rename environment
- reportEcs - Report ECS environment
- reportK8S - Report K8S environment
- putS3Report - Report S3 environment
- reportAzureApps - Report Azure Web and Function Apps environment
- cloudRunReport - Report Cloud Run environment
- reportDocker - Report Docker environment
- reportLambda - Report Lambda environment
- reportServer - Report server environment
Flows
- list - List flows
- ~~createOrUpdate~~ - Create or update flow :warning: Deprecated
- createOrUpdateWithTemplate - Create or update flow with template
- get - Get flow
- archive - Archive flow
- rename - Rename flow
Organizations
- get - Get organization
- getEnvironmentNotifications - List environment notifications
- updateEnvironmentNotifications - Create or update environment notification
- getEnvironmentNotification - Get environment notification
- updateEnvironmentNotification - Update environment notification
- deleteEnvironmentNotification - Delete environment notification
- updateExperimentalFeatures - Update experimental features
Policies
Repos
- list - List repos
- getLiveArtifacts - Get live artifacts for a repo
Schemas
- getEnvironmentPolicyV1 - Environment policy schema v1
- getFlowTemplateV1 - Flow template schema v1
Search
- getBySha - Search artifacts by SHA or fingerprint
ServiceAccounts
- listApiKeys - List API keys for a service account
- createApiKey - Create an API key for a service account
- deleteApiKey - Revoke an API key for a service account
- rotateApiKey - Rotate an API key for a service account
Snapshots
Tags
- patch - Update tags
Trails
- listForOrg - List trails for organization
- create - Begin trail
- list - List trails
- get - Get trail
- downloadAuditPackage - Download trail audit package
- downloadAuditPdf - Download trail audit PDF
User
- setDefaultOrg - Set default organization
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
actionsCreateOrUpdateFlow- Create or update flow actionactionsDelete- Delete an actionactionsGet- Get actionactionsList- List actionsactionsUpdateEnvironment- Create or update environment actionallowlistsAllowArtifactForEnv- Allow artifact for environmentallowlistsList- List allowlistapprovalGet- Get approvalapprovalsCreate- Create approvalapprovalsGetArtifactCommit- Get commit of running artifactapprovalsList- List approvalsartifactsCreate- Report artifactartifactsGetAuditPackage- Get artifact audit packageartifactsGetByCommitSHA- Get artifacts by commit SHAartifactsGetByFingerprint- Get artifact by fingerprintartifactsGetLatestCommit- Get latest artifact commitartifactsListApprovals- List artifact approvalsartifactsListInOrg- List artifactsassertsGetArtifact- Assert artifactattestationListFlow- List flow attestationsattestationsAddJira- Attest Jira issueattestationsAddSnyk- Attest Snyk scanattestationsAddSonar- Attest Sonar scanattestationsAttestCustom- Attest customattestationsAttestGeneric- Attest genericattestationsAttestJUnit- Attest JUnit test resultsattestationsAttestPullRequest- Attest pull requestattestationsGetArtifact- Get artifact attestationattestationsGetEvidence- Get attestation evidence fileattestationsGetTrail- Get trail attestationattestationsList- List attestationsattestationsListForCriteria- List attestations for criteriaattestationsOverrideAttestation- Override attestationbuildsList- List BuildscustomAttestationTypesArchive- Archive custom attestation typecustomAttestationTypesCreateOrUpdate- Create or update custom attestation typecustomAttestationTypesGet- Get custom attestation typecustomAttestationTypesList- List custom attestation typesdeploymentsGet- Get DeploymentdeploymentsList- List DeploymentsenvDiffGetDiff- Get environment diffenvironmentsArchive- Archive environmentenvironmentsAttachPolicy- Attach policy to environmentenvironmentsCloudRunReport- Report Cloud Run environmentenvironmentsCreateOrUpdate- Create or update environmentenvironmentsDetachPolicy- Detach policy from environmentenvironmentsGet- Get environmentenvironmentsGetAuditLog- Get environment audit logenvironmentsJoinPhysicalToLogical- Add environment to logical environmentenvironmentsList- List environmentsenvironmentsListEvents- List environment eventsenvironmentsPutS3Report- Report S3 environmentenvironmentsRename- Rename environmentenvironmentsReportAzureApps- Report Azure Web and Function Apps environmentenvironmentsReportDocker- Report Docker environmentenvironmentsReportEcs- Report ECS environmentenvironmentsReportK8S- Report K8S environmentenvironmentsReportLambda- Report Lambda environmentenvironmentsReportServer- Report server environmentenvironmentsUpdate- Update environmentflowsArchive- Archive flowflowsCreateOrUpdateWithTemplate- Create or update flow with templateflowsGet- Get flowflowsList- List flowsflowsRename- Rename floworganizationsDeleteEnvironmentNotification- Delete environment notificationorganizationsGet- Get organizationorganizationsGetEnvironmentNotification- Get environment notificationorganizationsGetEnvironmentNotifications- List environment notificationsorganizationsUpdateEnvironmentNotification- Update environment notificationorganizationsUpdateEnvironmentNotifications- Create or update environment notificationorganizationsUpdateExperimentalFeatures- Update experimental featurespoliciesGet- Get policypoliciesList- List policiespoliciesPut- Create or update policyreposGetLiveArtifacts- Get live artifacts for a reporeposList- List reposschemasGetEnvironmentPolicyV1- Environment policy schema v1schemasGetFlowTemplateV1- Flow template schema v1searchGetBySha- Search artifacts by SHA or fingerprintserviceAccountsCreateApiKey- Create an API key for a service accountserviceAccountsDeleteApiKey- Revoke an API key for a service accountserviceAccountsListApiKeys- List API keys for a service accountserviceAccountsRotateApiKey- Rotate an API key for a service accountsnapshotsGet- Get snapshotsnapshotsList- List snapshotstagsPatch- Update tagstrailsCreate- Begin trailtrailsDownloadAuditPackage- Download trail audit packagetrailsDownloadAuditPdf- Download trail audit PDFtrailsGet- Get trailtrailsList- List trailstrailsListForOrg- List trails for organizationuserSetDefaultOrg- Set default organization- ~~
artifactsList~~ - List artifacts in flow :warning: Deprecated - ~~
flowsCreateOrUpdate~~ - Create or update flow :warning: Deprecated
Pagination
Some of the endpoints in this SDK support pagination. To use pagination, you
make your SDK calls as usual, but the returned response object will also be an
async iterable that can be consumed using the for await...of
syntax.
Here's an example of one such pagination call:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli();
async function run() {
const result = await kosli.approvals.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
flowName: "<value>",
org: "<value>",
});
for await (const page of result) {
console.log(page);
}
}
run();
File uploads
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.
[!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
openAsBlobfunction innode:fs.- Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads.- Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element.- Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli();
async function run() {
const result = await kosli.attestations.attestCustom({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
flowName: "<value>",
trailName: "<value>",
org: "<value>",
body: {
dataJson: {
attestationName: "custom",
gitCommitInfo: {
sha1: "ae08fc6a5c963ae8dfaa0c27d8e5de9980d433b6",
message: "adding glorious commit",
author: "Jon Smith <[email protected]>",
branch: "main",
timestamp: 1750923680,
url:
"https://github.com/org/repo/commit/ae08fc6a5c963ae8dfaa0c27d8e5de9980d433b6",
},
userData: {},
typeName: "custom_type",
attestationData: "{\"key\":\"value\"}",
},
},
});
console.log(result);
}
run();
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:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli();
async function run() {
const result = await kosli.actions.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
async function run() {
const result = await kosli.actions.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
});
console.log(result);
}
run();
Default retry policy: Unless overridden, this SDK retries on
5XX,429, and409(lock conflict) responses and on connection errors, using an increasing backoff (1s initial interval, 10s max interval, ~30s total time budget).
Error Handling
KosliError is the base class for all HTTP error responses. It has the following properties:
| 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 |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { Kosli } from "@kosli/sdk";
import * as errors from "@kosli/sdk/models/errors";
const kosli = new Kosli();
async function run() {
try {
const result = await kosli.actions.updateEnvironment({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
body: {
name: "production-action",
targets: [
{
"type": "EMAIL",
"emails": [
"[email protected]",
],
},
],
environments: [
"<value 1>",
],
triggers: [
"ON_STARTED_ARTIFACT",
],
},
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.KosliError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (
error
instanceof errors
.FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel14
) {
console.log(error.data$.message); // string
console.log(error.data$.errors); // { [k: string]: string }
}
}
}
}
run();
Error Classes
Primary error:
KosliError: The base class for HTTP error responses.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from KosliError:
FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel2: Validation Error. Status code400. Applicable to 2 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel14: Validation Error. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel15: Validation Error. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel12: Validation Error. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel1: Validation Error. Status code400. Applicable to 1 of 96 methods.*Response400ListAttestationsForCriteriaError: Missing required commit_list parameter. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsBadRequestResponseLocalsBadRequestResponseModel1: Can only add physical environments to logical environments. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel3: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel5: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel4: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel6: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel7: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel8: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel9: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel10: Invalid report data. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel13: Invalid notification payload. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel11: Validation Error. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel16: expires_at cannot be in the past. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsValidationErrorResponseLocalsValidationErrorResponseModel17: expires_at cannot be in the past. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsBadRequestResponseLocalsBadRequestResponseModel2: Invalid Resource Type. Status code400. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel4: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel1: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel2: User does not have permission to archive environment. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel3: User does not have permission to detach policy. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel5: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel6: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel8: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsForbiddenResponseLocalsForbiddenResponseModel7: Forbidden. Status code403. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel11: Organization not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel10: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel16: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel12: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel14: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel15: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel13: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel30: Artifact not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel2: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel3: This attestation has no evidence file attached. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel1: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel4: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel39: Deployment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel25: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel28: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel26: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel29: Environment or policy not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel27: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel17: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel19: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel18: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel20: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel21: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel22: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel23: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel24: Environment not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel5: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel6: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel7: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel32: Action not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel33: Action not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel34: Action not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel31: Policy not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel37: Organization not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel38: Repo not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel40: Search results are too ambiguous. For example: no matches for the provided value. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel41: Service account not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel42: Service account not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel44: API key not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel43: API key not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel36: Flow not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel35: Resource not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel8: Flow or trail not found. Status code404. Applicable to 1 of 96 methods.*FastapiAppErrorsNotFoundResponseLocalsNotFoundResponseModel9: Flow or trail not found. Status code404. Applicable to 1 of 96 methods.*RequestEntityTooLargeResponseModelError: Request Entity Too Large. Status code413. Applicable to 1 of 96 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Select Server by Index
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:
| # | Server | Description |
| --- | --------------------------------- | ----------- |
| 0 | https://app.kosli.com/api/v2 | EU |
| 1 | https://app.us.kosli.com/api/v2 | US |
Example
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli({
serverIdx: 0,
});
async function run() {
const result = await kosli.actions.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
});
console.log(result);
}
run();
Override Server URL Per-Client
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:
import { Kosli } from "@kosli/sdk";
const kosli = new Kosli({
serverURL: "https://app.us.kosli.com/api/v2",
});
async function run() {
const result = await kosli.actions.list({
httpBearer: process.env["KOSLI_HTTP_BEARER"] ?? "",
}, {
org: "<value>",
});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
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.
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.
The following example shows how to:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { Kosli } from "@kosli/sdk";
import { ProxyAgent } from "undici";
import { HTTPClient } from "@kosli/sdk/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Kosli({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Kosli } from "@kosli/sdk";
const sdk = new Kosli({ debugLogger: console });You can also enable a default debug logger by setting an environment variable KOSLI_DEBUG to true.
Development
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.
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.
