@lightdash-tools/client 0.7.0 → 0.9.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/dist/api/v1/ai-agents/discovery.d.ts +7 -2
- package/dist/api/v1/ai-agents/discovery.js +3 -6
- package/dist/api/v1/ai-agents/discovery.test.js +17 -1
- package/dist/api/v1/ai-agents/facade.d.ts +5 -0
- package/dist/api/v1/ai-agents/facade.js +5 -2
- package/dist/api/v1/charts.d.ts +28 -1
- package/dist/api/v1/charts.js +51 -1
- package/dist/api/v1/charts.test.js +59 -6
- package/dist/api/v1/dashboards.d.ts +32 -1
- package/dist/api/v1/dashboards.js +20 -0
- package/dist/api/v1/dashboards.test.js +72 -0
- package/dist/api/v1/validation.d.ts +5 -1
- package/dist/api/v1/validation.js +8 -0
- package/dist/api/v1/validation.test.js +16 -0
- package/dist/api/v2/charts.d.ts +12 -0
- package/dist/api/v2/charts.js +18 -0
- package/dist/api/v2/charts.test.d.ts +4 -0
- package/dist/api/v2/charts.test.js +45 -0
- package/dist/api/v2/content.d.ts +19 -2
- package/dist/api/v2/content.js +15 -0
- package/dist/api/v2/content.test.js +41 -0
- package/dist/api/v2/dashboards.d.ts +7 -1
- package/dist/api/v2/dashboards.js +9 -1
- package/dist/api/v2/dashboards.test.js +34 -0
- package/dist/api/v2/parameters.d.ts +20 -0
- package/dist/api/v2/parameters.js +22 -0
- package/dist/api/v2/parameters.test.d.ts +4 -0
- package/dist/api/v2/parameters.test.js +39 -0
- package/dist/api/v2/query.d.ts +16 -1
- package/dist/api/v2/query.js +16 -0
- package/dist/api/v2/query.test.js +16 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +4 -0
- package/dist/client.test.js +2 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +37 -1
- package/dist/http/http-client.binary-url.test.d.ts +4 -0
- package/dist/http/http-client.binary-url.test.js +61 -0
- package/dist/http/http-client.d.ts +23 -11
- package/dist/http/http-client.envelope.test.d.ts +4 -0
- package/dist/http/http-client.envelope.test.js +59 -0
- package/dist/http/http-client.js +155 -6
- package/dist/http/unwrap-api-success.d.ts +26 -0
- package/dist/http/unwrap-api-success.js +25 -0
- package/dist/http/unwrap-api-success.test.d.ts +1 -0
- package/dist/http/unwrap-api-success.test.js +19 -0
- package/dist/index.d.ts +9 -2
- package/dist/index.js +17 -3
- package/package.json +2 -2
- package/src/api/v1/ai-agents/discovery.test.ts +19 -1
- package/src/api/v1/ai-agents/discovery.ts +17 -3
- package/src/api/v1/ai-agents/facade.ts +17 -1
- package/src/api/v1/charts.test.ts +61 -1
- package/src/api/v1/charts.ts +68 -0
- package/src/api/v1/dashboards.test.ts +85 -0
- package/src/api/v1/dashboards.ts +86 -0
- package/src/api/v1/validation.test.ts +18 -0
- package/src/api/v1/validation.ts +21 -1
- package/src/api/v2/charts.test.ts +53 -0
- package/src/api/v2/charts.ts +23 -0
- package/src/api/v2/content.test.ts +45 -0
- package/src/api/v2/content.ts +35 -2
- package/src/api/v2/dashboards.test.ts +39 -0
- package/src/api/v2/dashboards.ts +23 -1
- package/src/api/v2/parameters.test.ts +45 -0
- package/src/api/v2/parameters.ts +38 -0
- package/src/api/v2/query.test.ts +18 -0
- package/src/api/v2/query.ts +53 -0
- package/src/client.test.ts +2 -0
- package/src/client.ts +6 -0
- package/src/errors.ts +46 -0
- package/src/http/http-client.binary-url.test.ts +88 -0
- package/src/http/http-client.envelope.test.ts +74 -0
- package/src/http/http-client.ts +194 -16
- package/src/http/unwrap-api-success.test.ts +23 -0
- package/src/http/unwrap-api-success.ts +40 -0
- package/src/index.ts +40 -2
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project parameters API client (v2). Read-only.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { BaseApiClient } from '../base-client';
|
|
6
|
+
|
|
7
|
+
import type { components } from '@lightdash-tools/common';
|
|
8
|
+
|
|
9
|
+
export type ProjectParametersListResults =
|
|
10
|
+
components['schemas']['ApiGetProjectParametersListResults'];
|
|
11
|
+
export type ProjectParameterDefinitions = components['schemas']['ApiGetProjectParametersResults'];
|
|
12
|
+
|
|
13
|
+
export type ListProjectParametersParams = {
|
|
14
|
+
search?: string;
|
|
15
|
+
sortBy?: 'name';
|
|
16
|
+
sortOrder?: 'asc' | 'desc';
|
|
17
|
+
page?: number;
|
|
18
|
+
pageSize?: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export class ParametersClientV2 extends BaseApiClient {
|
|
22
|
+
/** List project parameter definitions (paginated). */
|
|
23
|
+
async listParameters(
|
|
24
|
+
projectUuid: string,
|
|
25
|
+
params?: ListProjectParametersParams,
|
|
26
|
+
): Promise<ProjectParametersListResults> {
|
|
27
|
+
return this.http.get<ProjectParametersListResults>(`/projects/${projectUuid}/parameters/list`, {
|
|
28
|
+
params,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Get project parameter definitions by name. */
|
|
33
|
+
async getParameters(projectUuid: string, names?: string[]): Promise<ProjectParameterDefinitions> {
|
|
34
|
+
return this.http.get<ProjectParameterDefinitions>(`/projects/${projectUuid}/parameters`, {
|
|
35
|
+
params: names !== undefined ? { names } : undefined,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/api/v2/query.test.ts
CHANGED
|
@@ -80,4 +80,22 @@ describe('QueryClientV2', () => {
|
|
|
80
80
|
expect(mockHttp.post).toHaveBeenCalledWith('/projects/p1/query/underlying-data', body);
|
|
81
81
|
expect(result).toEqual(results);
|
|
82
82
|
});
|
|
83
|
+
|
|
84
|
+
it('getAsyncQueryResults should call GET /projects/{projectUuid}/query/{queryUuid}', async () => {
|
|
85
|
+
const client = new QueryClientV2(mockHttp);
|
|
86
|
+
const results = { queryUuid: 'q1', status: 'ready', rows: [] };
|
|
87
|
+
vi.mocked(mockHttp.get).mockResolvedValue(results);
|
|
88
|
+
const result = await client.getAsyncQueryResults('p1', 'q1', { page: 1, pageSize: 100 });
|
|
89
|
+
expect(mockHttp.get).toHaveBeenCalledWith('/projects/p1/query/q1', {
|
|
90
|
+
params: { page: 1, pageSize: 100 },
|
|
91
|
+
});
|
|
92
|
+
expect(result).toEqual(results);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('cancelAsyncQuery should call POST /projects/{projectUuid}/query/{queryUuid}/cancel', async () => {
|
|
96
|
+
const client = new QueryClientV2(mockHttp);
|
|
97
|
+
vi.mocked(mockHttp.post).mockResolvedValue(undefined);
|
|
98
|
+
await client.cancelAsyncQuery('p1', 'q1');
|
|
99
|
+
expect(mockHttp.post).toHaveBeenCalledWith('/projects/p1/query/q1/cancel');
|
|
100
|
+
});
|
|
83
101
|
});
|
package/src/api/v2/query.ts
CHANGED
|
@@ -13,8 +13,20 @@ import type {
|
|
|
13
13
|
ExecuteAsyncMetricQueryResults,
|
|
14
14
|
ExecuteAsyncDashboardChartResults,
|
|
15
15
|
ExecuteAsyncSqlQueryResults,
|
|
16
|
+
components,
|
|
16
17
|
} from '@lightdash-tools/common';
|
|
17
18
|
|
|
19
|
+
export type AsyncQueryResults = components['schemas']['ApiGetAsyncQueryResults'];
|
|
20
|
+
export type ExecuteAsyncSqlChartRequestParams =
|
|
21
|
+
components['schemas']['ExecuteAsyncSqlChartRequestParams'];
|
|
22
|
+
export type ExecuteAsyncDashboardSqlChartRequestParams =
|
|
23
|
+
components['schemas']['ExecuteAsyncDashboardSqlChartRequestParams'];
|
|
24
|
+
|
|
25
|
+
export type GetAsyncQueryResultsParams = {
|
|
26
|
+
page?: number;
|
|
27
|
+
pageSize?: number;
|
|
28
|
+
};
|
|
29
|
+
|
|
18
30
|
export class QueryClientV2 extends BaseApiClient {
|
|
19
31
|
/** Run a metric query (v2 endpoint). */
|
|
20
32
|
async runMetricQuery(
|
|
@@ -67,4 +79,45 @@ export class QueryClientV2 extends BaseApiClient {
|
|
|
67
79
|
body,
|
|
68
80
|
);
|
|
69
81
|
}
|
|
82
|
+
|
|
83
|
+
/** Run a saved SQL chart query (v2). Present for completeness; MCP content-reader keeps SQL off by default. */
|
|
84
|
+
async runSqlChartQuery(
|
|
85
|
+
projectUuid: string,
|
|
86
|
+
body: ExecuteAsyncSqlChartRequestParams,
|
|
87
|
+
): Promise<ExecuteAsyncSqlQueryResults> {
|
|
88
|
+
return this.http.post<ExecuteAsyncSqlQueryResults>(
|
|
89
|
+
`/projects/${projectUuid}/query/sql-chart`,
|
|
90
|
+
body,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Run a dashboard SQL chart query (v2). Present for completeness; MCP content-reader keeps SQL off by default. */
|
|
95
|
+
async runDashboardSqlChartQuery(
|
|
96
|
+
projectUuid: string,
|
|
97
|
+
body: ExecuteAsyncDashboardSqlChartRequestParams,
|
|
98
|
+
): Promise<ExecuteAsyncSqlQueryResults> {
|
|
99
|
+
return this.http.post<ExecuteAsyncSqlQueryResults>(
|
|
100
|
+
`/projects/${projectUuid}/query/dashboard-sql-chart`,
|
|
101
|
+
body,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Poll paginated async query results. */
|
|
106
|
+
async getAsyncQueryResults(
|
|
107
|
+
projectUuid: string,
|
|
108
|
+
queryUuid: string,
|
|
109
|
+
params?: GetAsyncQueryResultsParams,
|
|
110
|
+
): Promise<AsyncQueryResults> {
|
|
111
|
+
return this.http.get<AsyncQueryResults>(
|
|
112
|
+
`/projects/${projectUuid}/query/${encodeURIComponent(queryUuid)}`,
|
|
113
|
+
{ params },
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Cancel a running async query. */
|
|
118
|
+
async cancelAsyncQuery(projectUuid: string, queryUuid: string): Promise<void> {
|
|
119
|
+
await this.http.post<unknown>(
|
|
120
|
+
`/projects/${projectUuid}/query/${encodeURIComponent(queryUuid)}/cancel`,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
70
123
|
}
|
package/src/client.test.ts
CHANGED
|
@@ -42,6 +42,8 @@ describe('LightdashClient', () => {
|
|
|
42
42
|
const client = new LightdashClient(config);
|
|
43
43
|
expect(client.v2).toBeDefined();
|
|
44
44
|
expect(client.v2.query).toBeDefined();
|
|
45
|
+
expect(client.v2.charts).toBeDefined();
|
|
46
|
+
expect(client.v2.parameters).toBeDefined();
|
|
45
47
|
});
|
|
46
48
|
|
|
47
49
|
it('v2.query.runMetricQuery should be a function', () => {
|
package/src/client.ts
CHANGED
|
@@ -18,9 +18,11 @@ import { SpacesClient } from './api/v1/spaces';
|
|
|
18
18
|
import { TagsClient } from './api/v1/tags';
|
|
19
19
|
import { UsersClient } from './api/v1/users';
|
|
20
20
|
import { ValidationClient } from './api/v1/validation';
|
|
21
|
+
import { ChartsClientV2 } from './api/v2/charts';
|
|
21
22
|
import { ContentClient } from './api/v2/content';
|
|
22
23
|
import { DashboardsClientV2 } from './api/v2/dashboards';
|
|
23
24
|
import { OrganizationRolesClient } from './api/v2/organization-roles';
|
|
25
|
+
import { ParametersClientV2 } from './api/v2/parameters';
|
|
24
26
|
import { ProjectRoleAssignmentsClient } from './api/v2/project-role-assignments';
|
|
25
27
|
import { QueryClientV2 } from './api/v2/query';
|
|
26
28
|
import { ValidationClientV2 } from './api/v2/validation';
|
|
@@ -82,6 +84,8 @@ export class V2ApiClients {
|
|
|
82
84
|
readonly content: ContentClient;
|
|
83
85
|
readonly validation: ValidationClientV2;
|
|
84
86
|
readonly dashboards: DashboardsClientV2;
|
|
87
|
+
readonly charts: ChartsClientV2;
|
|
88
|
+
readonly parameters: ParametersClientV2;
|
|
85
89
|
|
|
86
90
|
constructor(http: HttpClient) {
|
|
87
91
|
this.query = new QueryClientV2(http);
|
|
@@ -90,6 +94,8 @@ export class V2ApiClients {
|
|
|
90
94
|
this.content = new ContentClient(http);
|
|
91
95
|
this.validation = new ValidationClientV2(http);
|
|
92
96
|
this.dashboards = new DashboardsClientV2(http);
|
|
97
|
+
this.charts = new ChartsClientV2(http);
|
|
98
|
+
this.parameters = new ParametersClientV2(http);
|
|
93
99
|
}
|
|
94
100
|
}
|
|
95
101
|
|
package/src/errors.ts
CHANGED
|
@@ -4,6 +4,12 @@
|
|
|
4
4
|
|
|
5
5
|
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
6
6
|
|
|
7
|
+
/** HttpClient name when the response body is not a Lightdash success/error envelope. */
|
|
8
|
+
export const CONTRACT_ERROR_NAME = 'ContractError';
|
|
9
|
+
|
|
10
|
+
/** Human-readable message for {@link CONTRACT_ERROR_NAME}. */
|
|
11
|
+
export const CONTRACT_ERROR_MESSAGE = 'Unexpected Lightdash API response shape';
|
|
12
|
+
|
|
7
13
|
/** API error payload shape (from Lightdash ApiErrorPayload). */
|
|
8
14
|
export interface ApiErrorPayload {
|
|
9
15
|
error: {
|
|
@@ -65,3 +71,43 @@ export class NetworkError extends Error {
|
|
|
65
71
|
Object.setPrototypeOf(this, NetworkError.prototype);
|
|
66
72
|
}
|
|
67
73
|
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Thrown when a binary download exceeds the configured byte limit.
|
|
77
|
+
*/
|
|
78
|
+
export class BinarySizeLimitError extends Error {
|
|
79
|
+
readonly code = 'PAYLOAD_TOO_LARGE' as const;
|
|
80
|
+
|
|
81
|
+
constructor(
|
|
82
|
+
public readonly maxBytes: number,
|
|
83
|
+
public readonly byteLength?: number,
|
|
84
|
+
) {
|
|
85
|
+
super(
|
|
86
|
+
byteLength === undefined
|
|
87
|
+
? `Binary payload exceeds size limit (≥ ${maxBytes} bytes)`
|
|
88
|
+
: `Binary payload exceeds size limit (${byteLength} > ${maxBytes} bytes)`,
|
|
89
|
+
);
|
|
90
|
+
this.name = 'BinarySizeLimitError';
|
|
91
|
+
Object.setPrototypeOf(this, BinarySizeLimitError.prototype);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Thrown when a chart PNG export exceeds the configured byte limit.
|
|
97
|
+
*/
|
|
98
|
+
export class ChartImageSizeError extends Error {
|
|
99
|
+
readonly code = 'IMAGE_TOO_LARGE' as const;
|
|
100
|
+
|
|
101
|
+
constructor(
|
|
102
|
+
public readonly maxBytes: number,
|
|
103
|
+
public readonly byteLength?: number,
|
|
104
|
+
) {
|
|
105
|
+
super(
|
|
106
|
+
byteLength === undefined
|
|
107
|
+
? `Chart image exceeds size limit (≥ ${maxBytes} bytes)`
|
|
108
|
+
: `Chart image exceeds size limit (${byteLength} > ${maxBytes} bytes)`,
|
|
109
|
+
);
|
|
110
|
+
this.name = 'ChartImageSizeError';
|
|
111
|
+
Object.setPrototypeOf(this, ChartImageSizeError.prototype);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for binary download URL guards and getBytes error mapping.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { AxiosError } from 'axios';
|
|
6
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { assertSafeBinaryFetchUrl, HttpClient, isBlockedBinaryHostname } from './http-client.js';
|
|
9
|
+
|
|
10
|
+
import type { ResolvedLightdashClientConfig } from '../config.js';
|
|
11
|
+
import type { RateLimiter } from './rate-limiter.js';
|
|
12
|
+
import type { AxiosInstance } from 'axios';
|
|
13
|
+
|
|
14
|
+
describe('isBlockedBinaryHostname', () => {
|
|
15
|
+
it('blocks loopback and private IPv4 hosts', () => {
|
|
16
|
+
expect(isBlockedBinaryHostname('localhost')).toBe(true);
|
|
17
|
+
expect(isBlockedBinaryHostname('127.0.0.1')).toBe(true);
|
|
18
|
+
expect(isBlockedBinaryHostname('10.0.0.1')).toBe(true);
|
|
19
|
+
expect(isBlockedBinaryHostname('192.168.1.1')).toBe(true);
|
|
20
|
+
expect(isBlockedBinaryHostname('172.16.0.1')).toBe(true);
|
|
21
|
+
expect(isBlockedBinaryHostname('169.254.169.254')).toBe(true);
|
|
22
|
+
expect(isBlockedBinaryHostname('metadata.google.internal')).toBe(true);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('allows public hostnames', () => {
|
|
26
|
+
expect(isBlockedBinaryHostname('cdn.example.com')).toBe(false);
|
|
27
|
+
expect(isBlockedBinaryHostname('s3.amazonaws.com')).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('assertSafeBinaryFetchUrl', () => {
|
|
32
|
+
it('rejects same-host HTTPS to HTTP downgrades', () => {
|
|
33
|
+
expect(() =>
|
|
34
|
+
assertSafeBinaryFetchUrl(
|
|
35
|
+
'http://app.lightdash.com/export/chart.png',
|
|
36
|
+
'https://app.lightdash.com',
|
|
37
|
+
),
|
|
38
|
+
).toThrow(/must not downgrade HTTPS to HTTP/);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('allows same-host HTTPS URLs', () => {
|
|
42
|
+
expect(() =>
|
|
43
|
+
assertSafeBinaryFetchUrl(
|
|
44
|
+
'https://app.lightdash.com/export/chart.png',
|
|
45
|
+
'https://app.lightdash.com',
|
|
46
|
+
),
|
|
47
|
+
).not.toThrow();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('allows relative URLs without validation', () => {
|
|
51
|
+
expect(() =>
|
|
52
|
+
assertSafeBinaryFetchUrl('/api/v1/export.png', 'https://app.lightdash.com'),
|
|
53
|
+
).not.toThrow();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('HttpClient.getBytes', () => {
|
|
58
|
+
function makeClient(getImpl: ReturnType<typeof vi.fn>) {
|
|
59
|
+
const axiosInstance = { get: getImpl } as unknown as AxiosInstance;
|
|
60
|
+
const rateLimiter = {
|
|
61
|
+
schedule: <T>(fn: () => Promise<T>) => fn(),
|
|
62
|
+
} as unknown as RateLimiter;
|
|
63
|
+
const config = {
|
|
64
|
+
baseUrl: 'https://app.lightdash.com',
|
|
65
|
+
timeout: 30_000,
|
|
66
|
+
retry: { maxRetries: 0 },
|
|
67
|
+
} as unknown as ResolvedLightdashClientConfig;
|
|
68
|
+
return new HttpClient(axiosInstance, rateLimiter, config);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
it('maps axios maxContentLength errors to BinarySizeLimitError', async () => {
|
|
72
|
+
const maxBytes = 1024;
|
|
73
|
+
const axiosError = new AxiosError('maxContentLength size of 1024 exceeded');
|
|
74
|
+
const client = makeClient(vi.fn().mockRejectedValue(axiosError));
|
|
75
|
+
|
|
76
|
+
await expect(client.getBytes('/chart.png', { maxBytes })).rejects.toMatchObject({
|
|
77
|
+
code: 'PAYLOAD_TOO_LARGE',
|
|
78
|
+
maxBytes,
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('rejects same-host HTTP downgrade before fetching', async () => {
|
|
83
|
+
const client = makeClient(vi.fn());
|
|
84
|
+
await expect(client.getBytes('http://app.lightdash.com/chart.png')).rejects.toThrow(
|
|
85
|
+
/must not downgrade HTTPS to HTTP/,
|
|
86
|
+
);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unit tests for HttpClient success-envelope harden.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { CONTRACT_ERROR_MESSAGE, CONTRACT_ERROR_NAME, LightdashApiError } from '../errors.js';
|
|
8
|
+
|
|
9
|
+
import { HttpClient } from './http-client.js';
|
|
10
|
+
|
|
11
|
+
import type { ResolvedLightdashClientConfig } from '../config.js';
|
|
12
|
+
import type { RateLimiter } from './rate-limiter.js';
|
|
13
|
+
import type { AxiosInstance } from 'axios';
|
|
14
|
+
|
|
15
|
+
describe('HttpClient envelope harden', () => {
|
|
16
|
+
function makeClient(requestImpl: ReturnType<typeof vi.fn>) {
|
|
17
|
+
const axiosInstance = { request: requestImpl } as unknown as AxiosInstance;
|
|
18
|
+
const rateLimiter = {
|
|
19
|
+
schedule: <T>(fn: () => Promise<T>) => fn(),
|
|
20
|
+
} as unknown as RateLimiter;
|
|
21
|
+
const config = {
|
|
22
|
+
baseUrl: 'https://app.lightdash.com',
|
|
23
|
+
timeout: 30_000,
|
|
24
|
+
retry: { maxRetries: 0 },
|
|
25
|
+
} as unknown as ResolvedLightdashClientConfig;
|
|
26
|
+
return new HttpClient(axiosInstance, rateLimiter, config);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
it('returns results for ok envelopes', async () => {
|
|
30
|
+
const client = makeClient(
|
|
31
|
+
vi.fn().mockResolvedValue({
|
|
32
|
+
status: 200,
|
|
33
|
+
data: { status: 'ok', results: { id: '1' } },
|
|
34
|
+
config: {},
|
|
35
|
+
}),
|
|
36
|
+
);
|
|
37
|
+
await expect(client.get('/x')).resolves.toEqual({ id: '1' });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('throws LightdashApiError for error envelopes', async () => {
|
|
41
|
+
const client = makeClient(
|
|
42
|
+
vi.fn().mockResolvedValue({
|
|
43
|
+
status: 200,
|
|
44
|
+
data: {
|
|
45
|
+
status: 'error',
|
|
46
|
+
error: { name: 'Bad', statusCode: 400, message: 'nope' },
|
|
47
|
+
},
|
|
48
|
+
config: {},
|
|
49
|
+
}),
|
|
50
|
+
);
|
|
51
|
+
await expect(client.get('/x')).rejects.toMatchObject({
|
|
52
|
+
statusCode: 400,
|
|
53
|
+
error: { message: 'nope' },
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('throws ContractError for malformed 200 bodies', async () => {
|
|
58
|
+
const client = makeClient(
|
|
59
|
+
vi.fn().mockResolvedValue({
|
|
60
|
+
status: 200,
|
|
61
|
+
data: { foo: 1 },
|
|
62
|
+
config: {},
|
|
63
|
+
}),
|
|
64
|
+
);
|
|
65
|
+
await expect(client.get('/x')).rejects.toSatisfy((err: unknown) => {
|
|
66
|
+
expect(err).toBeInstanceOf(LightdashApiError);
|
|
67
|
+
const apiErr = err as LightdashApiError;
|
|
68
|
+
expect(apiErr.statusCode).toBe(502);
|
|
69
|
+
expect(apiErr.error.name).toBe(CONTRACT_ERROR_NAME);
|
|
70
|
+
expect(apiErr.error.message).toBe(CONTRACT_ERROR_MESSAGE);
|
|
71
|
+
return true;
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
});
|
package/src/http/http-client.ts
CHANGED
|
@@ -3,28 +3,135 @@
|
|
|
3
3
|
* All requests go through the rate limiter; retry applies to 5xx and network errors.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import
|
|
6
|
+
import axios from 'axios';
|
|
7
|
+
|
|
8
|
+
import { DEFAULT_TIMEOUT } from '../config';
|
|
9
|
+
import {
|
|
10
|
+
type ApiErrorPayload,
|
|
11
|
+
BinarySizeLimitError,
|
|
12
|
+
CONTRACT_ERROR_MESSAGE,
|
|
13
|
+
CONTRACT_ERROR_NAME,
|
|
14
|
+
LightdashApiError,
|
|
15
|
+
NetworkError,
|
|
16
|
+
} from '../errors';
|
|
7
17
|
import { withRetry } from '../utils/retry';
|
|
8
18
|
|
|
9
19
|
import { type RateLimiter } from './rate-limiter';
|
|
20
|
+
import { isApiSuccessEnvelope, type ApiEnvelope } from './unwrap-api-success';
|
|
10
21
|
|
|
11
22
|
import type { ResolvedLightdashClientConfig } from '../config';
|
|
12
23
|
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from 'axios';
|
|
13
24
|
|
|
14
|
-
/**
|
|
15
|
-
export
|
|
16
|
-
|
|
17
|
-
|
|
25
|
+
/** Default max raw bytes for chart PNG downloads (8 MiB). */
|
|
26
|
+
export const DEFAULT_BINARY_MAX_BYTES = 8 * 1024 * 1024;
|
|
27
|
+
|
|
28
|
+
export type GetBytesOptions = {
|
|
29
|
+
/** Hard cap on response body size in bytes. */
|
|
30
|
+
maxBytes?: number;
|
|
31
|
+
/** Per-request timeout override (ms). */
|
|
32
|
+
timeout?: number;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type GetBytesResult = {
|
|
36
|
+
bytes: Buffer;
|
|
37
|
+
mimeType: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function isPrivateIpv4Octets(a: number, b: number): boolean {
|
|
41
|
+
if (a === 0 || a === 10 || a === 127) {
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
if (a === 169 && b === 254) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
if (a === 192 && b === 168) {
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
return a === 172 && b >= 16 && b <= 31;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function isBlockedIpv6Host(host: string): boolean {
|
|
54
|
+
if (host === '::1' || host.startsWith('fe80:')) {
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
// Unique-local IPv6 (fc00::/7)
|
|
58
|
+
return host.startsWith('fc') || host.startsWith('fd');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isAxiosMaxContentLengthError(err: unknown): boolean {
|
|
62
|
+
if (!axios.isAxiosError(err)) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
if (typeof err.message !== 'string') {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return err.message.includes('maxContentLength') || err.message.includes('maxBodyLength');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** True when hostname is loopback, link-local, or RFC1918 (cross-host SSRF guard). */
|
|
72
|
+
export function isBlockedBinaryHostname(hostname: string): boolean {
|
|
73
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
74
|
+
if (host === 'localhost' || host === 'metadata.google.internal') {
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
78
|
+
if (ipv4 && isPrivateIpv4Octets(Number(ipv4[1]), Number(ipv4[2]))) {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
return isBlockedIpv6Host(host);
|
|
18
82
|
}
|
|
19
83
|
|
|
20
|
-
/**
|
|
21
|
-
export
|
|
22
|
-
|
|
23
|
-
|
|
84
|
+
/** Reject unsafe absolute binary download URLs (exported for unit tests). */
|
|
85
|
+
export function assertSafeBinaryFetchUrl(url: string, baseUrl: string): void {
|
|
86
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
let parsed: URL;
|
|
90
|
+
try {
|
|
91
|
+
parsed = new URL(url);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
throw new NetworkError(
|
|
94
|
+
'Invalid binary download URL',
|
|
95
|
+
err instanceof Error ? err : new Error(String(err)),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
const base = new URL(baseUrl);
|
|
99
|
+
if (parsed.host === base.host && parsed.protocol === 'http:' && base.protocol === 'https:') {
|
|
100
|
+
throw new NetworkError(
|
|
101
|
+
'Binary download URL must not downgrade HTTPS to HTTP',
|
|
102
|
+
new Error(`${base.protocol} -> ${parsed.protocol}`),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
const crossHost = parsed.host !== base.host;
|
|
106
|
+
if (!crossHost) {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (parsed.protocol !== 'https:') {
|
|
110
|
+
throw new NetworkError(
|
|
111
|
+
'Cross-host binary download URL must use https',
|
|
112
|
+
new Error(parsed.protocol),
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (isBlockedBinaryHostname(parsed.hostname)) {
|
|
116
|
+
throw new NetworkError(
|
|
117
|
+
`Binary download host is not allowed: ${parsed.hostname}`,
|
|
118
|
+
new Error(parsed.hostname),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
24
121
|
}
|
|
25
122
|
|
|
26
|
-
function
|
|
27
|
-
|
|
123
|
+
function readApiErrorPayload(data: unknown): ApiErrorPayload['error'] | undefined {
|
|
124
|
+
if (data === null || typeof data !== 'object' || !('error' in data)) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const error = (data as { error: unknown }).error;
|
|
128
|
+
if (error === null || typeof error !== 'object') {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
if (typeof (error as { statusCode?: unknown }).statusCode !== 'number') {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
return error as ApiErrorPayload['error'];
|
|
28
135
|
}
|
|
29
136
|
|
|
30
137
|
/**
|
|
@@ -39,7 +146,7 @@ export class HttpClient {
|
|
|
39
146
|
|
|
40
147
|
private async request<T>(method: Method, url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
41
148
|
const doRequest = () =>
|
|
42
|
-
this.axiosInstance.request<
|
|
149
|
+
this.axiosInstance.request<ApiEnvelope<T>>({
|
|
43
150
|
...config,
|
|
44
151
|
method,
|
|
45
152
|
url,
|
|
@@ -48,15 +155,35 @@ export class HttpClient {
|
|
|
48
155
|
const response = await this.rateLimiter.schedule(() => withRetry(doRequest, this.config.retry));
|
|
49
156
|
|
|
50
157
|
const data = response.data;
|
|
51
|
-
if (
|
|
158
|
+
if (data !== null && typeof data === 'object') {
|
|
159
|
+
const envelope = data as ApiEnvelope<T>;
|
|
160
|
+
if (isApiSuccessEnvelope(envelope)) {
|
|
161
|
+
return envelope.results;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const apiError = readApiErrorPayload(data);
|
|
166
|
+
if (apiError !== undefined) {
|
|
52
167
|
throw new LightdashApiError(
|
|
53
|
-
|
|
54
|
-
|
|
168
|
+
apiError.statusCode,
|
|
169
|
+
apiError,
|
|
55
170
|
response.config,
|
|
56
171
|
response as AxiosResponse<ApiErrorPayload>,
|
|
57
172
|
);
|
|
58
173
|
}
|
|
59
|
-
|
|
174
|
+
|
|
175
|
+
const httpStatus = response.status;
|
|
176
|
+
const contractStatus = typeof httpStatus === 'number' && httpStatus >= 400 ? httpStatus : 502;
|
|
177
|
+
throw new LightdashApiError(
|
|
178
|
+
contractStatus,
|
|
179
|
+
{
|
|
180
|
+
name: CONTRACT_ERROR_NAME,
|
|
181
|
+
statusCode: contractStatus,
|
|
182
|
+
message: CONTRACT_ERROR_MESSAGE,
|
|
183
|
+
},
|
|
184
|
+
response.config,
|
|
185
|
+
response as AxiosResponse<ApiErrorPayload>,
|
|
186
|
+
);
|
|
60
187
|
}
|
|
61
188
|
|
|
62
189
|
async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
@@ -78,4 +205,55 @@ export class HttpClient {
|
|
|
78
205
|
async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
|
|
79
206
|
return this.request<T>('DELETE', url, config);
|
|
80
207
|
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
|
|
211
|
+
* authenticated API client; absolute URLs on a different host (e.g. signed S3)
|
|
212
|
+
* are fetched without Lightdash Authorization. Cross-host fetches require https,
|
|
213
|
+
* disallow private/link-local hosts, and follow no redirects.
|
|
214
|
+
*/
|
|
215
|
+
async getBytes(url: string, options?: GetBytesOptions): Promise<GetBytesResult> {
|
|
216
|
+
const maxBytes = options?.maxBytes ?? DEFAULT_BINARY_MAX_BYTES;
|
|
217
|
+
const timeout = options?.timeout ?? this.config.timeout ?? DEFAULT_TIMEOUT;
|
|
218
|
+
assertSafeBinaryFetchUrl(url, this.config.baseUrl);
|
|
219
|
+
const binaryConfig: AxiosRequestConfig = {
|
|
220
|
+
responseType: 'arraybuffer',
|
|
221
|
+
timeout,
|
|
222
|
+
maxContentLength: maxBytes,
|
|
223
|
+
maxBodyLength: maxBytes,
|
|
224
|
+
maxRedirects: 0,
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const doRequest = (): Promise<AxiosResponse<ArrayBuffer>> => {
|
|
228
|
+
if (/^https?:\/\//i.test(url)) {
|
|
229
|
+
const targetHost = new URL(url).host;
|
|
230
|
+
const baseHost = new URL(this.config.baseUrl).host;
|
|
231
|
+
if (targetHost !== baseHost) {
|
|
232
|
+
return axios.get<ArrayBuffer>(url, binaryConfig);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return this.axiosInstance.get<ArrayBuffer>(url, binaryConfig);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
let response: AxiosResponse<ArrayBuffer>;
|
|
239
|
+
try {
|
|
240
|
+
// No retries: binary bodies can be multi-MiB; a 5xx would re-download the payload.
|
|
241
|
+
response = await this.rateLimiter.schedule(doRequest);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
if (isAxiosMaxContentLengthError(err)) {
|
|
244
|
+
throw new BinarySizeLimitError(maxBytes);
|
|
245
|
+
}
|
|
246
|
+
throw err;
|
|
247
|
+
}
|
|
248
|
+
const bytes = Buffer.from(response.data);
|
|
249
|
+
if (bytes.byteLength > maxBytes) {
|
|
250
|
+
throw new BinarySizeLimitError(maxBytes, bytes.byteLength);
|
|
251
|
+
}
|
|
252
|
+
const rawType = response.headers['content-type'];
|
|
253
|
+
const mimeType =
|
|
254
|
+
typeof rawType === 'string'
|
|
255
|
+
? (rawType.split(';')[0]?.trim() ?? 'application/octet-stream')
|
|
256
|
+
: 'application/octet-stream';
|
|
257
|
+
return { bytes, mimeType };
|
|
258
|
+
}
|
|
81
259
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { isApiSuccessEnvelope, unwrapApiSuccessResults } from './unwrap-api-success';
|
|
4
|
+
|
|
5
|
+
describe('unwrapApiSuccessResults', () => {
|
|
6
|
+
it('returns results for ok envelopes', () => {
|
|
7
|
+
expect(unwrapApiSuccessResults({ status: 'ok', results: { id: '1' } })).toEqual({ id: '1' });
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('throws for error envelopes', () => {
|
|
11
|
+
expect(() =>
|
|
12
|
+
unwrapApiSuccessResults({
|
|
13
|
+
status: 'error',
|
|
14
|
+
error: { statusCode: 400, message: 'bad request' },
|
|
15
|
+
}),
|
|
16
|
+
).toThrow(/bad request/);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('narrows success envelopes', () => {
|
|
20
|
+
const body = { status: 'ok' as const, results: [1, 2] };
|
|
21
|
+
expect(isApiSuccessEnvelope(body)).toBe(true);
|
|
22
|
+
});
|
|
23
|
+
});
|