@lightdash-tools/client 0.8.0 → 0.11.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 +19 -0
- package/dist/api/v1/charts.js +43 -1
- package/dist/api/v1/charts.test.js +45 -8
- 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 -0
- 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 -4
- package/dist/index.d.ts +3 -1
- package/dist/index.js +12 -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 +43 -1
- package/src/api/v1/charts.ts +51 -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 +198 -5
- package/src/index.ts +19 -1
package/dist/http/http-client.js
CHANGED
|
@@ -3,11 +3,100 @@
|
|
|
3
3
|
* HTTP client wrapper: rate limiter + axios + retry.
|
|
4
4
|
* All requests go through the rate limiter; retry applies to 5xx and network errors.
|
|
5
5
|
*/
|
|
6
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
7
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
8
|
+
};
|
|
6
9
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
-
exports.HttpClient = void 0;
|
|
10
|
+
exports.HttpClient = exports.DEFAULT_BINARY_MAX_BYTES = void 0;
|
|
11
|
+
exports.isBlockedBinaryHostname = isBlockedBinaryHostname;
|
|
12
|
+
exports.assertSafeBinaryFetchUrl = assertSafeBinaryFetchUrl;
|
|
13
|
+
const axios_1 = __importDefault(require("axios"));
|
|
14
|
+
const config_1 = require("../config");
|
|
8
15
|
const errors_1 = require("../errors");
|
|
9
16
|
const retry_1 = require("../utils/retry");
|
|
10
17
|
const unwrap_api_success_1 = require("./unwrap-api-success");
|
|
18
|
+
/** Default max raw bytes for chart PNG downloads (8 MiB). */
|
|
19
|
+
exports.DEFAULT_BINARY_MAX_BYTES = 8 * 1024 * 1024;
|
|
20
|
+
function isPrivateIpv4Octets(a, b) {
|
|
21
|
+
if (a === 0 || a === 10 || a === 127) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
if (a === 169 && b === 254) {
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
if (a === 192 && b === 168) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
return a === 172 && b >= 16 && b <= 31;
|
|
31
|
+
}
|
|
32
|
+
function isBlockedIpv6Host(host) {
|
|
33
|
+
if (host === '::1' || host.startsWith('fe80:')) {
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
// Unique-local IPv6 (fc00::/7)
|
|
37
|
+
return host.startsWith('fc') || host.startsWith('fd');
|
|
38
|
+
}
|
|
39
|
+
function isAxiosMaxContentLengthError(err) {
|
|
40
|
+
if (!axios_1.default.isAxiosError(err)) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (typeof err.message !== 'string') {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return err.message.includes('maxContentLength') || err.message.includes('maxBodyLength');
|
|
47
|
+
}
|
|
48
|
+
/** True when hostname is loopback, link-local, or RFC1918 (cross-host SSRF guard). */
|
|
49
|
+
function isBlockedBinaryHostname(hostname) {
|
|
50
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
51
|
+
if (host === 'localhost' || host === 'metadata.google.internal') {
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
55
|
+
if (ipv4 && isPrivateIpv4Octets(Number(ipv4[1]), Number(ipv4[2]))) {
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
return isBlockedIpv6Host(host);
|
|
59
|
+
}
|
|
60
|
+
/** Reject unsafe absolute binary download URLs (exported for unit tests). */
|
|
61
|
+
function assertSafeBinaryFetchUrl(url, baseUrl) {
|
|
62
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
let parsed;
|
|
66
|
+
try {
|
|
67
|
+
parsed = new URL(url);
|
|
68
|
+
}
|
|
69
|
+
catch (err) {
|
|
70
|
+
throw new errors_1.NetworkError('Invalid binary download URL', err instanceof Error ? err : new Error(String(err)));
|
|
71
|
+
}
|
|
72
|
+
const base = new URL(baseUrl);
|
|
73
|
+
if (parsed.host === base.host && parsed.protocol === 'http:' && base.protocol === 'https:') {
|
|
74
|
+
throw new errors_1.NetworkError('Binary download URL must not downgrade HTTPS to HTTP', new Error(`${base.protocol} -> ${parsed.protocol}`));
|
|
75
|
+
}
|
|
76
|
+
const crossHost = parsed.host !== base.host;
|
|
77
|
+
if (!crossHost) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (parsed.protocol !== 'https:') {
|
|
81
|
+
throw new errors_1.NetworkError('Cross-host binary download URL must use https', new Error(parsed.protocol));
|
|
82
|
+
}
|
|
83
|
+
if (isBlockedBinaryHostname(parsed.hostname)) {
|
|
84
|
+
throw new errors_1.NetworkError(`Binary download host is not allowed: ${parsed.hostname}`, new Error(parsed.hostname));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function readApiErrorPayload(data) {
|
|
88
|
+
if (data === null || typeof data !== 'object' || !('error' in data)) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
const error = data.error;
|
|
92
|
+
if (error === null || typeof error !== 'object') {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
if (typeof error.statusCode !== 'number') {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
return error;
|
|
99
|
+
}
|
|
11
100
|
/**
|
|
12
101
|
* HTTP client that wraps Axios with rate limiting and retry.
|
|
13
102
|
*/
|
|
@@ -22,10 +111,23 @@ class HttpClient {
|
|
|
22
111
|
url }));
|
|
23
112
|
const response = await this.rateLimiter.schedule(() => (0, retry_1.withRetry)(doRequest, this.config.retry));
|
|
24
113
|
const data = response.data;
|
|
25
|
-
if (
|
|
26
|
-
|
|
114
|
+
if (data !== null && typeof data === 'object') {
|
|
115
|
+
const envelope = data;
|
|
116
|
+
if ((0, unwrap_api_success_1.isApiSuccessEnvelope)(envelope)) {
|
|
117
|
+
return envelope.results;
|
|
118
|
+
}
|
|
27
119
|
}
|
|
28
|
-
|
|
120
|
+
const apiError = readApiErrorPayload(data);
|
|
121
|
+
if (apiError !== undefined) {
|
|
122
|
+
throw new errors_1.LightdashApiError(apiError.statusCode, apiError, response.config, response);
|
|
123
|
+
}
|
|
124
|
+
const httpStatus = response.status;
|
|
125
|
+
const contractStatus = typeof httpStatus === 'number' && httpStatus >= 400 ? httpStatus : 502;
|
|
126
|
+
throw new errors_1.LightdashApiError(contractStatus, {
|
|
127
|
+
name: errors_1.CONTRACT_ERROR_NAME,
|
|
128
|
+
statusCode: contractStatus,
|
|
129
|
+
message: errors_1.CONTRACT_ERROR_MESSAGE,
|
|
130
|
+
}, response.config, response);
|
|
29
131
|
}
|
|
30
132
|
async get(url, config) {
|
|
31
133
|
return this.request('GET', url, config);
|
|
@@ -42,5 +144,54 @@ class HttpClient {
|
|
|
42
144
|
async delete(url, config) {
|
|
43
145
|
return this.request('DELETE', url, config);
|
|
44
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
|
|
149
|
+
* authenticated API client; absolute URLs on a different host (e.g. signed S3)
|
|
150
|
+
* are fetched without Lightdash Authorization. Cross-host fetches require https,
|
|
151
|
+
* disallow private/link-local hosts, and follow no redirects.
|
|
152
|
+
*/
|
|
153
|
+
async getBytes(url, options) {
|
|
154
|
+
var _a, _b, _c, _d, _e;
|
|
155
|
+
const maxBytes = (_a = options === null || options === void 0 ? void 0 : options.maxBytes) !== null && _a !== void 0 ? _a : exports.DEFAULT_BINARY_MAX_BYTES;
|
|
156
|
+
const timeout = (_c = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : this.config.timeout) !== null && _c !== void 0 ? _c : config_1.DEFAULT_TIMEOUT;
|
|
157
|
+
assertSafeBinaryFetchUrl(url, this.config.baseUrl);
|
|
158
|
+
const binaryConfig = {
|
|
159
|
+
responseType: 'arraybuffer',
|
|
160
|
+
timeout,
|
|
161
|
+
maxContentLength: maxBytes,
|
|
162
|
+
maxBodyLength: maxBytes,
|
|
163
|
+
maxRedirects: 0,
|
|
164
|
+
};
|
|
165
|
+
const doRequest = () => {
|
|
166
|
+
if (/^https?:\/\//i.test(url)) {
|
|
167
|
+
const targetHost = new URL(url).host;
|
|
168
|
+
const baseHost = new URL(this.config.baseUrl).host;
|
|
169
|
+
if (targetHost !== baseHost) {
|
|
170
|
+
return axios_1.default.get(url, binaryConfig);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return this.axiosInstance.get(url, binaryConfig);
|
|
174
|
+
};
|
|
175
|
+
let response;
|
|
176
|
+
try {
|
|
177
|
+
// No retries: binary bodies can be multi-MiB; a 5xx would re-download the payload.
|
|
178
|
+
response = await this.rateLimiter.schedule(doRequest);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
if (isAxiosMaxContentLengthError(err)) {
|
|
182
|
+
throw new errors_1.BinarySizeLimitError(maxBytes);
|
|
183
|
+
}
|
|
184
|
+
throw err;
|
|
185
|
+
}
|
|
186
|
+
const bytes = Buffer.from(response.data);
|
|
187
|
+
if (bytes.byteLength > maxBytes) {
|
|
188
|
+
throw new errors_1.BinarySizeLimitError(maxBytes, bytes.byteLength);
|
|
189
|
+
}
|
|
190
|
+
const rawType = response.headers['content-type'];
|
|
191
|
+
const mimeType = typeof rawType === 'string'
|
|
192
|
+
? ((_e = (_d = rawType.split(';')[0]) === null || _d === void 0 ? void 0 : _d.trim()) !== null && _e !== void 0 ? _e : 'application/octet-stream')
|
|
193
|
+
: 'application/octet-stream';
|
|
194
|
+
return { bytes, mimeType };
|
|
195
|
+
}
|
|
45
196
|
}
|
|
46
197
|
exports.HttpClient = HttpClient;
|
package/dist/index.d.ts
CHANGED
|
@@ -30,8 +30,10 @@ export type { PartialLightdashClientConfig } from './config';
|
|
|
30
30
|
export type { LightdashClientConfig, LightdashAuthConfig, ResolvedLightdashClientConfig, RateLimitConfig, RetryConfig, Logger, ObservabilityHooks, } from './config';
|
|
31
31
|
export { noopLogger, consoleLogger } from './utils/logger';
|
|
32
32
|
export { DEFAULT_RATE_LIMIT, DEFAULT_TIMEOUT, DEFAULT_RETRY } from './config';
|
|
33
|
-
export { LightdashApiError, RateLimitError, NetworkError } from './errors';
|
|
33
|
+
export { LightdashApiError, RateLimitError, NetworkError, ChartImageSizeError, CONTRACT_ERROR_NAME, CONTRACT_ERROR_MESSAGE, } from './errors';
|
|
34
34
|
export type { ApiErrorPayload } from './errors';
|
|
35
|
+
export { CHART_IMAGE_EXPORT_TIMEOUT_MS, CHART_IMAGE_MAX_BYTES, type ChartImagePng, } from './api/v1/charts';
|
|
36
|
+
export { DEFAULT_BINARY_MAX_BYTES, isBlockedBinaryHostname, type GetBytesOptions, type GetBytesResult, } from './http/http-client';
|
|
35
37
|
export { loadConfigFromEnv, mergeConfig, createBearerConfig } from './utils/env';
|
|
36
38
|
export { ENV_LIGHTDASH_API_KEY, ENV_LIGHTDASH_URL, ENV_LIGHTDASH_PROXY_AUTHORIZATION, } from './utils/env';
|
|
37
39
|
export { HttpClient } from './http/http-client';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SecretString = exports.RateLimiter = exports.unwrapApiSuccessResults = exports.isApiSuccessEnvelope = exports.HttpClient = exports.ENV_LIGHTDASH_PROXY_AUTHORIZATION = exports.ENV_LIGHTDASH_URL = exports.ENV_LIGHTDASH_API_KEY = exports.createBearerConfig = exports.mergeConfig = exports.loadConfigFromEnv = exports.NetworkError = exports.RateLimitError = exports.LightdashApiError = exports.DEFAULT_RETRY = exports.DEFAULT_TIMEOUT = exports.DEFAULT_RATE_LIMIT = exports.consoleLogger = exports.noopLogger = exports.DashboardsClientV2 = exports.ChartsClientV2 = exports.ContentClient = exports.AnalyticsClient = exports.TagsClient = exports.SchedulersClient = exports.MetricsClient = exports.ValidationClientV2 = exports.ValidationClient = exports.ProjectAccessClient = exports.AiAgentsClient = exports.ProjectRoleAssignmentsClient = exports.OrganizationRolesClient = exports.GroupsClient = exports.UsersClient = exports.resolveEvaluationRun = exports.applyBundleDiff = exports.fetchBundleCurrentState = exports.V2ApiClients = exports.V1ApiClients = exports.LightdashClient = void 0;
|
|
3
|
+
exports.SecretString = exports.RateLimiter = exports.unwrapApiSuccessResults = exports.isApiSuccessEnvelope = exports.HttpClient = exports.ENV_LIGHTDASH_PROXY_AUTHORIZATION = exports.ENV_LIGHTDASH_URL = exports.ENV_LIGHTDASH_API_KEY = exports.createBearerConfig = exports.mergeConfig = exports.loadConfigFromEnv = exports.isBlockedBinaryHostname = exports.DEFAULT_BINARY_MAX_BYTES = exports.CHART_IMAGE_MAX_BYTES = exports.CHART_IMAGE_EXPORT_TIMEOUT_MS = exports.CONTRACT_ERROR_MESSAGE = exports.CONTRACT_ERROR_NAME = exports.ChartImageSizeError = exports.NetworkError = exports.RateLimitError = exports.LightdashApiError = exports.DEFAULT_RETRY = exports.DEFAULT_TIMEOUT = exports.DEFAULT_RATE_LIMIT = exports.consoleLogger = exports.noopLogger = exports.DashboardsClientV2 = exports.ChartsClientV2 = exports.ContentClient = exports.AnalyticsClient = exports.TagsClient = exports.SchedulersClient = exports.MetricsClient = exports.ValidationClientV2 = exports.ValidationClient = exports.ProjectAccessClient = exports.AiAgentsClient = exports.ProjectRoleAssignmentsClient = exports.OrganizationRolesClient = exports.GroupsClient = exports.UsersClient = exports.resolveEvaluationRun = exports.applyBundleDiff = exports.fetchBundleCurrentState = exports.V2ApiClients = exports.V1ApiClients = exports.LightdashClient = void 0;
|
|
4
4
|
var client_1 = require("./client");
|
|
5
5
|
Object.defineProperty(exports, "LightdashClient", { enumerable: true, get: function () { return client_1.LightdashClient; } });
|
|
6
6
|
Object.defineProperty(exports, "V1ApiClients", { enumerable: true, get: function () { return client_1.V1ApiClients; } });
|
|
@@ -50,6 +50,15 @@ var errors_1 = require("./errors");
|
|
|
50
50
|
Object.defineProperty(exports, "LightdashApiError", { enumerable: true, get: function () { return errors_1.LightdashApiError; } });
|
|
51
51
|
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_1.RateLimitError; } });
|
|
52
52
|
Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return errors_1.NetworkError; } });
|
|
53
|
+
Object.defineProperty(exports, "ChartImageSizeError", { enumerable: true, get: function () { return errors_1.ChartImageSizeError; } });
|
|
54
|
+
Object.defineProperty(exports, "CONTRACT_ERROR_NAME", { enumerable: true, get: function () { return errors_1.CONTRACT_ERROR_NAME; } });
|
|
55
|
+
Object.defineProperty(exports, "CONTRACT_ERROR_MESSAGE", { enumerable: true, get: function () { return errors_1.CONTRACT_ERROR_MESSAGE; } });
|
|
56
|
+
var charts_2 = require("./api/v1/charts");
|
|
57
|
+
Object.defineProperty(exports, "CHART_IMAGE_EXPORT_TIMEOUT_MS", { enumerable: true, get: function () { return charts_2.CHART_IMAGE_EXPORT_TIMEOUT_MS; } });
|
|
58
|
+
Object.defineProperty(exports, "CHART_IMAGE_MAX_BYTES", { enumerable: true, get: function () { return charts_2.CHART_IMAGE_MAX_BYTES; } });
|
|
59
|
+
var http_client_1 = require("./http/http-client");
|
|
60
|
+
Object.defineProperty(exports, "DEFAULT_BINARY_MAX_BYTES", { enumerable: true, get: function () { return http_client_1.DEFAULT_BINARY_MAX_BYTES; } });
|
|
61
|
+
Object.defineProperty(exports, "isBlockedBinaryHostname", { enumerable: true, get: function () { return http_client_1.isBlockedBinaryHostname; } });
|
|
53
62
|
var env_1 = require("./utils/env");
|
|
54
63
|
Object.defineProperty(exports, "loadConfigFromEnv", { enumerable: true, get: function () { return env_1.loadConfigFromEnv; } });
|
|
55
64
|
Object.defineProperty(exports, "mergeConfig", { enumerable: true, get: function () { return env_1.mergeConfig; } });
|
|
@@ -58,8 +67,8 @@ var env_2 = require("./utils/env");
|
|
|
58
67
|
Object.defineProperty(exports, "ENV_LIGHTDASH_API_KEY", { enumerable: true, get: function () { return env_2.ENV_LIGHTDASH_API_KEY; } });
|
|
59
68
|
Object.defineProperty(exports, "ENV_LIGHTDASH_URL", { enumerable: true, get: function () { return env_2.ENV_LIGHTDASH_URL; } });
|
|
60
69
|
Object.defineProperty(exports, "ENV_LIGHTDASH_PROXY_AUTHORIZATION", { enumerable: true, get: function () { return env_2.ENV_LIGHTDASH_PROXY_AUTHORIZATION; } });
|
|
61
|
-
var
|
|
62
|
-
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return
|
|
70
|
+
var http_client_2 = require("./http/http-client");
|
|
71
|
+
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return http_client_2.HttpClient; } });
|
|
63
72
|
var unwrap_api_success_1 = require("./http/unwrap-api-success");
|
|
64
73
|
Object.defineProperty(exports, "isApiSuccessEnvelope", { enumerable: true, get: function () { return unwrap_api_success_1.isApiSuccessEnvelope; } });
|
|
65
74
|
Object.defineProperty(exports, "unwrapApiSuccessResults", { enumerable: true, get: function () { return unwrap_api_success_1.unwrapApiSuccessResults; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lightdash-tools/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Client library for Lightdash AI.",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"repository": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"axios": "^1.19.0",
|
|
17
17
|
"bottleneck": "^2.19.5",
|
|
18
|
-
"@lightdash-tools/common": "0.
|
|
18
|
+
"@lightdash-tools/common": "0.11.0"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"@types/node": "^25.9.3"
|
|
@@ -53,7 +53,7 @@ describe('AiAgentsDiscoveryClient', () => {
|
|
|
53
53
|
const client = new AiAgentsDiscoveryClient(mockHttp);
|
|
54
54
|
const summary = [{ exploreName: 'orders', metrics: [], dimensions: [], joinedTables: [] }];
|
|
55
55
|
vi.mocked(mockHttp.post).mockResolvedValue(summary);
|
|
56
|
-
const result = await client.getExploreAccessSummary('proj1',
|
|
56
|
+
const result = await client.getExploreAccessSummary('proj1', { tags: ['ai'] });
|
|
57
57
|
expect(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
|
|
58
58
|
tags: ['ai'],
|
|
59
59
|
});
|
|
@@ -61,6 +61,24 @@ describe('AiAgentsDiscoveryClient', () => {
|
|
|
61
61
|
});
|
|
62
62
|
|
|
63
63
|
it('getExploreAccessSummary without body should default tags to null', async () => {
|
|
64
|
+
const client = new AiAgentsDiscoveryClient(mockHttp);
|
|
65
|
+
vi.mocked(mockHttp.post).mockResolvedValue([]);
|
|
66
|
+
await client.getExploreAccessSummary('proj1');
|
|
67
|
+
expect(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
|
|
68
|
+
tags: null,
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('getExploreAccessSummary legacy (project, agentUuid, body) ignores agentUuid', async () => {
|
|
73
|
+
const client = new AiAgentsDiscoveryClient(mockHttp);
|
|
74
|
+
vi.mocked(mockHttp.post).mockResolvedValue([]);
|
|
75
|
+
await client.getExploreAccessSummary('proj1', 'a1', { tags: ['ai'] });
|
|
76
|
+
expect(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
|
|
77
|
+
tags: ['ai'],
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('getExploreAccessSummary legacy (project, agentUuid) defaults tags to null', async () => {
|
|
64
82
|
const client = new AiAgentsDiscoveryClient(mockHttp);
|
|
65
83
|
vi.mocked(mockHttp.post).mockResolvedValue([]);
|
|
66
84
|
await client.getExploreAccessSummary('proj1', 'a1');
|
|
@@ -43,16 +43,30 @@ export class AiAgentsDiscoveryClient extends BaseApiClient {
|
|
|
43
43
|
|
|
44
44
|
/**
|
|
45
45
|
* Summarize explore access for tag-filtered explores
|
|
46
|
-
* (POST …/explore-access-summary).
|
|
46
|
+
* (POST …/explore-access-summary). Project-scoped; no agent path segment.
|
|
47
47
|
*/
|
|
48
|
+
getExploreAccessSummary(
|
|
49
|
+
projectUuid: string,
|
|
50
|
+
body?: ExploreAccessSummaryBody,
|
|
51
|
+
): Promise<AiAgentExploreAccessSummary[]>;
|
|
52
|
+
/**
|
|
53
|
+
* @deprecated `agentUuid` is ignored; the endpoint is project-scoped.
|
|
54
|
+
* Prefer `getExploreAccessSummary(projectUuid, body?)`.
|
|
55
|
+
*/
|
|
56
|
+
getExploreAccessSummary(
|
|
57
|
+
projectUuid: string,
|
|
58
|
+
agentUuid: string,
|
|
59
|
+
body?: ExploreAccessSummaryBody,
|
|
60
|
+
): Promise<AiAgentExploreAccessSummary[]>;
|
|
48
61
|
async getExploreAccessSummary(
|
|
49
62
|
projectUuid: string,
|
|
50
|
-
|
|
63
|
+
agentUuidOrBody?: ExploreAccessSummaryBody | string,
|
|
51
64
|
body?: ExploreAccessSummaryBody,
|
|
52
65
|
): Promise<AiAgentExploreAccessSummary[]> {
|
|
66
|
+
const resolvedBody = typeof agentUuidOrBody === 'string' ? body : agentUuidOrBody;
|
|
53
67
|
return this.http.post<AiAgentExploreAccessSummary[]>(
|
|
54
68
|
`/projects/${projectUuid}/aiAgents/explore-access-summary`,
|
|
55
|
-
|
|
69
|
+
resolvedBody ?? { tags: null },
|
|
56
70
|
);
|
|
57
71
|
}
|
|
58
72
|
|
|
@@ -150,12 +150,28 @@ export class AiAgentsClient extends BaseApiClient {
|
|
|
150
150
|
return this.discovery.evaluateAgentReadiness(projectUuid, agentUuid);
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
getExploreAccessSummary(
|
|
154
|
+
projectUuid: string,
|
|
155
|
+
body?: ExploreAccessSummaryBody,
|
|
156
|
+
): Promise<AiAgentExploreAccessSummary[]>;
|
|
157
|
+
/**
|
|
158
|
+
* @deprecated `agentUuid` is ignored; the endpoint is project-scoped.
|
|
159
|
+
* Prefer `getExploreAccessSummary(projectUuid, body?)`.
|
|
160
|
+
*/
|
|
153
161
|
getExploreAccessSummary(
|
|
154
162
|
projectUuid: string,
|
|
155
163
|
agentUuid: string,
|
|
156
164
|
body?: ExploreAccessSummaryBody,
|
|
165
|
+
): Promise<AiAgentExploreAccessSummary[]>;
|
|
166
|
+
getExploreAccessSummary(
|
|
167
|
+
projectUuid: string,
|
|
168
|
+
agentUuidOrBody?: ExploreAccessSummaryBody | string,
|
|
169
|
+
body?: ExploreAccessSummaryBody,
|
|
157
170
|
): Promise<AiAgentExploreAccessSummary[]> {
|
|
158
|
-
|
|
171
|
+
if (typeof agentUuidOrBody === 'string') {
|
|
172
|
+
return this.discovery.getExploreAccessSummary(projectUuid, agentUuidOrBody, body);
|
|
173
|
+
}
|
|
174
|
+
return this.discovery.getExploreAccessSummary(projectUuid, agentUuidOrBody);
|
|
159
175
|
}
|
|
160
176
|
|
|
161
177
|
getUserAgentPreferences(projectUuid: string): Promise<AiAgentUserPreferences | null> {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { BinarySizeLimitError } from '../../errors.js';
|
|
4
|
+
|
|
5
|
+
import { ChartsClient } from './charts.js';
|
|
4
6
|
|
|
5
7
|
import type { HttpClient } from '../../http/http-client';
|
|
6
8
|
|
|
@@ -14,6 +16,7 @@ describe('ChartsClient', () => {
|
|
|
14
16
|
put: vi.fn(),
|
|
15
17
|
patch: vi.fn(),
|
|
16
18
|
delete: vi.fn(),
|
|
19
|
+
getBytes: vi.fn(),
|
|
17
20
|
} as unknown as HttpClient;
|
|
18
21
|
});
|
|
19
22
|
|
|
@@ -120,4 +123,43 @@ describe('ChartsClient', () => {
|
|
|
120
123
|
expect(mockHttp.get).toHaveBeenCalledWith('/saved/c1/version/v1');
|
|
121
124
|
expect(result).toEqual(version);
|
|
122
125
|
});
|
|
126
|
+
|
|
127
|
+
it('exportChartImage should POST /saved/{chartUuid}/export and return URL', async () => {
|
|
128
|
+
const client = new ChartsClient(mockHttp);
|
|
129
|
+
vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
|
|
130
|
+
const result = await client.exportChartImage('c1', 'p1');
|
|
131
|
+
expect(mockHttp.post).toHaveBeenCalledWith('/saved/c1/export', undefined, {
|
|
132
|
+
params: { projectUuid: 'p1' },
|
|
133
|
+
timeout: 120_000,
|
|
134
|
+
});
|
|
135
|
+
expect(result).toBe('https://cdn.example/chart.png');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('exportChartImagePng should export then download bytes', async () => {
|
|
139
|
+
const client = new ChartsClient(mockHttp);
|
|
140
|
+
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
|
|
141
|
+
vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
|
|
142
|
+
vi.mocked(mockHttp.getBytes).mockResolvedValue({ bytes: png, mimeType: 'image/png' });
|
|
143
|
+
const result = await client.exportChartImagePng('c1');
|
|
144
|
+
expect(mockHttp.getBytes).toHaveBeenCalledWith('https://cdn.example/chart.png', {
|
|
145
|
+
maxBytes: 8 * 1024 * 1024,
|
|
146
|
+
timeout: 120_000,
|
|
147
|
+
});
|
|
148
|
+
expect(result).toEqual({
|
|
149
|
+
imageUrl: 'https://cdn.example/chart.png',
|
|
150
|
+
bytes: png,
|
|
151
|
+
mimeType: 'image/png',
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it('exportChartImagePng maps BinarySizeLimitError to ChartImageSizeError', async () => {
|
|
156
|
+
const client = new ChartsClient(mockHttp);
|
|
157
|
+
vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
|
|
158
|
+
vi.mocked(mockHttp.getBytes).mockRejectedValue(new BinarySizeLimitError(8 * 1024 * 1024));
|
|
159
|
+
|
|
160
|
+
await expect(client.exportChartImagePng('c1')).rejects.toMatchObject({
|
|
161
|
+
code: 'IMAGE_TOO_LARGE',
|
|
162
|
+
maxBytes: 8 * 1024 * 1024,
|
|
163
|
+
});
|
|
164
|
+
});
|
|
123
165
|
});
|
package/src/api/v1/charts.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Charts API client. Endpoints for saved charts and chart-as-code operations.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
+
import { BinarySizeLimitError, ChartImageSizeError } from '../../errors';
|
|
6
|
+
import { DEFAULT_BINARY_MAX_BYTES } from '../../http/http-client';
|
|
5
7
|
import { BaseApiClient } from '../base-client';
|
|
6
8
|
|
|
7
9
|
import type {
|
|
@@ -24,6 +26,18 @@ export type ChartHistoryResults = components['schemas']['ApiGetChartHistoryRespo
|
|
|
24
26
|
/** Results of GET saved/{chartUuid}/version/{versionUuid} (a single chart version). */
|
|
25
27
|
export type ChartVersionResults = components['schemas']['ApiGetChartVersionResponse']['results'];
|
|
26
28
|
|
|
29
|
+
/** Headless chart PNG export can take longer than the default HTTP timeout. */
|
|
30
|
+
export const CHART_IMAGE_EXPORT_TIMEOUT_MS = 120_000;
|
|
31
|
+
|
|
32
|
+
/** Hard cap on downloaded PNG size (8 MiB). */
|
|
33
|
+
export const CHART_IMAGE_MAX_BYTES = DEFAULT_BINARY_MAX_BYTES;
|
|
34
|
+
|
|
35
|
+
export type ChartImagePng = {
|
|
36
|
+
imageUrl: string;
|
|
37
|
+
bytes: Buffer;
|
|
38
|
+
mimeType: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
27
41
|
export class ChartsClient extends BaseApiClient {
|
|
28
42
|
/**
|
|
29
43
|
* List charts in a project (returns SpaceQuery array).
|
|
@@ -69,4 +83,41 @@ export class ChartsClient extends BaseApiClient {
|
|
|
69
83
|
async getChartVersion(chartUuid: string, versionUuid: string): Promise<ChartVersionResults> {
|
|
70
84
|
return this.http.get<ChartVersionResults>(`/saved/${chartUuid}/version/${versionUuid}`);
|
|
71
85
|
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Export a saved chart as a PNG via headless render.
|
|
89
|
+
* @returns Image URL string from `ApiExportChartImageResponse.results`.
|
|
90
|
+
*/
|
|
91
|
+
async exportChartImage(chartUuid: string, projectUuid?: string): Promise<string> {
|
|
92
|
+
return this.http.post<string>(`/saved/${encodeURIComponent(chartUuid)}/export`, undefined, {
|
|
93
|
+
params: projectUuid ? { projectUuid } : undefined,
|
|
94
|
+
timeout: CHART_IMAGE_EXPORT_TIMEOUT_MS,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Export a saved chart PNG and download the image bytes.
|
|
100
|
+
* Requires Lightdash headless browser support on the instance.
|
|
101
|
+
*/
|
|
102
|
+
async exportChartImagePng(chartUuid: string, projectUuid?: string): Promise<ChartImagePng> {
|
|
103
|
+
const imageUrl = await this.exportChartImage(chartUuid, projectUuid);
|
|
104
|
+
let bytes: Buffer;
|
|
105
|
+
let mimeType: string;
|
|
106
|
+
try {
|
|
107
|
+
({ bytes, mimeType } = await this.http.getBytes(imageUrl, {
|
|
108
|
+
maxBytes: CHART_IMAGE_MAX_BYTES,
|
|
109
|
+
timeout: CHART_IMAGE_EXPORT_TIMEOUT_MS,
|
|
110
|
+
}));
|
|
111
|
+
} catch (err) {
|
|
112
|
+
if (err instanceof BinarySizeLimitError) {
|
|
113
|
+
throw new ChartImageSizeError(err.maxBytes, err.byteLength);
|
|
114
|
+
}
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
imageUrl,
|
|
119
|
+
bytes,
|
|
120
|
+
mimeType: mimeType === 'application/octet-stream' ? 'image/png' : mimeType,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
72
123
|
}
|
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
|
+
});
|