kloudspot-analytics-sdk
v1.0.8
Published
Node/TypeScript SDK for Kloudspot APIs
Downloads
376
Maintainers
Readme
Kloudspot Analytics SDK
A typed, ergonomic Node (TypeScript) SDK for Kloudspot APIs generated from our OpenAPI (Swagger) spec.
It handles JWT auth, exposes per-service methods, and includes an optional custom HTTP requester for better debugging, timeouts, interceptors, and headers.
Requires Node ≥ 20 (LTS recommended).
The package ships a dual build viatsup(ESM+CommonJS) and type declarations.
Table of contents
- Quick start
- Install & requirements
- Project layout
- Generate the client (from OpenAPI)
- Build
- Example usage
- Authentication
- Custom requester (what/why/how)
- Debugging & troubleshooting
- Scripts reference
- Publishing
- CI (Bitbucket Pipelines)
- Contact / Support
- License
Quick start
# 1) Install the SDK in your app
npm i kloudspot-analytics-sdk
# 2) Minimal ESM example (example.mjs)
cat > example.mjs <<'EOF'
import { KloudspotSDK } from 'kloudspot-analytics-sdk';
const sdk = new KloudspotSDK({
baseUrl: 'https://walker.kloudspot.com/advanced',
apiKeyId: process.env.KLOUD_API_KEY,
apiSecret: process.env.KLOUD_API_SECRET,
});
const res = await sdk.api.alertResource.findAlertsByUser({
showUnreadOnly: true,
pageable: { page: 0, size: 10, sort: ['createdTime,DESC'] },
});
console.log(res);
EOF
# 3) Run it (set your credentials)
KLOUD_API_KEY="<your_api_key_id>" \
KLOUD_API_SECRET="<your_api_secret>" \
node example.mjsInstall & requirements
- Node: v20+ (LTS).
- Package format: ESM + CJS (dual).
- Type declarations: included (
.d.ts).
If you clone this SDK repo to work on it locally, run:
npm installProject layout
kloudspot-analytics-sdk/
├─ openapi/
│ └─ public-api.json # OpenAPI spec (source of truth)
├─ scripts/
│ ├─ request.ts # Custom HTTP requester (optional but recommended)
│ └─ make-services-index.mjs # Builds barrel file for services (auto-run after codegen)
├─ src/
│ ├─ gen/ # GENERATED client (do not edit)
│ │ ├─ core/ # OpenAPI config, request helpers
│ │ ├─ models/ # Schemas as TS types
│ │ └─ services/ # Per-tag service files (e.g., AlertResourceService.ts)
│ ├─ sdk.ts # SDK class (auth, headers, token, api aliases)
│ └─ index.ts # Barrel export for bundling
├─ examples/
│ └─ node.ts # Example using the SDK
├─ tsup.config.ts
├─ tsconfig.json
├─ package.json
└─ README.mdGenerate the client (from OpenAPI)
The SDK source is generated from openapi/public-api.json using openapi-typescript-codegen.
npm run generate:clientThis emits:
src/gen/models/*(types)src/gen/services/*(endpoint classes/methods)src/gen/core/*(OpenAPI config + requester)
We also auto-create
src/gen/services/index.tsviascripts/make-services-index.mjsso that all services can be imported and exposed assdk.api.*keys automatically.
Build
Builds ESM + CJS + .d.ts via tsup:
npm run buildOutputs:
dist/
├─ index.js # ESM
├─ index.cjs # CommonJS
└─ index.d.ts # TypesExample usage
ESM (Node ≥20)
import { KloudspotSDK } from 'kloudspot-analytics-sdk';
const sdk = new KloudspotSDK({
baseUrl: 'https://walker.kloudspot.com/advanced',
apiKeyId: process.env.KLOUD_API_KEY,
apiSecret: process.env.KLOUD_API_SECRET,
});
// Alerts
const alerts = await sdk.api.alertResource.findAlertsByUser({
showUnreadOnly: true,
pageable: { page: 0, size: 20, sort: ['createdTime,DESC'] },
});
// Camera analytics
const distribution = await sdk.api.cameraAnalyticsQueries.distributionQuery2({
requestBody: {
distributionTiming: 'DAILY', // thanks to --useUnionTypes
start: 1756191600000, // epoch millis
finish: 1756277999999, // epoch millis
locations: ['64ff81281457952a7d4bb7c0'],
attributes: ['male', 'female'],
},
});
console.log({ alerts, distribution });CommonJS
(async () => {
const { KloudspotSDK } = await import('kloudspot-analytics-sdk');
const sdk = new KloudspotSDK({
baseUrl: 'https://walker.kloudspot.com/advanced',
apiKeyId: process.env.KLOUD_API_KEY,
apiSecret: process.env.KLOUD_API_SECRET,
});
const alerts = await sdk.api.alertResource.findAlertsByUser({ showUnreadOnly: true });
console.log(alerts);
})();Browser / Angular (no secrets in the browser)
Do not ship API key/secret to the browser. Instead, provide a backend endpoint that returns a short-lived JWT and configure the SDK with tokenProvider:
import { KloudspotSDK } from 'kloudspot-analytics-sdk';
const sdk = new KloudspotSDK({
baseUrl: 'https://walker.kloudspot.com/advanced',
tokenProvider: async () => {
const r = await fetch('/sdk/token', { method: 'POST' }); // your backend
if (!r.ok) throw new Error('token fetch failed');
return r.json(); // { token, expEpochSec? }
},
});
// Use sdk.api.* as usualAuthentication
- APIs require
Authorization: Bearer <JWT>. - The SDK:
- Logs in using
{ id, secretKey }server-side OR usestokenProviderclient-side. - Stores the raw JWT (no
"Bearer "); the requester adds the prefix to avoid double-prefix bugs. - Exposes every generated service under
sdk.api.<serviceName>.
- Logs in using
Custom requester (what/why/how)
We pass --request ./scripts/request.ts to the generator so it uses our custom HTTP transport instead of the default. Benefits:
- Debug quickly:
DEBUG_SDK=1logs method, URL, headers (auth redacted by default), body, and response. - Authorization safety: Normalizes the token to avoid
Bearer Bearer <jwt>. - Timeouts & retries: Tunable constants with jitter and
Retry-Aftersupport. - Interceptors: Pre-request and post-response hooks (e.g., correlation IDs, observability).
- Headers in one place: Merges
OpenAPI.HEADERSand setsAccept: application/json. - Correct URLs: Uses
options.urlfrom the generator, avoiding/advancedundefinedbugs.
Enable the custom requester
package.json already includes the flag in the codegen script:
"generate:client": "openapi --input ./openapi/public-api.json --output ./src/gen --client fetch --useOptions --useUnionTypes --exportServices true --exportModels true --request ./scripts/request.ts && node scripts/make-services-index.mjs"Disable / remove the custom requester
If you prefer the generator’s default requester:
- Edit
package.jsonand remove the flag:- --request ./scripts/request.ts - && node scripts/make-services-index.mjs + && node scripts/make-services-index.mjs - Clean & regenerate:
rm -rf ./src/gen npm run generate:client - Important: Ensure
OpenAPI.TOKEN("Authorization")returns a raw JWT (no"Bearer "), because some templates add the prefix themselves.
Trade-offs when removing the custom requester:
- You lose built-in debug logs (
DEBUG_SDK). - You lose the timeout/retry knobs and interceptors.
Debugging & troubleshooting
Enable logs (with the custom requester):
DEBUG_SDK=1 npm run example:nodeYou’ll see lines like:
→ POST https://walker.kloudspot.com/advanced/api/v1/camera/analytics/distribution
→ headers: { authorization: "[REDACTED]", accept: "application/json", ... }
→ body: {"distributionTiming":"DAILY","start":...}
← 200 OK
← body: {"data":[...]}Common issues:
- “Bearer Bearer …” header — return raw JWT from
OpenAPI.TOKEN; requester addsBearer. - URL ends with
undefined— requester must useoptions.url(fixed in our requester). - Postman works, SDK fails — compare headers/body with debug logs; ensure required tenant/site headers via
OpenAPI.HEADERS. - Enum typing — we generate with
--useUnionTypesso"DAILY"etc. are valid string literals.
Scripts reference
From the SDK repo:
{
"scripts": {
"generate:client": "openapi --input ./openapi/public-api.json --output ./src/gen --client fetch --useOptions --useUnionTypes --exportServices true --exportModels true --request ./scripts/request.ts && node scripts/make-services-index.mjs",
"generate:client:clean": "rimraf ./src/gen && npm run generate:client",
"build": "tsup",
"prepublishOnly": "npm run generate:client:clean && npm run build",
"example:node": "npm run generate:client && tsx examples/node.ts"
}
}Publishing
npm run generate:client:clean
npm run build
npm version patch
npm publish --access publicCI (Bitbucket Pipelines)
bitbucket-pipelines.yml:
image: node:20
pipelines:
default:
- step:
name: Build SDK
caches: [node]
script:
- node -v
- npm ci
- npm run generate:client
- npm run buildContact / Support
Questions or feedback? Reach out:
- Name: Uday Pyda
- LinkedIn: https://www.linkedin.com/in/udaysasi/
License
Apache-2.0 © Kloudspot Inc.
