@lightdash-tools/client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +144 -0
- package/dist/api/base-client.d.ts +13 -0
- package/dist/api/base-client.js +17 -0
- package/dist/api/v1/ai-agents.d.ts +17 -0
- package/dist/api/v1/ai-agents.js +47 -0
- package/dist/api/v1/ai-agents.test.d.ts +1 -0
- package/dist/api/v1/ai-agents.test.js +77 -0
- package/dist/api/v1/charts.d.ts +18 -0
- package/dist/api/v1/charts.js +45 -0
- package/dist/api/v1/charts.test.d.ts +1 -0
- package/dist/api/v1/charts.test.js +106 -0
- package/dist/api/v1/dashboards.d.ts +9 -0
- package/dist/api/v1/dashboards.js +25 -0
- package/dist/api/v1/dashboards.test.d.ts +1 -0
- package/dist/api/v1/dashboards.test.js +33 -0
- package/dist/api/v1/explores.d.ts +11 -0
- package/dist/api/v1/explores.js +31 -0
- package/dist/api/v1/explores.test.d.ts +1 -0
- package/dist/api/v1/explores.test.js +46 -0
- package/dist/api/v1/groups.d.ts +42 -0
- package/dist/api/v1/groups.js +81 -0
- package/dist/api/v1/groups.test.d.ts +1 -0
- package/dist/api/v1/groups.test.js +107 -0
- package/dist/api/v1/organizations.d.ts +9 -0
- package/dist/api/v1/organizations.js +25 -0
- package/dist/api/v1/organizations.test.d.ts +1 -0
- package/dist/api/v1/organizations.test.js +33 -0
- package/dist/api/v1/project-access.d.ts +40 -0
- package/dist/api/v1/project-access.js +88 -0
- package/dist/api/v1/project-access.test.d.ts +1 -0
- package/dist/api/v1/project-access.test.js +109 -0
- package/dist/api/v1/projects.d.ts +13 -0
- package/dist/api/v1/projects.js +37 -0
- package/dist/api/v1/projects.test.d.ts +1 -0
- package/dist/api/v1/projects.test.js +49 -0
- package/dist/api/v1/query.d.ts +11 -0
- package/dist/api/v1/query.js +31 -0
- package/dist/api/v1/query.test.d.ts +1 -0
- package/dist/api/v1/query.test.js +51 -0
- package/dist/api/v1/spaces.d.ts +25 -0
- package/dist/api/v1/spaces.js +73 -0
- package/dist/api/v1/spaces.test.d.ts +1 -0
- package/dist/api/v1/spaces.test.js +91 -0
- package/dist/api/v1/users.d.ts +35 -0
- package/dist/api/v1/users.js +66 -0
- package/dist/api/v1/users.test.d.ts +1 -0
- package/dist/api/v1/users.test.js +122 -0
- package/dist/api/v2/organization-roles.d.ts +45 -0
- package/dist/api/v2/organization-roles.js +81 -0
- package/dist/api/v2/organization-roles.test.d.ts +1 -0
- package/dist/api/v2/organization-roles.test.js +112 -0
- package/dist/api/v2/project-role-assignments.d.ts +23 -0
- package/dist/api/v2/project-role-assignments.js +55 -0
- package/dist/api/v2/project-role-assignments.test.d.ts +1 -0
- package/dist/api/v2/project-role-assignments.test.js +66 -0
- package/dist/api/v2/query.d.ts +17 -0
- package/dist/api/v2/query.js +49 -0
- package/dist/api/v2/query.test.d.ts +1 -0
- package/dist/api/v2/query.test.js +78 -0
- package/dist/client.d.ts +118 -0
- package/dist/client.js +113 -0
- package/dist/client.test.d.ts +1 -0
- package/dist/client.test.js +94 -0
- package/dist/config.d.ts +83 -0
- package/dist/config.js +22 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +46 -0
- package/dist/errors.test.d.ts +1 -0
- package/dist/errors.test.js +29 -0
- package/dist/http/axios-client.d.ts +22 -0
- package/dist/http/axios-client.js +51 -0
- package/dist/http/http-client.d.ts +33 -0
- package/dist/http/http-client.js +69 -0
- package/dist/http/interceptors.d.ts +13 -0
- package/dist/http/interceptors.js +82 -0
- package/dist/http/rate-limiter.d.ts +23 -0
- package/dist/http/rate-limiter.js +60 -0
- package/dist/http/rate-limiter.test.d.ts +1 -0
- package/dist/http/rate-limiter.test.js +40 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +41 -0
- package/dist/index.test.d.ts +1 -0
- package/dist/index.test.js +65 -0
- package/dist/pagination/fetch-all-pages.d.ts +15 -0
- package/dist/pagination/fetch-all-pages.js +41 -0
- package/dist/pagination/fetch-all-pages.test.d.ts +1 -0
- package/dist/pagination/fetch-all-pages.test.js +70 -0
- package/dist/pagination/types.d.ts +14 -0
- package/dist/pagination/types.js +6 -0
- package/dist/types/api.d.ts +22 -0
- package/dist/types/api.js +8 -0
- package/dist/utils/env.d.ts +20 -0
- package/dist/utils/env.js +59 -0
- package/dist/utils/env.test.d.ts +1 -0
- package/dist/utils/env.test.js +73 -0
- package/dist/utils/logger.d.ts +8 -0
- package/dist/utils/logger.js +20 -0
- package/dist/utils/retry.d.ts +14 -0
- package/dist/utils/retry.js +67 -0
- package/dist/utils/retry.test.d.ts +1 -0
- package/dist/utils/retry.test.js +53 -0
- package/package.json +21 -0
- package/src/api/base-client.ts +14 -0
- package/src/api/v1/ai-agents.test.ts +74 -0
- package/src/api/v1/ai-agents.ts +41 -0
- package/src/api/v1/charts.test.ts +103 -0
- package/src/api/v1/charts.ts +51 -0
- package/src/api/v1/dashboards.test.ts +26 -0
- package/src/api/v1/dashboards.ts +15 -0
- package/src/api/v1/explores.test.ts +40 -0
- package/src/api/v1/explores.ts +18 -0
- package/src/api/v1/groups.test.ts +108 -0
- package/src/api/v1/groups.ts +100 -0
- package/src/api/v1/organizations.test.ts +26 -0
- package/src/api/v1/organizations.ts +13 -0
- package/src/api/v1/project-access.test.ts +110 -0
- package/src/api/v1/project-access.ts +102 -0
- package/src/api/v1/projects.test.ts +44 -0
- package/src/api/v1/projects.ts +23 -0
- package/src/api/v1/query.test.ts +46 -0
- package/src/api/v1/query.ts +37 -0
- package/src/api/v1/spaces.test.ts +92 -0
- package/src/api/v1/spaces.ts +83 -0
- package/src/api/v1/users.test.ts +125 -0
- package/src/api/v1/users.ts +76 -0
- package/src/api/v2/organization-roles.test.ts +115 -0
- package/src/api/v2/organization-roles.ts +90 -0
- package/src/api/v2/project-role-assignments.test.ts +75 -0
- package/src/api/v2/project-role-assignments.ts +63 -0
- package/src/api/v2/query.test.ts +81 -0
- package/src/api/v2/query.ts +69 -0
- package/src/client.test.ts +105 -0
- package/src/client.ts +182 -0
- package/src/config.ts +113 -0
- package/src/errors.test.ts +45 -0
- package/src/errors.ts +67 -0
- package/src/http/axios-client.ts +59 -0
- package/src/http/http-client.ts +79 -0
- package/src/http/interceptors.ts +110 -0
- package/src/http/rate-limiter.test.ts +34 -0
- package/src/http/rate-limiter.ts +54 -0
- package/src/index.test.ts +91 -0
- package/src/index.ts +41 -0
- package/src/pagination/fetch-all-pages.test.ts +75 -0
- package/src/pagination/fetch-all-pages.ts +39 -0
- package/src/pagination/types.ts +16 -0
- package/src/types/api.ts +28 -0
- package/src/utils/env.test.ts +88 -0
- package/src/utils/env.ts +69 -0
- package/src/utils/logger.ts +21 -0
- package/src/utils/retry.test.ts +49 -0
- package/src/utils/retry.ts +60 -0
- package/tsconfig.json +13 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Main Lightdash API client. Configuration can be explicit or loaded from environment variables.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { PartialLightdashClientConfig } from './config';
|
|
6
|
+
import { mergeConfig } from './utils/env';
|
|
7
|
+
import { createAxiosInstanceV1, createAxiosInstanceV2 } from './http/axios-client';
|
|
8
|
+
import { RateLimiter } from './http/rate-limiter';
|
|
9
|
+
import { HttpClient } from './http/http-client';
|
|
10
|
+
import { ProjectsClient } from './api/v1/projects';
|
|
11
|
+
import { OrganizationsClient } from './api/v1/organizations';
|
|
12
|
+
import { ChartsClient } from './api/v1/charts';
|
|
13
|
+
import { DashboardsClient } from './api/v1/dashboards';
|
|
14
|
+
import { SpacesClient } from './api/v1/spaces';
|
|
15
|
+
import { QueryClient } from './api/v1/query';
|
|
16
|
+
import { QueryClientV2 } from './api/v2/query';
|
|
17
|
+
import { OrganizationRolesClient } from './api/v2/organization-roles';
|
|
18
|
+
import { ProjectRoleAssignmentsClient } from './api/v2/project-role-assignments';
|
|
19
|
+
import { UsersClient } from './api/v1/users';
|
|
20
|
+
import { GroupsClient } from './api/v1/groups';
|
|
21
|
+
import { AiAgentsClient } from './api/v1/ai-agents';
|
|
22
|
+
import { ProjectAccessClient } from './api/v1/project-access';
|
|
23
|
+
import { ExploresClient } from './api/v1/explores';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* V1 API clients namespace. Contains all v1 API clients.
|
|
27
|
+
*/
|
|
28
|
+
export class V1ApiClients {
|
|
29
|
+
readonly projects: ProjectsClient;
|
|
30
|
+
readonly organizations: OrganizationsClient;
|
|
31
|
+
readonly charts: ChartsClient;
|
|
32
|
+
readonly dashboards: DashboardsClient;
|
|
33
|
+
readonly spaces: SpacesClient;
|
|
34
|
+
readonly query: QueryClient;
|
|
35
|
+
readonly users: UsersClient;
|
|
36
|
+
readonly groups: GroupsClient;
|
|
37
|
+
readonly aiAgents: AiAgentsClient;
|
|
38
|
+
readonly projectAccess: ProjectAccessClient;
|
|
39
|
+
readonly explores: ExploresClient;
|
|
40
|
+
|
|
41
|
+
constructor(http: HttpClient) {
|
|
42
|
+
this.projects = new ProjectsClient(http);
|
|
43
|
+
this.organizations = new OrganizationsClient(http);
|
|
44
|
+
this.charts = new ChartsClient(http);
|
|
45
|
+
this.dashboards = new DashboardsClient(http);
|
|
46
|
+
this.spaces = new SpacesClient(http);
|
|
47
|
+
this.query = new QueryClient(http);
|
|
48
|
+
this.users = new UsersClient(http);
|
|
49
|
+
this.groups = new GroupsClient(http);
|
|
50
|
+
this.aiAgents = new AiAgentsClient(http);
|
|
51
|
+
this.projectAccess = new ProjectAccessClient(http);
|
|
52
|
+
this.explores = new ExploresClient(http);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* V2 API clients namespace. Contains v2-specific API clients.
|
|
58
|
+
*/
|
|
59
|
+
export class V2ApiClients {
|
|
60
|
+
readonly query: QueryClientV2;
|
|
61
|
+
readonly organizationRoles: OrganizationRolesClient;
|
|
62
|
+
readonly projectRoleAssignments: ProjectRoleAssignmentsClient;
|
|
63
|
+
|
|
64
|
+
constructor(http: HttpClient) {
|
|
65
|
+
this.query = new QueryClientV2(http);
|
|
66
|
+
this.organizationRoles = new OrganizationRolesClient(http);
|
|
67
|
+
this.projectRoleAssignments = new ProjectRoleAssignmentsClient(http);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Lightdash HTTP client. Use environment variables (LIGHTDASH_URL, LIGHTDASH_API_KEY)
|
|
73
|
+
* or pass a config object. Explicit config takes priority over env vars.
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```typescript
|
|
77
|
+
* const client = new LightdashClient({ baseUrl: 'https://app.lightdash.cloud', personalAccessToken: 'token' });
|
|
78
|
+
* // Use v1 namespace
|
|
79
|
+
* const project = await client.v1.projects.getProject('project-uuid');
|
|
80
|
+
* // Use v2 namespace (when available)
|
|
81
|
+
* // const result = await client.v2.query.runMetricQuery(projectUuid, body);
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export class LightdashClient {
|
|
85
|
+
private readonly httpV1: HttpClient;
|
|
86
|
+
private readonly httpV2: HttpClient;
|
|
87
|
+
|
|
88
|
+
readonly v1: V1ApiClients;
|
|
89
|
+
readonly v2: V2ApiClients;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @deprecated Use `client.v1.projects` instead. This alias will be removed in a future major version.
|
|
93
|
+
*/
|
|
94
|
+
readonly projects: ProjectsClient;
|
|
95
|
+
/**
|
|
96
|
+
* @deprecated Use `client.v1.organizations` instead. This alias will be removed in a future major version.
|
|
97
|
+
*/
|
|
98
|
+
readonly organizations: OrganizationsClient;
|
|
99
|
+
/**
|
|
100
|
+
* @deprecated Use `client.v1.charts` instead. This alias will be removed in a future major version.
|
|
101
|
+
*/
|
|
102
|
+
readonly charts: ChartsClient;
|
|
103
|
+
/**
|
|
104
|
+
* @deprecated Use `client.v1.dashboards` instead. This alias will be removed in a future major version.
|
|
105
|
+
*/
|
|
106
|
+
readonly dashboards: DashboardsClient;
|
|
107
|
+
/**
|
|
108
|
+
* @deprecated Use `client.v1.spaces` instead. This alias will be removed in a future major version.
|
|
109
|
+
*/
|
|
110
|
+
readonly spaces: SpacesClient;
|
|
111
|
+
/**
|
|
112
|
+
* @deprecated Use `client.v1.query` instead. This alias will be removed in a future major version.
|
|
113
|
+
*/
|
|
114
|
+
readonly query: QueryClient;
|
|
115
|
+
/**
|
|
116
|
+
* @deprecated Use `client.v1.users` instead. This alias will be removed in a future major version.
|
|
117
|
+
*/
|
|
118
|
+
readonly users: UsersClient;
|
|
119
|
+
/**
|
|
120
|
+
* @deprecated Use `client.v1.groups` instead. This alias will be removed in a future major version.
|
|
121
|
+
*/
|
|
122
|
+
readonly groups: GroupsClient;
|
|
123
|
+
/**
|
|
124
|
+
* @deprecated Use `client.v1.aiAgents` instead. This alias will be removed in a future major version.
|
|
125
|
+
*/
|
|
126
|
+
readonly aiAgents: AiAgentsClient;
|
|
127
|
+
/**
|
|
128
|
+
* @deprecated Use `client.v1.explores` instead. This alias will be removed in a future major version.
|
|
129
|
+
*/
|
|
130
|
+
readonly explores: ExploresClient;
|
|
131
|
+
|
|
132
|
+
constructor(config?: PartialLightdashClientConfig) {
|
|
133
|
+
const merged = mergeConfig(config);
|
|
134
|
+
const rateLimiter = new RateLimiter(merged.rateLimit);
|
|
135
|
+
|
|
136
|
+
// Create v1 HTTP client
|
|
137
|
+
const axiosInstanceV1 = createAxiosInstanceV1(merged);
|
|
138
|
+
this.httpV1 = new HttpClient(axiosInstanceV1, rateLimiter, merged);
|
|
139
|
+
|
|
140
|
+
// Create v2 HTTP client
|
|
141
|
+
const axiosInstanceV2 = createAxiosInstanceV2(merged);
|
|
142
|
+
this.httpV2 = new HttpClient(axiosInstanceV2, rateLimiter, merged);
|
|
143
|
+
|
|
144
|
+
// Create versioned namespaces
|
|
145
|
+
this.v1 = new V1ApiClients(this.httpV1);
|
|
146
|
+
this.v2 = new V2ApiClients(this.httpV2);
|
|
147
|
+
|
|
148
|
+
// Backward compatibility: deprecated aliases delegate to v1
|
|
149
|
+
this.projects = this.v1.projects;
|
|
150
|
+
this.organizations = this.v1.organizations;
|
|
151
|
+
this.charts = this.v1.charts;
|
|
152
|
+
this.dashboards = this.v1.dashboards;
|
|
153
|
+
this.spaces = this.v1.spaces;
|
|
154
|
+
this.query = this.v1.query;
|
|
155
|
+
this.users = this.v1.users;
|
|
156
|
+
this.groups = this.v1.groups;
|
|
157
|
+
this.aiAgents = this.v1.aiAgents;
|
|
158
|
+
this.explores = this.v1.explores;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Low-level HTTP client for custom v1 requests. Prefer domain methods (e.g. v1.projects, v1.charts) when available.
|
|
163
|
+
* @deprecated Use `getHttpClientV1()` instead. This method will be removed in a future major version.
|
|
164
|
+
*/
|
|
165
|
+
getHttpClient(): HttpClient {
|
|
166
|
+
return this.httpV1;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Low-level HTTP client for custom v1 requests. Prefer domain methods (e.g. v1.projects, v1.charts) when available.
|
|
171
|
+
*/
|
|
172
|
+
getHttpClientV1(): HttpClient {
|
|
173
|
+
return this.httpV1;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Low-level HTTP client for custom v2 requests. Prefer domain methods (e.g. v2.query) when available.
|
|
178
|
+
*/
|
|
179
|
+
getHttpClientV2(): HttpClient {
|
|
180
|
+
return this.httpV2;
|
|
181
|
+
}
|
|
182
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration types for the Lightdash HTTP client.
|
|
3
|
+
* Supports explicit config and environment variables (LIGHTDASH_API_KEY, LIGHTDASH_URL, LIGHTDASH_PROXY_AUTHORIZATION).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Rate limit configuration for Bottleneck (token bucket algorithm).
|
|
8
|
+
*/
|
|
9
|
+
export interface RateLimitConfig {
|
|
10
|
+
/** Minimum time between requests in milliseconds (e.g. 100 = 10 req/sec max). */
|
|
11
|
+
minTime?: number;
|
|
12
|
+
/** Maximum concurrent requests. */
|
|
13
|
+
maxConcurrent?: number;
|
|
14
|
+
/** Token bucket size (burst capacity). */
|
|
15
|
+
reservoir?: number;
|
|
16
|
+
/** Token refresh interval in milliseconds. */
|
|
17
|
+
reservoirRefreshInterval?: number;
|
|
18
|
+
/** Number of tokens added per refresh. */
|
|
19
|
+
reservoirRefreshAmount?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Retry configuration for transient failures.
|
|
24
|
+
*/
|
|
25
|
+
export interface RetryConfig {
|
|
26
|
+
/** Maximum number of retries for 5xx and network errors. */
|
|
27
|
+
maxRetries?: number;
|
|
28
|
+
/** Base delay in ms for exponential backoff. */
|
|
29
|
+
retryDelay?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Logger interface for optional request/response logging.
|
|
34
|
+
*/
|
|
35
|
+
export interface Logger {
|
|
36
|
+
debug?(message: string, ...args: unknown[]): void;
|
|
37
|
+
info?(message: string, ...args: unknown[]): void;
|
|
38
|
+
warn?(message: string, ...args: unknown[]): void;
|
|
39
|
+
error?(message: string, ...args: unknown[]): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Optional hooks for metrics/telemetry. Called after each request completes.
|
|
44
|
+
*/
|
|
45
|
+
export interface ObservabilityHooks {
|
|
46
|
+
/** Called when a request completes (success or error). */
|
|
47
|
+
onRequestComplete?(info: {
|
|
48
|
+
method: string;
|
|
49
|
+
url: string;
|
|
50
|
+
statusCode?: number;
|
|
51
|
+
durationMs: number;
|
|
52
|
+
error?: Error;
|
|
53
|
+
}): void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Full configuration for the Lightdash HTTP client.
|
|
58
|
+
* All fields except rateLimit, timeout, retry, and logger can be provided via environment variables.
|
|
59
|
+
*/
|
|
60
|
+
export interface LightdashClientConfig {
|
|
61
|
+
/** Lightdash server base URL (e.g. https://app.lightdash.cloud). */
|
|
62
|
+
baseUrl: string;
|
|
63
|
+
/** Personal access token for API authentication (without ldpat_ prefix). */
|
|
64
|
+
personalAccessToken: string;
|
|
65
|
+
/** Optional proxy authorization header value for proxied access. */
|
|
66
|
+
proxyAuthorization?: string;
|
|
67
|
+
/** Override default rate limits. */
|
|
68
|
+
rateLimit?: RateLimitConfig;
|
|
69
|
+
/** Request timeout in milliseconds. Default 30000. */
|
|
70
|
+
timeout?: number;
|
|
71
|
+
/** Retry behavior for transient failures. */
|
|
72
|
+
retry?: RetryConfig;
|
|
73
|
+
/** Optional logger for request/response logging. */
|
|
74
|
+
logger?: Logger;
|
|
75
|
+
/** Optional hooks for metrics/telemetry. */
|
|
76
|
+
observability?: ObservabilityHooks;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Partial config for merging with environment variables.
|
|
81
|
+
* Used when constructing the client with optional explicit overrides.
|
|
82
|
+
*/
|
|
83
|
+
export type PartialLightdashClientConfig = Partial<
|
|
84
|
+
Pick<
|
|
85
|
+
LightdashClientConfig,
|
|
86
|
+
| 'baseUrl'
|
|
87
|
+
| 'personalAccessToken'
|
|
88
|
+
| 'proxyAuthorization'
|
|
89
|
+
| 'rateLimit'
|
|
90
|
+
| 'timeout'
|
|
91
|
+
| 'retry'
|
|
92
|
+
| 'logger'
|
|
93
|
+
| 'observability'
|
|
94
|
+
>
|
|
95
|
+
>;
|
|
96
|
+
|
|
97
|
+
/** Default rate limit: 10 req/sec, 5 concurrent, token bucket. */
|
|
98
|
+
export const DEFAULT_RATE_LIMIT: Required<RateLimitConfig> = {
|
|
99
|
+
minTime: 100,
|
|
100
|
+
maxConcurrent: 5,
|
|
101
|
+
reservoir: 100,
|
|
102
|
+
reservoirRefreshInterval: 1000,
|
|
103
|
+
reservoirRefreshAmount: 10,
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** Default request timeout in ms. */
|
|
107
|
+
export const DEFAULT_TIMEOUT = 30_000;
|
|
108
|
+
|
|
109
|
+
/** Default retry config. */
|
|
110
|
+
export const DEFAULT_RETRY: Required<RetryConfig> = {
|
|
111
|
+
maxRetries: 3,
|
|
112
|
+
retryDelay: 1000,
|
|
113
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { LightdashApiError, RateLimitError, NetworkError } from './errors';
|
|
3
|
+
|
|
4
|
+
describe('LightdashApiError', () => {
|
|
5
|
+
it('should set name and message', () => {
|
|
6
|
+
const err = new LightdashApiError(
|
|
7
|
+
400,
|
|
8
|
+
{ name: 'BadRequest', statusCode: 400, message: 'Invalid input' },
|
|
9
|
+
{ method: 'POST', url: '/api' },
|
|
10
|
+
);
|
|
11
|
+
expect(err.name).toBe('LightdashApiError');
|
|
12
|
+
expect(err.message).toBe('Invalid input');
|
|
13
|
+
expect(err.statusCode).toBe(400);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('should use default message when error.message is missing', () => {
|
|
17
|
+
const err = new LightdashApiError(
|
|
18
|
+
500,
|
|
19
|
+
{ name: 'InternalError', statusCode: 500 },
|
|
20
|
+
{ method: 'GET', url: '/' },
|
|
21
|
+
);
|
|
22
|
+
expect(err.message).toContain('500');
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('RateLimitError', () => {
|
|
27
|
+
it('should store retryAfter', () => {
|
|
28
|
+
const err = new RateLimitError(
|
|
29
|
+
429,
|
|
30
|
+
{ name: 'TooManyRequests', statusCode: 429 },
|
|
31
|
+
{ url: '/' },
|
|
32
|
+
undefined,
|
|
33
|
+
120,
|
|
34
|
+
);
|
|
35
|
+
expect(err.retryAfter).toBe(120);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('NetworkError', () => {
|
|
40
|
+
it('should preserve originalError', () => {
|
|
41
|
+
const original = new Error('fetch failed');
|
|
42
|
+
const err = new NetworkError('Network error', original);
|
|
43
|
+
expect(err.originalError).toBe(original);
|
|
44
|
+
});
|
|
45
|
+
});
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error types for the Lightdash HTTP client.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
6
|
+
|
|
7
|
+
/** API error payload shape (from Lightdash ApiErrorPayload). */
|
|
8
|
+
export interface ApiErrorPayload {
|
|
9
|
+
error: {
|
|
10
|
+
name: string;
|
|
11
|
+
statusCode: number;
|
|
12
|
+
message?: string;
|
|
13
|
+
data?: unknown;
|
|
14
|
+
};
|
|
15
|
+
status: 'error';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Base error for Lightdash API failures.
|
|
20
|
+
*/
|
|
21
|
+
export class LightdashApiError extends Error {
|
|
22
|
+
constructor(
|
|
23
|
+
public readonly statusCode: number,
|
|
24
|
+
public readonly error: ApiErrorPayload['error'],
|
|
25
|
+
public readonly request: AxiosRequestConfig,
|
|
26
|
+
public readonly response?: AxiosResponse<ApiErrorPayload>,
|
|
27
|
+
) {
|
|
28
|
+
super(error.message ?? `Lightdash API error: ${statusCode}`);
|
|
29
|
+
this.name = 'LightdashApiError';
|
|
30
|
+
Object.setPrototypeOf(this, LightdashApiError.prototype);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Error when the API returns 429 Too Many Requests.
|
|
36
|
+
*/
|
|
37
|
+
export class RateLimitError extends LightdashApiError {
|
|
38
|
+
/** Seconds to wait before retrying (from Retry-After header if present). */
|
|
39
|
+
public readonly retryAfter?: number;
|
|
40
|
+
|
|
41
|
+
constructor(
|
|
42
|
+
statusCode: number,
|
|
43
|
+
error: ApiErrorPayload['error'],
|
|
44
|
+
request: AxiosRequestConfig,
|
|
45
|
+
response?: AxiosResponse<ApiErrorPayload>,
|
|
46
|
+
retryAfter?: number,
|
|
47
|
+
) {
|
|
48
|
+
super(statusCode, error, request, response);
|
|
49
|
+
this.name = 'RateLimitError';
|
|
50
|
+
this.retryAfter = retryAfter;
|
|
51
|
+
Object.setPrototypeOf(this, RateLimitError.prototype);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Wrapper for network/connection errors.
|
|
57
|
+
*/
|
|
58
|
+
export class NetworkError extends Error {
|
|
59
|
+
constructor(
|
|
60
|
+
message: string,
|
|
61
|
+
public readonly originalError: Error,
|
|
62
|
+
) {
|
|
63
|
+
super(message);
|
|
64
|
+
this.name = 'NetworkError';
|
|
65
|
+
Object.setPrototypeOf(this, NetworkError.prototype);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Axios instance setup with base URL, timeout, and interceptors.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import axios, { type AxiosInstance } from 'axios';
|
|
6
|
+
import type { LightdashClientConfig } from '../config';
|
|
7
|
+
import { DEFAULT_TIMEOUT } from '../config';
|
|
8
|
+
import { attachRequestInterceptors, attachResponseInterceptors } from './interceptors';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* API version type.
|
|
12
|
+
*/
|
|
13
|
+
export type ApiVersion = 'v1' | 'v2';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Creates a configured Axios instance for the Lightdash API with a specific version.
|
|
17
|
+
*/
|
|
18
|
+
function createAxiosInstanceForVersion(
|
|
19
|
+
config: LightdashClientConfig,
|
|
20
|
+
version: ApiVersion,
|
|
21
|
+
): AxiosInstance {
|
|
22
|
+
const baseURL = config.baseUrl.replace(/\/$/, '') + `/api/${version}`;
|
|
23
|
+
const timeout = config.timeout ?? DEFAULT_TIMEOUT;
|
|
24
|
+
|
|
25
|
+
const instance = axios.create({
|
|
26
|
+
baseURL,
|
|
27
|
+
timeout,
|
|
28
|
+
headers: {
|
|
29
|
+
'Content-Type': 'application/json',
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
attachRequestInterceptors(instance, config);
|
|
34
|
+
attachResponseInterceptors(instance, config);
|
|
35
|
+
|
|
36
|
+
return instance;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Creates a configured Axios instance for the Lightdash API v1.
|
|
41
|
+
*/
|
|
42
|
+
export function createAxiosInstanceV1(config: LightdashClientConfig): AxiosInstance {
|
|
43
|
+
return createAxiosInstanceForVersion(config, 'v1');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Creates a configured Axios instance for the Lightdash API v2.
|
|
48
|
+
*/
|
|
49
|
+
export function createAxiosInstanceV2(config: LightdashClientConfig): AxiosInstance {
|
|
50
|
+
return createAxiosInstanceForVersion(config, 'v2');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Creates a configured Axios instance for the Lightdash API v1.
|
|
55
|
+
* @deprecated Use `createAxiosInstanceV1` instead. This function is kept for backward compatibility.
|
|
56
|
+
*/
|
|
57
|
+
export function createAxiosInstance(config: LightdashClientConfig): AxiosInstance {
|
|
58
|
+
return createAxiosInstanceV1(config);
|
|
59
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP client wrapper: rate limiter + axios + retry.
|
|
3
|
+
* All requests go through the rate limiter; retry applies to 5xx and network errors.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from 'axios';
|
|
7
|
+
import type { LightdashClientConfig } from '../config';
|
|
8
|
+
import { type ApiErrorPayload, LightdashApiError } from '../errors';
|
|
9
|
+
import { type RateLimiter } from './rate-limiter';
|
|
10
|
+
import { withRetry } from '../utils/retry';
|
|
11
|
+
|
|
12
|
+
/** Lightdash API success response shape. */
|
|
13
|
+
export interface ApiSuccessBody<T = unknown> {
|
|
14
|
+
status: 'ok';
|
|
15
|
+
results: T;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Lightdash API error response shape (body). */
|
|
19
|
+
export interface ApiErrorBody {
|
|
20
|
+
status: 'error';
|
|
21
|
+
error: ApiErrorPayload['error'];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function assertSuccess<T>(data: ApiSuccessBody<T> | ApiErrorBody): data is ApiSuccessBody<T> {
|
|
25
|
+
return data.status === 'ok';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* HTTP client that wraps Axios with rate limiting and retry.
|
|
30
|
+
*/
|
|
31
|
+
export class HttpClient {
|
|
32
|
+
constructor(
|
|
33
|
+
private readonly axiosInstance: AxiosInstance,
|
|
34
|
+
private readonly rateLimiter: RateLimiter,
|
|
35
|
+
private readonly config: LightdashClientConfig,
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
private async request<T>(method: Method, url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
39
|
+
const doRequest = () =>
|
|
40
|
+
this.axiosInstance.request<ApiSuccessBody<T> | ApiErrorBody>({
|
|
41
|
+
...config,
|
|
42
|
+
method,
|
|
43
|
+
url,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const response = await this.rateLimiter.schedule(() => withRetry(doRequest, this.config.retry));
|
|
47
|
+
|
|
48
|
+
const data = response.data;
|
|
49
|
+
if (!assertSuccess(data)) {
|
|
50
|
+
throw new LightdashApiError(
|
|
51
|
+
data.error.statusCode,
|
|
52
|
+
data.error,
|
|
53
|
+
response.config,
|
|
54
|
+
response as AxiosResponse<ApiErrorPayload>,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
return data.results;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
61
|
+
return this.request<T>('GET', url, config);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async post<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
|
|
65
|
+
return this.request<T>('POST', url, { ...config, data: body });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async put<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
|
|
69
|
+
return this.request<T>('PUT', url, { ...config, data: body });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async patch<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
|
|
73
|
+
return this.request<T>('PATCH', url, { ...config, data: body });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
77
|
+
return this.request<T>('DELETE', url, config);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request and response interceptors for auth, proxy, and error handling.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
|
|
6
|
+
import type { LightdashClientConfig } from '../config';
|
|
7
|
+
import type { ApiErrorPayload } from '../errors';
|
|
8
|
+
import { LightdashApiError, RateLimitError, NetworkError } from '../errors';
|
|
9
|
+
|
|
10
|
+
function getRetryAfterSeconds(value: string | undefined): number | undefined {
|
|
11
|
+
if (value === undefined) return undefined;
|
|
12
|
+
const n = parseInt(value, 10);
|
|
13
|
+
return Number.isNaN(n) ? undefined : n;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Attaches request interceptors: Authorization, Proxy-Authorization, optional request ID and logging.
|
|
18
|
+
*/
|
|
19
|
+
export function attachRequestInterceptors(
|
|
20
|
+
axiosInstance: AxiosInstance,
|
|
21
|
+
config: LightdashClientConfig,
|
|
22
|
+
): void {
|
|
23
|
+
axiosInstance.interceptors.request.use(
|
|
24
|
+
(req: InternalAxiosRequestConfig) => {
|
|
25
|
+
const token = config.personalAccessToken.startsWith('ldpat_')
|
|
26
|
+
? config.personalAccessToken
|
|
27
|
+
: `ldpat_${config.personalAccessToken}`;
|
|
28
|
+
req.headers.Authorization = `ApiKey ${token}`;
|
|
29
|
+
|
|
30
|
+
if (config.proxyAuthorization) {
|
|
31
|
+
req.headers['Proxy-Authorization'] = config.proxyAuthorization;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
(req as InternalAxiosRequestConfig & { _lightdashStartTime?: number })._lightdashStartTime =
|
|
35
|
+
Date.now();
|
|
36
|
+
|
|
37
|
+
if (config.logger?.debug) {
|
|
38
|
+
config.logger.debug('Lightdash request: %s %s', req.method, req.url);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return req;
|
|
42
|
+
},
|
|
43
|
+
(err) => Promise.reject(err),
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Attaches response interceptors: parse API responses, transform errors to LightdashApiError / RateLimitError.
|
|
49
|
+
*/
|
|
50
|
+
export function attachResponseInterceptors(
|
|
51
|
+
axiosInstance: AxiosInstance,
|
|
52
|
+
config?: Pick<LightdashClientConfig, 'logger' | 'observability'>,
|
|
53
|
+
): void {
|
|
54
|
+
const logger = config?.logger;
|
|
55
|
+
axiosInstance.interceptors.response.use(
|
|
56
|
+
(response) => {
|
|
57
|
+
if (logger?.debug) {
|
|
58
|
+
logger.debug(
|
|
59
|
+
'Lightdash response: %s %s %s',
|
|
60
|
+
response.config.method,
|
|
61
|
+
response.config.url,
|
|
62
|
+
response.status,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const start = (response.config as { _lightdashStartTime?: number })._lightdashStartTime;
|
|
66
|
+
config?.observability?.onRequestComplete?.({
|
|
67
|
+
method: response.config.method ?? 'GET',
|
|
68
|
+
url: response.config.url ?? '',
|
|
69
|
+
statusCode: response.status,
|
|
70
|
+
durationMs: start !== undefined ? Date.now() - start : 0,
|
|
71
|
+
});
|
|
72
|
+
return response;
|
|
73
|
+
},
|
|
74
|
+
(error) => {
|
|
75
|
+
const reqConfig = error.config as
|
|
76
|
+
| (InternalAxiosRequestConfig & { _lightdashStartTime?: number })
|
|
77
|
+
| undefined;
|
|
78
|
+
const start = reqConfig?._lightdashStartTime;
|
|
79
|
+
config?.observability?.onRequestComplete?.({
|
|
80
|
+
method: reqConfig?.method ?? 'GET',
|
|
81
|
+
url: reqConfig?.url ?? '',
|
|
82
|
+
statusCode: error.response?.status,
|
|
83
|
+
durationMs: start !== undefined ? Date.now() - start : 0,
|
|
84
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
85
|
+
});
|
|
86
|
+
if (error.response) {
|
|
87
|
+
const status = error.response.status as number;
|
|
88
|
+
const data = error.response.data as ApiErrorPayload | undefined;
|
|
89
|
+
const retryAfter = getRetryAfterSeconds(error.response.headers?.['retry-after']);
|
|
90
|
+
|
|
91
|
+
const payload = data?.error ?? {
|
|
92
|
+
name: 'UnknownError',
|
|
93
|
+
statusCode: status,
|
|
94
|
+
message: error.message,
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
if (status === 429) {
|
|
98
|
+
return Promise.reject(
|
|
99
|
+
new RateLimitError(status, payload, error.config, error.response, retryAfter),
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return Promise.reject(new LightdashApiError(status, payload, error.config, error.response));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const msg = error.message || (error.code ? `Network error: ${error.code}` : 'Network error');
|
|
107
|
+
return Promise.reject(new NetworkError(msg, error));
|
|
108
|
+
},
|
|
109
|
+
);
|
|
110
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { RateLimiter } from './rate-limiter';
|
|
3
|
+
|
|
4
|
+
describe('RateLimiter', () => {
|
|
5
|
+
it('should schedule and run a single task', async () => {
|
|
6
|
+
const limiter = new RateLimiter({ minTime: 0, maxConcurrent: 1 });
|
|
7
|
+
const result = await limiter.schedule(async () => 42);
|
|
8
|
+
expect(result).toBe(42);
|
|
9
|
+
await limiter.disconnect();
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('should run tasks sequentially when maxConcurrent is 1', async () => {
|
|
13
|
+
const limiter = new RateLimiter({ minTime: 10, maxConcurrent: 1 });
|
|
14
|
+
const order: number[] = [];
|
|
15
|
+
const promises = [1, 2, 3].map((n) =>
|
|
16
|
+
limiter.schedule(async () => {
|
|
17
|
+
order.push(n);
|
|
18
|
+
return n;
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
const results = await Promise.all(promises);
|
|
22
|
+
expect(results).toEqual([1, 2, 3]);
|
|
23
|
+
expect(order).toEqual([1, 2, 3]);
|
|
24
|
+
await limiter.disconnect();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('should wrap a function', async () => {
|
|
28
|
+
const limiter = new RateLimiter({ minTime: 0 });
|
|
29
|
+
const wrapped = limiter.wrap(async (a: number, b: number) => a + b);
|
|
30
|
+
const result = await wrapped(1, 2);
|
|
31
|
+
expect(result).toBe(3);
|
|
32
|
+
await limiter.disconnect();
|
|
33
|
+
});
|
|
34
|
+
});
|