@lightdash-tools/cli 0.6.0 → 0.8.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/README.md +8 -4
- package/dist/commands/agentops/apply.d.ts +5 -0
- package/dist/commands/agentops/apply.js +53 -0
- package/dist/commands/agentops/bundle-schema.d.ts +5 -0
- package/dist/commands/agentops/bundle-schema.js +16 -0
- package/dist/commands/agentops/drift.d.ts +5 -0
- package/dist/commands/agentops/drift.js +46 -0
- package/dist/commands/agentops/evaluate-gate.d.ts +5 -0
- package/dist/commands/agentops/evaluate-gate.js +89 -0
- package/dist/commands/agentops/gate-schema.d.ts +5 -0
- package/dist/commands/agentops/gate-schema.js +16 -0
- package/dist/commands/agentops/plan.d.ts +5 -0
- package/dist/commands/agentops/plan.js +42 -0
- package/dist/commands/agentops/state.d.ts +4 -0
- package/dist/commands/agentops/state.js +8 -0
- package/dist/commands/agentops.d.ts +8 -0
- package/dist/commands/agentops.js +26 -0
- package/dist/commands/agentops.test.d.ts +1 -0
- package/dist/commands/agentops.test.js +400 -0
- package/dist/commands/agents-crud.d.ts +8 -0
- package/dist/commands/agents-crud.js +144 -0
- package/dist/commands/agents-discovery.d.ts +8 -0
- package/dist/commands/agents-discovery.js +139 -0
- package/dist/commands/agents-discovery.test.d.ts +1 -0
- package/dist/commands/agents-discovery.test.js +13 -0
- package/dist/commands/agents-evals.d.ts +8 -0
- package/dist/commands/agents-evals.js +246 -0
- package/dist/commands/agents-threads.d.ts +8 -0
- package/dist/commands/agents-threads.js +83 -0
- package/dist/commands/agents.js +8 -360
- package/dist/commands/ai-agents.js +52 -70
- package/dist/commands/charts.js +35 -46
- package/dist/commands/content.js +3 -12
- package/dist/commands/dashboards.js +3 -12
- package/dist/commands/explores.js +12 -21
- package/dist/commands/groups.js +44 -63
- package/dist/commands/metrics.js +6 -15
- package/dist/commands/organization-roles.js +28 -39
- package/dist/commands/organization.js +3 -12
- package/dist/commands/project-access.js +9 -18
- package/dist/commands/project-role-assignments.js +15 -24
- package/dist/commands/projects.js +33 -26
- package/dist/commands/query.js +30 -41
- package/dist/commands/schedulers.js +6 -15
- package/dist/commands/schema.d.ts +1 -2
- package/dist/commands/schema.js +24 -97
- package/dist/commands/schema.test.js +80 -15
- package/dist/commands/space-access.js +12 -21
- package/dist/commands/spaces.js +6 -15
- package/dist/commands/tags.js +6 -15
- package/dist/commands/users.js +23 -41
- package/dist/index.js +18 -16
- package/dist/index.test.js +9 -9
- package/dist/utils/cli-params.d.ts +4 -0
- package/dist/utils/cli-params.js +15 -0
- package/dist/utils/cli-params.test.d.ts +1 -0
- package/dist/utils/cli-params.test.js +12 -0
- package/dist/utils/file-input.d.ts +30 -0
- package/dist/utils/file-input.js +77 -0
- package/dist/utils/file-input.test.d.ts +1 -0
- package/dist/utils/file-input.test.js +68 -0
- package/dist/utils/safety.d.ts +5 -0
- package/dist/utils/safety.js +97 -109
- package/dist/utils/safety.test.js +135 -33
- package/package.json +14 -5
- package/src/commands/agentops/apply.ts +77 -0
- package/src/commands/agentops/bundle-schema.ts +20 -0
- package/src/commands/agentops/drift.ts +63 -0
- package/src/commands/agentops/evaluate-gate.ts +128 -0
- package/src/commands/agentops/gate-schema.ts +20 -0
- package/src/commands/agentops/plan.ts +55 -0
- package/src/commands/agentops/state.ts +5 -0
- package/src/commands/agentops.test.ts +454 -0
- package/src/commands/agentops.ts +28 -0
- package/src/commands/agents-crud.ts +193 -0
- package/src/commands/agents-discovery.test.ts +16 -0
- package/src/commands/agents-discovery.ts +180 -0
- package/src/commands/agents-evals.ts +353 -0
- package/src/commands/agents-threads.ts +116 -0
- package/src/commands/agents.ts +9 -493
- package/src/commands/ai-agents.ts +37 -28
- package/src/commands/charts.ts +6 -3
- package/src/commands/content.ts +3 -1
- package/src/commands/dashboards.ts +3 -1
- package/src/commands/explores.ts +3 -1
- package/src/commands/groups.ts +33 -33
- package/src/commands/metrics.ts +3 -1
- package/src/commands/organization-roles.ts +3 -1
- package/src/commands/organization.ts +3 -1
- package/src/commands/project-access.ts +3 -1
- package/src/commands/project-role-assignments.ts +3 -1
- package/src/commands/projects.ts +44 -18
- package/src/commands/query.ts +4 -1
- package/src/commands/schedulers.ts +3 -1
- package/src/commands/schema.test.ts +95 -16
- package/src/commands/schema.ts +42 -99
- package/src/commands/space-access.ts +3 -1
- package/src/commands/spaces.ts +3 -1
- package/src/commands/tags.ts +3 -1
- package/src/commands/users.ts +29 -25
- package/src/index.test.ts +10 -9
- package/src/index.ts +19 -16
- package/src/utils/cli-params.test.ts +13 -0
- package/src/utils/cli-params.ts +12 -0
- package/src/utils/client.test.ts +1 -0
- package/src/utils/file-input.test.ts +91 -0
- package/src/utils/file-input.ts +83 -0
- package/src/utils/safety.test.ts +158 -2
- package/src/utils/safety.ts +27 -20
- package/tsconfig.json +2 -1
package/src/commands/users.ts
CHANGED
|
@@ -2,11 +2,37 @@
|
|
|
2
2
|
* Users command implementation.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import type { Command } from 'commander';
|
|
6
5
|
import { READ_ONLY_DEFAULT } from '@lightdash-tools/common';
|
|
6
|
+
|
|
7
|
+
import { pickDefined } from '../utils/cli-params';
|
|
7
8
|
import { getClient } from '../utils/client';
|
|
8
9
|
import { wrapAction } from '../utils/safety';
|
|
9
10
|
|
|
11
|
+
import type { LightdashClient } from '@lightdash-tools/client';
|
|
12
|
+
import type { Command } from 'commander';
|
|
13
|
+
|
|
14
|
+
type ListUsersCliOptions = {
|
|
15
|
+
all?: boolean;
|
|
16
|
+
page?: number;
|
|
17
|
+
pageSize?: number;
|
|
18
|
+
search?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
async function listUsers(client: LightdashClient, options: ListUsersCliOptions): Promise<void> {
|
|
22
|
+
const searchQuery = options.search;
|
|
23
|
+
|
|
24
|
+
if (options.all) {
|
|
25
|
+
const list = await client.v1.users.listAllMembers(pickDefined({ searchQuery }));
|
|
26
|
+
console.log(JSON.stringify(list, null, 2));
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const result = await client.v1.users.listMembers(
|
|
31
|
+
pickDefined({ page: options.page, pageSize: options.pageSize, searchQuery }),
|
|
32
|
+
);
|
|
33
|
+
console.log(JSON.stringify(result, null, 2));
|
|
34
|
+
}
|
|
35
|
+
|
|
10
36
|
/**
|
|
11
37
|
* Registers the users command and its subcommands.
|
|
12
38
|
* Uses client.v1.users (typed client) per ADR-0010.
|
|
@@ -23,31 +49,9 @@ export function registerUsersCommand(program: Command): void {
|
|
|
23
49
|
.option('--search <query>', 'Search query')
|
|
24
50
|
.action(
|
|
25
51
|
wrapAction(READ_ONLY_DEFAULT, async function (this: Command) {
|
|
26
|
-
const options = this.opts() as
|
|
27
|
-
all?: boolean;
|
|
28
|
-
page?: number;
|
|
29
|
-
pageSize?: number;
|
|
30
|
-
search?: string;
|
|
31
|
-
};
|
|
52
|
+
const options = this.opts() as ListUsersCliOptions;
|
|
32
53
|
try {
|
|
33
|
-
|
|
34
|
-
if (options.all) {
|
|
35
|
-
const listParams: { searchQuery?: string } = {};
|
|
36
|
-
if (options.search != null) listParams.searchQuery = options.search;
|
|
37
|
-
const list = await client.v1.users.listAllMembers(
|
|
38
|
-
Object.keys(listParams).length > 0 ? listParams : undefined,
|
|
39
|
-
);
|
|
40
|
-
console.log(JSON.stringify(list, null, 2));
|
|
41
|
-
} else {
|
|
42
|
-
const params: { page?: number; pageSize?: number; searchQuery?: string } = {};
|
|
43
|
-
if (options.page != null) params.page = options.page;
|
|
44
|
-
if (options.pageSize != null) params.pageSize = options.pageSize;
|
|
45
|
-
if (options.search != null) params.searchQuery = options.search;
|
|
46
|
-
const result = await client.v1.users.listMembers(
|
|
47
|
-
Object.keys(params).length > 0 ? params : undefined,
|
|
48
|
-
);
|
|
49
|
-
console.log(JSON.stringify(result, null, 2));
|
|
50
|
-
}
|
|
54
|
+
await listUsers(getClient(), options);
|
|
51
55
|
} catch (error) {
|
|
52
56
|
console.error(
|
|
53
57
|
'Error listing users:',
|
package/src/index.test.ts
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import { describe, it, expect } from 'vitest';
|
|
2
1
|
import { Command } from 'commander';
|
|
2
|
+
import { describe, it, expect } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { registerAiAgentsCommand } from './commands/ai-agents';
|
|
5
|
+
import { registerChartsCommand } from './commands/charts';
|
|
6
|
+
import { registerDashboardsCommand } from './commands/dashboards';
|
|
7
|
+
import { registerExploresCommand } from './commands/explores';
|
|
8
|
+
import { registerGroupsCommand } from './commands/groups';
|
|
3
9
|
import { registerOrganizationCommand } from './commands/organization';
|
|
4
10
|
import { registerOrganizationRolesCommand } from './commands/organization-roles';
|
|
5
|
-
import { registerProjectsCommand } from './commands/projects';
|
|
6
|
-
import { registerProjectRoleAssignmentsCommand } from './commands/project-role-assignments';
|
|
7
11
|
import { registerProjectAccessCommand } from './commands/project-access';
|
|
8
|
-
import {
|
|
12
|
+
import { registerProjectRoleAssignmentsCommand } from './commands/project-role-assignments';
|
|
13
|
+
import { registerProjectsCommand } from './commands/projects';
|
|
9
14
|
import { registerSpaceAccessCommand } from './commands/space-access';
|
|
10
|
-
import {
|
|
11
|
-
import { registerDashboardsCommand } from './commands/dashboards';
|
|
12
|
-
import { registerAiAgentsCommand } from './commands/ai-agents';
|
|
13
|
-
import { registerGroupsCommand } from './commands/groups';
|
|
15
|
+
import { registerSpacesCommand } from './commands/spaces';
|
|
14
16
|
import { registerUsersCommand } from './commands/users';
|
|
15
|
-
import { registerExploresCommand } from './commands/explores';
|
|
16
17
|
|
|
17
18
|
describe('CLI Command Registration', () => {
|
|
18
19
|
it('should register organization command', () => {
|
package/src/index.ts
CHANGED
|
@@ -3,28 +3,30 @@
|
|
|
3
3
|
* Main entry point for Lightdash AI CLI.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { Command } from 'commander';
|
|
7
6
|
import { initAuditLog } from '@lightdash-tools/common';
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { registerSpacesCommand } from './commands/spaces';
|
|
14
|
-
import { registerSpaceAccessCommand } from './commands/space-access';
|
|
7
|
+
import { Command } from 'commander';
|
|
8
|
+
|
|
9
|
+
import { registerAgentopsCommand } from './commands/agentops';
|
|
10
|
+
import { registerAgentsCommand } from './commands/agents';
|
|
11
|
+
import { registerAiAgentsCommand } from './commands/ai-agents';
|
|
15
12
|
import { registerChartsCommand } from './commands/charts';
|
|
13
|
+
import { registerContentCommand } from './commands/content';
|
|
16
14
|
import { registerDashboardsCommand } from './commands/dashboards';
|
|
17
|
-
import { registerAiAgentsCommand } from './commands/ai-agents';
|
|
18
|
-
import { registerAgentsCommand } from './commands/agents';
|
|
19
|
-
import { registerGroupsCommand } from './commands/groups';
|
|
20
|
-
import { registerUsersCommand } from './commands/users';
|
|
21
|
-
import { registerQueryCommand } from './commands/query';
|
|
22
15
|
import { registerExploresCommand } from './commands/explores';
|
|
16
|
+
import { registerGroupsCommand } from './commands/groups';
|
|
23
17
|
import { registerMetricsCommand } from './commands/metrics';
|
|
18
|
+
import { registerOrganizationCommand } from './commands/organization';
|
|
19
|
+
import { registerOrganizationRolesCommand } from './commands/organization-roles';
|
|
20
|
+
import { registerProjectAccessCommand } from './commands/project-access';
|
|
21
|
+
import { registerProjectRoleAssignmentsCommand } from './commands/project-role-assignments';
|
|
22
|
+
import { registerProjectsCommand } from './commands/projects';
|
|
23
|
+
import { registerQueryCommand } from './commands/query';
|
|
24
24
|
import { registerSchedulersCommand } from './commands/schedulers';
|
|
25
|
-
import { registerTagsCommand } from './commands/tags';
|
|
26
|
-
import { registerContentCommand } from './commands/content';
|
|
27
25
|
import { registerSchemaCommand } from './commands/schema';
|
|
26
|
+
import { registerSpaceAccessCommand } from './commands/space-access';
|
|
27
|
+
import { registerSpacesCommand } from './commands/spaces';
|
|
28
|
+
import { registerTagsCommand } from './commands/tags';
|
|
29
|
+
import { registerUsersCommand } from './commands/users';
|
|
28
30
|
|
|
29
31
|
// Initialise audit log before any command runs (uses LIGHTDASH_TOOLS_AUDIT_LOG env var).
|
|
30
32
|
initAuditLog(process.env.LIGHTDASH_TOOLS_AUDIT_LOG);
|
|
@@ -34,7 +36,7 @@ const program = new Command();
|
|
|
34
36
|
program
|
|
35
37
|
.name('lightdash-ai')
|
|
36
38
|
.description('CLI for Lightdash AI')
|
|
37
|
-
.version('0.
|
|
39
|
+
.version('0.8.0')
|
|
38
40
|
.option(
|
|
39
41
|
'--safety-mode <mode>',
|
|
40
42
|
'Safety mode (read-only, write-idempotent, write-destructive)',
|
|
@@ -60,6 +62,7 @@ registerSpaceAccessCommand(program);
|
|
|
60
62
|
registerChartsCommand(program);
|
|
61
63
|
registerDashboardsCommand(program);
|
|
62
64
|
registerAiAgentsCommand(program);
|
|
65
|
+
registerAgentopsCommand(program);
|
|
63
66
|
registerAgentsCommand(program);
|
|
64
67
|
registerGroupsCommand(program);
|
|
65
68
|
registerUsersCommand(program);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { pickDefined } from './cli-params';
|
|
4
|
+
|
|
5
|
+
describe('pickDefined', () => {
|
|
6
|
+
it('returns undefined when all values are null or undefined', () => {
|
|
7
|
+
expect(pickDefined({ page: undefined, search: null })).toBeUndefined();
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('returns only defined entries', () => {
|
|
11
|
+
expect(pickDefined({ page: 1, search: undefined, name: 'x' })).toEqual({ page: 1, name: 'x' });
|
|
12
|
+
});
|
|
13
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build optional API params from CLI options, omitting null/undefined values.
|
|
3
|
+
*/
|
|
4
|
+
export function pickDefined<T extends Record<string, unknown>>(source: T): Partial<T> | undefined {
|
|
5
|
+
const params: Partial<T> = {};
|
|
6
|
+
for (const [key, value] of Object.entries(source)) {
|
|
7
|
+
if (value != null) {
|
|
8
|
+
params[key as keyof T] = value as T[keyof T];
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return Object.keys(params).length > 0 ? params : undefined;
|
|
12
|
+
}
|
package/src/utils/client.test.ts
CHANGED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
import { describe, expect, it, vi, afterEach } from 'vitest';
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
hasExplicitFileInput,
|
|
7
|
+
parseJsonOrYaml,
|
|
8
|
+
readExplicitFileOrStdin,
|
|
9
|
+
readFileOrStdin,
|
|
10
|
+
readParsedInput,
|
|
11
|
+
} from './file-input';
|
|
12
|
+
|
|
13
|
+
vi.mock('node:fs', () => ({
|
|
14
|
+
readFileSync: vi.fn(),
|
|
15
|
+
}));
|
|
16
|
+
|
|
17
|
+
describe('file-input', () => {
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
vi.mocked(readFileSync).mockReset();
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('parseJsonOrYaml', () => {
|
|
23
|
+
it('parses JSON objects', () => {
|
|
24
|
+
expect(parseJsonOrYaml('{"name":"agent"}')).toEqual({ name: 'agent' });
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('parses JSON arrays', () => {
|
|
28
|
+
expect(parseJsonOrYaml('[1,2]')).toEqual([1, 2]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('parses YAML objects', () => {
|
|
32
|
+
expect(parseJsonOrYaml('name: agent\ntags:\n - a')).toEqual({
|
|
33
|
+
name: 'agent',
|
|
34
|
+
tags: ['a'],
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('rejects empty input', () => {
|
|
39
|
+
expect(() => parseJsonOrYaml(' ')).toThrow('Input is empty');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('rejects invalid JSON', () => {
|
|
43
|
+
expect(() => parseJsonOrYaml('{not json')).toThrow();
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('hasExplicitFileInput', () => {
|
|
48
|
+
it('returns true only for --file or --stdin', () => {
|
|
49
|
+
expect(hasExplicitFileInput({ file: 'agent.json' })).toBe(true);
|
|
50
|
+
expect(hasExplicitFileInput({ stdin: true })).toBe(true);
|
|
51
|
+
expect(hasExplicitFileInput({})).toBe(false);
|
|
52
|
+
expect(hasExplicitFileInput({ stdin: false })).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('readFileOrStdin', () => {
|
|
57
|
+
it('reads from file path', async () => {
|
|
58
|
+
vi.mocked(readFileSync).mockReturnValue('{"x":1}');
|
|
59
|
+
const result = await readFileOrStdin({ file: 'agent.json' });
|
|
60
|
+
expect(result).toBe('{"x":1}');
|
|
61
|
+
expect(readFileSync).toHaveBeenCalledWith('agent.json', 'utf-8');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('readExplicitFileOrStdin', () => {
|
|
66
|
+
it('requires --file or --stdin', async () => {
|
|
67
|
+
await expect(readExplicitFileOrStdin({})).rejects.toThrow(
|
|
68
|
+
'No input provided. Use --file <path> or --stdin.',
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('reads from file when --file is set', async () => {
|
|
73
|
+
vi.mocked(readFileSync).mockReturnValue('content');
|
|
74
|
+
await expect(readExplicitFileOrStdin({ file: 'bundle.yaml' })).resolves.toBe('content');
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe('readParsedInput', () => {
|
|
79
|
+
it('reads and parses file content', async () => {
|
|
80
|
+
vi.mocked(readFileSync).mockReturnValue('name: test');
|
|
81
|
+
await expect(readParsedInput({ file: 'agent.yaml' })).resolves.toEqual({ name: 'test' });
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('wraps parse errors with context', async () => {
|
|
85
|
+
vi.mocked(readFileSync).mockReturnValue('{bad');
|
|
86
|
+
await expect(readParsedInput({ file: 'bad.json' })).rejects.toThrow(
|
|
87
|
+
'Failed to parse input as JSON or YAML',
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read and parse JSON or YAML from --file or stdin.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
|
|
7
|
+
import { parse as parseYaml } from 'yaml';
|
|
8
|
+
|
|
9
|
+
export type FileInputOptions = {
|
|
10
|
+
file?: string;
|
|
11
|
+
stdin?: boolean;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* True when the caller explicitly requested file or stdin input (--file / --stdin).
|
|
16
|
+
* Unlike {@link readFileOrStdin}, does not treat a non-TTY stdin as implicit input,
|
|
17
|
+
* so flag-only commands work in CI where stdin is closed.
|
|
18
|
+
*/
|
|
19
|
+
export function hasExplicitFileInput(options: FileInputOptions): boolean {
|
|
20
|
+
return options.file != null || options.stdin === true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Reads YAML/JSON only when --file or --stdin was explicitly requested.
|
|
25
|
+
* Use for commands that also support flag-based bodies in non-TTY environments.
|
|
26
|
+
*/
|
|
27
|
+
export async function readExplicitFileOrStdin(options: FileInputOptions): Promise<string> {
|
|
28
|
+
if (!hasExplicitFileInput(options)) {
|
|
29
|
+
throw new Error('No input provided. Use --file <path> or --stdin.');
|
|
30
|
+
}
|
|
31
|
+
return readFileOrStdin(options);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Reads raw text from a file path or stdin (when --stdin is set or stdin is piped).
|
|
36
|
+
*/
|
|
37
|
+
export async function readFileOrStdin(options: FileInputOptions): Promise<string> {
|
|
38
|
+
if (options.file) {
|
|
39
|
+
return readFileSync(options.file, 'utf-8');
|
|
40
|
+
}
|
|
41
|
+
if (options.stdin === true || !process.stdin.isTTY) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const chunks: Buffer[] = [];
|
|
44
|
+
process.stdin.setEncoding('utf8');
|
|
45
|
+
process.stdin.on('data', (chunk) => {
|
|
46
|
+
chunks.push(Buffer.from(chunk));
|
|
47
|
+
});
|
|
48
|
+
process.stdin.on('end', () => {
|
|
49
|
+
resolve(Buffer.concat(chunks).toString('utf-8'));
|
|
50
|
+
});
|
|
51
|
+
process.stdin.on('error', reject);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
throw new Error('No input provided. Use --file <path> or --stdin to read from stdin.');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Parses a string as JSON (object/array) or YAML.
|
|
59
|
+
*/
|
|
60
|
+
export function parseJsonOrYaml(content: string): unknown {
|
|
61
|
+
const trimmed = content.trim();
|
|
62
|
+
if (trimmed.length === 0) {
|
|
63
|
+
throw new Error('Input is empty');
|
|
64
|
+
}
|
|
65
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
66
|
+
return JSON.parse(trimmed) as unknown;
|
|
67
|
+
}
|
|
68
|
+
return parseYaml(content) as unknown;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Reads from file or stdin and parses as JSON or YAML.
|
|
73
|
+
*/
|
|
74
|
+
export async function readParsedInput(options: FileInputOptions): Promise<unknown> {
|
|
75
|
+
const content = await readFileOrStdin(options);
|
|
76
|
+
try {
|
|
77
|
+
return parseJsonOrYaml(content);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`Failed to parse input as JSON or YAML: ${error instanceof Error ? error.message : String(error)}`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
}
|
package/src/utils/safety.test.ts
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
-
import { wrapAction } from './safety';
|
|
3
1
|
import {
|
|
4
2
|
READ_ONLY_DEFAULT,
|
|
5
3
|
WRITE_DESTRUCTIVE,
|
|
@@ -7,6 +5,104 @@ import {
|
|
|
7
5
|
SafetyMode,
|
|
8
6
|
} from '@lightdash-tools/common';
|
|
9
7
|
import { Command } from 'commander';
|
|
8
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
assertAllowedProject,
|
|
12
|
+
getAllowedProjects,
|
|
13
|
+
getSafetyMode,
|
|
14
|
+
isDryRun,
|
|
15
|
+
wrapAction,
|
|
16
|
+
} from './safety';
|
|
17
|
+
|
|
18
|
+
const UUID_ALLOWED = '11111111-1111-1111-1111-111111111111';
|
|
19
|
+
const UUID_FORBIDDEN = '22222222-2222-2222-2222-222222222222';
|
|
20
|
+
|
|
21
|
+
/** Builds a root + subcommand hierarchy like the real CLI program. */
|
|
22
|
+
function buildCommandHierarchy(): { root: Command; child: Command } {
|
|
23
|
+
const root = new Command('lightdash-ai');
|
|
24
|
+
root
|
|
25
|
+
.option('--safety-mode <mode>', 'Safety mode')
|
|
26
|
+
.option('--projects <uuids>', 'Allowed project UUIDs')
|
|
27
|
+
.option('--dry-run', 'Simulate mutating operations');
|
|
28
|
+
const child = new Command('charts');
|
|
29
|
+
root.addCommand(child);
|
|
30
|
+
return { root, child };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('getSafetyMode', () => {
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
delete process.env.LIGHTDASH_TOOLS_SAFETY_MODE;
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('reads safety mode from cmd option via optsWithGlobals', () => {
|
|
39
|
+
const { child } = buildCommandHierarchy();
|
|
40
|
+
child.setOptionValueWithSource('safetyMode', SafetyMode.WRITE_DESTRUCTIVE, 'cli');
|
|
41
|
+
|
|
42
|
+
expect(getSafetyMode(child)).toBe(SafetyMode.WRITE_DESTRUCTIVE);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('isDryRun', () => {
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
delete process.env.LIGHTDASH_TOOLS_DRY_RUN;
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
afterEach(() => {
|
|
52
|
+
delete process.env.LIGHTDASH_TOOLS_DRY_RUN;
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('reads dry-run from root --dry-run flag', () => {
|
|
56
|
+
const { root, child } = buildCommandHierarchy();
|
|
57
|
+
root.setOptionValueWithSource('dryRun', true, 'cli');
|
|
58
|
+
|
|
59
|
+
expect(isDryRun(child)).toBe(true);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('getAllowedProjects', () => {
|
|
64
|
+
it('reads comma-separated projects from root --projects flag', () => {
|
|
65
|
+
const { root, child } = buildCommandHierarchy();
|
|
66
|
+
root.setOptionValueWithSource('projects', `${UUID_ALLOWED}, ${UUID_FORBIDDEN}`, 'cli');
|
|
67
|
+
|
|
68
|
+
expect(getAllowedProjects(child)).toEqual([UUID_ALLOWED, UUID_FORBIDDEN]);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe('assertAllowedProject', () => {
|
|
73
|
+
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
74
|
+
const processExitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
|
|
75
|
+
throw new Error('exit');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
afterEach(() => {
|
|
79
|
+
vi.clearAllMocks();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('allows project when no allowlist is configured', () => {
|
|
83
|
+
const { child } = buildCommandHierarchy();
|
|
84
|
+
expect(() => assertAllowedProject(child, UUID_FORBIDDEN)).not.toThrow();
|
|
85
|
+
expect(processExitSpy).not.toHaveBeenCalled();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('allows project when it is in the allowlist', () => {
|
|
89
|
+
const { root, child } = buildCommandHierarchy();
|
|
90
|
+
root.setOptionValueWithSource('projects', UUID_ALLOWED, 'cli');
|
|
91
|
+
expect(() => assertAllowedProject(child, UUID_ALLOWED)).not.toThrow();
|
|
92
|
+
expect(processExitSpy).not.toHaveBeenCalled();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('blocks project parsed from bundle when not in allowlist', () => {
|
|
96
|
+
const { root, child } = buildCommandHierarchy();
|
|
97
|
+
root.setOptionValueWithSource('projects', UUID_ALLOWED, 'cli');
|
|
98
|
+
|
|
99
|
+
expect(() => assertAllowedProject(child, UUID_FORBIDDEN)).toThrow('exit');
|
|
100
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
|
101
|
+
expect.stringContaining('not in the list of allowed projects'),
|
|
102
|
+
);
|
|
103
|
+
expect(processExitSpy).toHaveBeenCalledWith(1);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
10
106
|
|
|
11
107
|
describe('CLI wrapAction', () => {
|
|
12
108
|
const mockAction = vi.fn().mockResolvedValue(undefined);
|
|
@@ -117,4 +213,64 @@ describe('CLI wrapAction', () => {
|
|
|
117
213
|
expect(mockAction).toHaveBeenCalledWith('arg1');
|
|
118
214
|
expect(consoleLogSpy).not.toHaveBeenCalledWith(expect.stringContaining('[DRY-RUN]'));
|
|
119
215
|
});
|
|
216
|
+
|
|
217
|
+
it('should simulate write command when root --dry-run flag is set', async () => {
|
|
218
|
+
const { root, child } = buildCommandHierarchy();
|
|
219
|
+
child.setOptionValueWithSource('safetyMode', SafetyMode.WRITE_IDEMPOTENT, 'cli');
|
|
220
|
+
root.setOptionValueWithSource('dryRun', true, 'cli');
|
|
221
|
+
|
|
222
|
+
const wrapped = wrapAction(WRITE_IDEMPOTENT, mockAction);
|
|
223
|
+
await wrapped.call(child, UUID_ALLOWED);
|
|
224
|
+
|
|
225
|
+
expect(mockAction).not.toHaveBeenCalled();
|
|
226
|
+
expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringContaining('[DRY-RUN] Would execute'));
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it('should block when project is not in root --projects list', async () => {
|
|
230
|
+
const { root, child } = buildCommandHierarchy();
|
|
231
|
+
child.setOptionValueWithSource('safetyMode', SafetyMode.WRITE_DESTRUCTIVE, 'cli');
|
|
232
|
+
root.setOptionValueWithSource('projects', UUID_ALLOWED, 'cli');
|
|
233
|
+
|
|
234
|
+
const wrapped = wrapAction(WRITE_IDEMPOTENT, mockAction);
|
|
235
|
+
|
|
236
|
+
await expect(wrapped.call(child, UUID_FORBIDDEN)).rejects.toThrow('exit');
|
|
237
|
+
|
|
238
|
+
expect(mockAction).not.toHaveBeenCalled();
|
|
239
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
|
240
|
+
expect.stringContaining('not in the list of allowed projects'),
|
|
241
|
+
);
|
|
242
|
+
expect(processExitSpy).toHaveBeenCalledWith(1);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('should enforce allowlist from command opts when project is only in --project', async () => {
|
|
246
|
+
const { root, child } = buildCommandHierarchy();
|
|
247
|
+
child
|
|
248
|
+
.option('--project <uuid>', 'Project UUID')
|
|
249
|
+
.setOptionValueWithSource('safetyMode', SafetyMode.WRITE_DESTRUCTIVE, 'cli');
|
|
250
|
+
root.setOptionValueWithSource('projects', UUID_ALLOWED, 'cli');
|
|
251
|
+
child.setOptionValueWithSource('project', UUID_FORBIDDEN, 'cli');
|
|
252
|
+
|
|
253
|
+
const wrapped = wrapAction(WRITE_IDEMPOTENT, mockAction);
|
|
254
|
+
|
|
255
|
+
await expect(wrapped.call(child)).rejects.toThrow('exit');
|
|
256
|
+
|
|
257
|
+
expect(mockAction).not.toHaveBeenCalled();
|
|
258
|
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
|
259
|
+
expect.stringContaining('not in the list of allowed projects'),
|
|
260
|
+
);
|
|
261
|
+
expect(processExitSpy).toHaveBeenCalledWith(1);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('should re-throw when the action throws', async () => {
|
|
265
|
+
const failingAction = vi.fn().mockRejectedValue(new Error('action failed'));
|
|
266
|
+
const cmd = new Command();
|
|
267
|
+
cmd.setOptionValueWithSource('safetyMode', SafetyMode.READ_ONLY, 'cli');
|
|
268
|
+
|
|
269
|
+
const wrapped = wrapAction(READ_ONLY_DEFAULT, failingAction);
|
|
270
|
+
|
|
271
|
+
await expect(wrapped.call(cmd, 'arg1')).rejects.toThrow('action failed');
|
|
272
|
+
|
|
273
|
+
expect(failingAction).toHaveBeenCalledWith('arg1');
|
|
274
|
+
expect(processExitSpy).not.toHaveBeenCalled();
|
|
275
|
+
});
|
|
120
276
|
});
|
package/src/utils/safety.ts
CHANGED
|
@@ -8,7 +8,9 @@ import {
|
|
|
8
8
|
getAllowedProjectUuidsFromEnv,
|
|
9
9
|
extractProjectUuids,
|
|
10
10
|
validateResourceId,
|
|
11
|
+
validateResourceIdsInObject,
|
|
11
12
|
} from '@lightdash-tools/common';
|
|
13
|
+
|
|
12
14
|
import type { ToolAnnotations } from '@lightdash-tools/common';
|
|
13
15
|
import type { Command } from 'commander';
|
|
14
16
|
|
|
@@ -59,6 +61,21 @@ export function getAllowedProjects(cmd: Command): string[] {
|
|
|
59
61
|
return getAllowedProjectUuidsFromEnv();
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Enforces project allowlist for project UUIDs parsed from bundle/gate YAML.
|
|
66
|
+
* wrapAction only inspects CLI args, so bundle.spec.projectUuid must be checked separately.
|
|
67
|
+
*/
|
|
68
|
+
export function assertAllowedProject(cmd: Command, projectUuid: string): void {
|
|
69
|
+
validateResourceId(projectUuid);
|
|
70
|
+
const allowedProjects = getAllowedProjects(cmd);
|
|
71
|
+
if (allowedProjects.length > 0 && !areAllProjectsAllowed(allowedProjects, [projectUuid])) {
|
|
72
|
+
console.error(
|
|
73
|
+
`Error: Project [${projectUuid}] is not in the list of allowed projects. Allowed: [${allowedProjects.join(', ')}].`,
|
|
74
|
+
);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
62
79
|
/** Builds a human-readable command path (e.g. "lightdash-ai charts list"). */
|
|
63
80
|
function getCommandPath(cmd: Command): string {
|
|
64
81
|
const parts: string[] = [];
|
|
@@ -77,34 +94,24 @@ function getCommandPath(cmd: Command): string {
|
|
|
77
94
|
export function wrapAction<T extends unknown[]>(
|
|
78
95
|
annotations: ToolAnnotations,
|
|
79
96
|
action: (...args: T) => Promise<void> | void,
|
|
80
|
-
) {
|
|
81
|
-
return async function (this: Command, ...args: T) {
|
|
97
|
+
): (this: Command, ...args: T) => Promise<void> {
|
|
98
|
+
return async function (this: Command, ...args: T): Promise<void> {
|
|
82
99
|
const start = Date.now();
|
|
83
100
|
const commandPath = getCommandPath(this);
|
|
84
101
|
const mode = getSafetyMode(this);
|
|
85
102
|
const allowedProjects = getAllowedProjects(this);
|
|
86
|
-
const targetProjects =
|
|
103
|
+
const targetProjects = [
|
|
104
|
+
...new Set([...extractProjectUuids(args), ...extractProjectUuids(this.opts())]),
|
|
105
|
+
];
|
|
87
106
|
|
|
88
107
|
// ── Input Validation ─────────────────────────────────────────────────────
|
|
89
|
-
// Validate only known identifier fields (
|
|
108
|
+
// Validate only known identifier fields (RESOURCE_ID_KEYS) in objects.
|
|
90
109
|
// Do NOT validate bare positional strings—they may be free-form (query, name, etc.).
|
|
91
|
-
function validateStringArgs(values: unknown[]): void {
|
|
92
|
-
for (const v of values) {
|
|
93
|
-
if (Array.isArray(v)) {
|
|
94
|
-
validateStringArgs(v);
|
|
95
|
-
} else if (v && typeof v === 'object') {
|
|
96
|
-
const o = v as Record<string, unknown>;
|
|
97
|
-
for (const key of ['project', 'projectUuid', 'projectUuids', 'projects', 'slug']) {
|
|
98
|
-
const val = o[key];
|
|
99
|
-
if (typeof val === 'string') validateResourceId(val);
|
|
100
|
-
else if (Array.isArray(val))
|
|
101
|
-
for (const item of val) if (typeof item === 'string') validateResourceId(item);
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
110
|
try {
|
|
107
|
-
|
|
111
|
+
for (const arg of args as unknown[]) {
|
|
112
|
+
validateResourceIdsInObject(arg);
|
|
113
|
+
}
|
|
114
|
+
validateResourceIdsInObject(this.opts());
|
|
108
115
|
} catch (err) {
|
|
109
116
|
logAuditEntry({
|
|
110
117
|
timestamp: new Date().toISOString(),
|
package/tsconfig.json
CHANGED