@diafunc/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4047 @@
1
+ // src/index.ts
2
+ import { Command } from "commander";
3
+
4
+ // src/commands/auth/login.ts
5
+ import chalk2 from "chalk";
6
+
7
+ // src/config/store.ts
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import * as os from "os";
11
+ var CONFIG_DIR = path.join(os.homedir(), ".diafunc");
12
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
13
+ var DEFAULT_CONFIG = {
14
+ currentProfile: "default",
15
+ profiles: {
16
+ default: {
17
+ endpoint: "https://diafunc.com"
18
+ }
19
+ },
20
+ defaults: {}
21
+ };
22
+ function ensureConfigDir() {
23
+ if (!fs.existsSync(CONFIG_DIR)) {
24
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
25
+ }
26
+ }
27
+ function loadConfig() {
28
+ if (!fs.existsSync(CONFIG_FILE)) {
29
+ return structuredClone(DEFAULT_CONFIG);
30
+ }
31
+ const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
32
+ return JSON.parse(raw);
33
+ }
34
+ function saveConfig(config) {
35
+ ensureConfigDir();
36
+ const tmp = CONFIG_FILE + ".tmp";
37
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", {
38
+ encoding: "utf-8",
39
+ mode: 384
40
+ });
41
+ fs.renameSync(tmp, CONFIG_FILE);
42
+ }
43
+ function resolveEndpoint(config, profileOverride) {
44
+ const name = profileOverride ?? config.currentProfile;
45
+ const profile = config.profiles[name];
46
+ if (!profile) {
47
+ throw new Error(`Profile "${name}" not found.`);
48
+ }
49
+ return profile.endpoint.replace(/\/+$/, "");
50
+ }
51
+
52
+ // src/client/errors.ts
53
+ var ApiError = class _ApiError extends Error {
54
+ status;
55
+ details;
56
+ constructor(status, message, details) {
57
+ super(message);
58
+ this.name = "ApiError";
59
+ this.status = status;
60
+ this.details = details;
61
+ }
62
+ static fromBody(status, body) {
63
+ return new _ApiError(status, body.message, body.details);
64
+ }
65
+ toUserMessage() {
66
+ switch (this.status) {
67
+ case 401:
68
+ return `Authentication failed. Run 'diafunc auth login' to configure your credentials.`;
69
+ case 403:
70
+ return `Permission denied. Your token may not have the required scope.${this.details ? ` (${this.details})` : ""}`;
71
+ case 404:
72
+ return `Not found: ${this.message}`;
73
+ case 409:
74
+ return `Conflict: ${this.message}`;
75
+ case 429:
76
+ return `Rate limited. Please wait before retrying.`;
77
+ default:
78
+ return this.details ? `${this.message} (${this.details})` : this.message;
79
+ }
80
+ }
81
+ };
82
+ var NetworkError = class extends Error {
83
+ constructor(message, cause) {
84
+ super(message);
85
+ this.name = "NetworkError";
86
+ this.cause = cause;
87
+ }
88
+ };
89
+
90
+ // src/client/http.ts
91
+ function buildUrl(endpoint, service, path5, query) {
92
+ const base = `${endpoint}/api/v1/${service}${path5}`;
93
+ const params = new URLSearchParams();
94
+ if (query) {
95
+ for (const [key, value] of Object.entries(query)) {
96
+ if (value !== void 0) {
97
+ params.set(key, String(value));
98
+ }
99
+ }
100
+ }
101
+ const qs = params.toString();
102
+ return qs ? `${base}?${qs}` : base;
103
+ }
104
+ function getAuthHeader(auth) {
105
+ if (!auth) return void 0;
106
+ if (auth.type === "api-token") {
107
+ return `Bearer ${auth.token}`;
108
+ }
109
+ if (auth.type === "session") {
110
+ return `Bearer ${auth.accessToken}`;
111
+ }
112
+ return void 0;
113
+ }
114
+ function isTokenExpired(auth) {
115
+ if (!auth || auth.type !== "session") return false;
116
+ return Date.now() >= auth.accessTokenExpiry - 3e4;
117
+ }
118
+ async function refreshSession(endpoint, refreshToken) {
119
+ const url = `${endpoint}/api/v1/admin/sessions/`;
120
+ const response = await fetch(url, {
121
+ method: "PUT",
122
+ headers: { "Content-Type": "text/plain" },
123
+ body: refreshToken
124
+ });
125
+ if (!response.ok) {
126
+ throw new ApiError(response.status, "Session refresh failed. Please log in again.");
127
+ }
128
+ const session = await response.json();
129
+ return {
130
+ accessToken: session.accessToken.raw,
131
+ accessTokenExpiry: session.accessToken.expiry
132
+ };
133
+ }
134
+ async function ensureValidAuth(config, profileOverride) {
135
+ const profileName = profileOverride ?? config.currentProfile;
136
+ const profile = config.profiles[profileName];
137
+ if (!profile?.auth) return void 0;
138
+ if (isTokenExpired(profile.auth)) {
139
+ const auth = profile.auth;
140
+ const endpoint = resolveEndpoint(config, profileOverride);
141
+ const refreshed = await refreshSession(endpoint, auth.refreshToken);
142
+ profile.auth = {
143
+ type: "session",
144
+ accessToken: refreshed.accessToken,
145
+ refreshToken: auth.refreshToken,
146
+ accessTokenExpiry: refreshed.accessTokenExpiry
147
+ };
148
+ saveConfig(config);
149
+ }
150
+ return profile.auth;
151
+ }
152
+ async function parseErrorBody(response) {
153
+ try {
154
+ const contentType = response.headers.get("content-type") ?? "";
155
+ if (contentType.includes("application/json")) {
156
+ const body = await response.json();
157
+ return ApiError.fromBody(response.status, body);
158
+ }
159
+ const text = await response.text();
160
+ return new ApiError(response.status, text || response.statusText);
161
+ } catch {
162
+ return new ApiError(response.status, response.statusText);
163
+ }
164
+ }
165
+ var _dryRun = false;
166
+ function setDryRun(enabled) {
167
+ _dryRun = enabled;
168
+ }
169
+ function createHttpClient(options = {}) {
170
+ const config = loadConfig();
171
+ const endpoint = resolveEndpoint(config, options.profileOverride);
172
+ async function doRequest(opts) {
173
+ if (_dryRun && opts.method !== "GET") {
174
+ const url2 = buildUrl(endpoint, opts.service, opts.path, opts.query);
175
+ const bodyPreview = opts.body ? JSON.stringify(opts.body, null, 2) : opts.rawBody ? "(binary)" : "(none)";
176
+ console.log(`[dry-run] ${opts.method} ${url2}`);
177
+ if (opts.body) {
178
+ console.log(`[dry-run] Body:
179
+ ${bodyPreview}`);
180
+ }
181
+ return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
182
+ }
183
+ const auth = await ensureValidAuth(config, options.profileOverride);
184
+ const url = buildUrl(endpoint, opts.service, opts.path, opts.query);
185
+ const headers = {
186
+ ...opts.headers
187
+ };
188
+ const authHeader = getAuthHeader(auth);
189
+ if (authHeader) {
190
+ headers["Authorization"] = authHeader;
191
+ }
192
+ let body;
193
+ if (opts.rawBody !== void 0) {
194
+ body = opts.rawBody;
195
+ if (opts.contentType) {
196
+ headers["Content-Type"] = opts.contentType;
197
+ }
198
+ } else if (opts.body !== void 0) {
199
+ headers["Content-Type"] = "application/json";
200
+ body = JSON.stringify(opts.body);
201
+ }
202
+ try {
203
+ return await fetch(url, {
204
+ method: opts.method,
205
+ headers,
206
+ body
207
+ });
208
+ } catch (err) {
209
+ throw new NetworkError(
210
+ `Failed to connect to ${endpoint}. Check your network and endpoint configuration.`,
211
+ err instanceof Error ? err : void 0
212
+ );
213
+ }
214
+ }
215
+ return {
216
+ async request(opts) {
217
+ const response = await doRequest(opts);
218
+ if (!response.ok) {
219
+ throw await parseErrorBody(response);
220
+ }
221
+ const contentType = response.headers.get("content-type") ?? "";
222
+ if (contentType.includes("application/json")) {
223
+ return await response.json();
224
+ }
225
+ return await response.text();
226
+ },
227
+ async requestRaw(opts) {
228
+ const response = await doRequest(opts);
229
+ if (!response.ok) {
230
+ throw await parseErrorBody(response);
231
+ }
232
+ return response;
233
+ }
234
+ };
235
+ }
236
+
237
+ // src/client/services/admin.ts
238
+ var SERVICE = "admin";
239
+ function createAdminService(client) {
240
+ return {
241
+ // Sessions
242
+ async createSession(credentials) {
243
+ return client.request({
244
+ method: "POST",
245
+ service: SERVICE,
246
+ path: "/sessions/",
247
+ body: credentials
248
+ });
249
+ },
250
+ async refreshSession(refreshToken) {
251
+ return client.request({
252
+ method: "PUT",
253
+ service: SERVICE,
254
+ path: "/sessions/",
255
+ rawBody: refreshToken,
256
+ contentType: "text/plain"
257
+ });
258
+ },
259
+ // Users
260
+ async getMyUser() {
261
+ return client.request({
262
+ method: "GET",
263
+ service: SERVICE,
264
+ path: "/myuser/"
265
+ });
266
+ },
267
+ async getUsers() {
268
+ return client.request({
269
+ method: "GET",
270
+ service: SERVICE,
271
+ path: "/users/"
272
+ });
273
+ },
274
+ async getUserName(userId) {
275
+ return client.request({
276
+ method: "GET",
277
+ service: SERVICE,
278
+ path: `/users/name/${encodeURIComponent(userId)}`
279
+ });
280
+ },
281
+ // Projects
282
+ async getProjects() {
283
+ return client.request({
284
+ method: "GET",
285
+ service: SERVICE,
286
+ path: "/projects/"
287
+ });
288
+ },
289
+ async getAllProjects() {
290
+ return client.request({
291
+ method: "GET",
292
+ service: SERVICE,
293
+ path: "/projects/all"
294
+ });
295
+ },
296
+ async getProject(projectId) {
297
+ return client.request({
298
+ method: "GET",
299
+ service: SERVICE,
300
+ path: `/projects/${encodeURIComponent(projectId)}`
301
+ });
302
+ },
303
+ async createProject(request) {
304
+ return client.request({
305
+ method: "POST",
306
+ service: SERVICE,
307
+ path: "/projects/",
308
+ body: request
309
+ });
310
+ },
311
+ async updateProject(project) {
312
+ return client.request({
313
+ method: "PUT",
314
+ service: SERVICE,
315
+ path: "/projects/",
316
+ body: project
317
+ });
318
+ },
319
+ async deleteProject(projectId) {
320
+ return client.request({
321
+ method: "DELETE",
322
+ service: SERVICE,
323
+ path: `/projects/${encodeURIComponent(projectId)}`
324
+ });
325
+ },
326
+ async lockProject(projectId) {
327
+ return client.request({
328
+ method: "PUT",
329
+ service: SERVICE,
330
+ path: `/projects/lock/${encodeURIComponent(projectId)}`
331
+ });
332
+ },
333
+ async unlockProject(projectId) {
334
+ return client.request({
335
+ method: "DELETE",
336
+ service: SERVICE,
337
+ path: `/projects/lock/${encodeURIComponent(projectId)}`
338
+ });
339
+ },
340
+ // Project Members
341
+ async getProjectMembers(projectId) {
342
+ return client.request({
343
+ method: "GET",
344
+ service: SERVICE,
345
+ path: `/projects/members/${encodeURIComponent(projectId)}`
346
+ });
347
+ },
348
+ async inviteProjectMember(projectId, userId, role) {
349
+ return client.request({
350
+ method: "POST",
351
+ service: SERVICE,
352
+ path: `/projects/members/invitations/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}/${encodeURIComponent(role)}`
353
+ });
354
+ },
355
+ async joinProject(projectId, userId) {
356
+ return client.request({
357
+ method: "POST",
358
+ service: SERVICE,
359
+ path: `/projects/members/joins/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}`
360
+ });
361
+ },
362
+ async removeProjectMember(projectId, userId) {
363
+ return client.request({
364
+ method: "DELETE",
365
+ service: SERVICE,
366
+ path: `/projects/members/${encodeURIComponent(projectId)}/${encodeURIComponent(userId)}`
367
+ });
368
+ },
369
+ // Permissions
370
+ async getPermissions(projectId) {
371
+ return client.request({
372
+ method: "GET",
373
+ service: SERVICE,
374
+ path: `/permissions/${encodeURIComponent(projectId)}`
375
+ });
376
+ },
377
+ // API Tokens
378
+ async createApiToken(request) {
379
+ return client.request({
380
+ method: "POST",
381
+ service: SERVICE,
382
+ path: "/api-tokens/",
383
+ body: request
384
+ });
385
+ },
386
+ async getApiTokens() {
387
+ return client.request({
388
+ method: "GET",
389
+ service: SERVICE,
390
+ path: "/api-tokens/"
391
+ });
392
+ },
393
+ async getApiTokensByResource(resourceId) {
394
+ return client.request({
395
+ method: "GET",
396
+ service: SERVICE,
397
+ path: `/api-tokens/resource/${encodeURIComponent(resourceId)}`
398
+ });
399
+ },
400
+ async revokeApiToken(tokenId) {
401
+ return client.request({
402
+ method: "DELETE",
403
+ service: SERVICE,
404
+ path: `/api-tokens/${encodeURIComponent(tokenId)}`
405
+ });
406
+ },
407
+ // Groups
408
+ async getGroups() {
409
+ return client.request({
410
+ method: "GET",
411
+ service: SERVICE,
412
+ path: "/groups/"
413
+ });
414
+ },
415
+ async getAllGroups() {
416
+ return client.request({
417
+ method: "GET",
418
+ service: SERVICE,
419
+ path: "/groups/all"
420
+ });
421
+ },
422
+ async getGroup(groupId) {
423
+ return client.request({
424
+ method: "GET",
425
+ service: SERVICE,
426
+ path: `/groups/${encodeURIComponent(groupId)}`
427
+ });
428
+ },
429
+ async createGroup(group) {
430
+ return client.request({
431
+ method: "POST",
432
+ service: SERVICE,
433
+ path: "/groups/",
434
+ body: group
435
+ });
436
+ },
437
+ async deleteGroup(groupId) {
438
+ return client.request({
439
+ method: "DELETE",
440
+ service: SERVICE,
441
+ path: `/groups/${encodeURIComponent(groupId)}`
442
+ });
443
+ },
444
+ async getGroupMembers(groupId) {
445
+ return client.request({
446
+ method: "GET",
447
+ service: SERVICE,
448
+ path: `/groups/members/${encodeURIComponent(groupId)}`
449
+ });
450
+ },
451
+ async inviteGroupMember(groupId, userId, role) {
452
+ return client.request({
453
+ method: "POST",
454
+ service: SERVICE,
455
+ path: `/groups/members/invitations/${encodeURIComponent(groupId)}/${encodeURIComponent(userId)}/${encodeURIComponent(role)}`
456
+ });
457
+ },
458
+ async removeGroupMember(groupId, userId) {
459
+ return client.request({
460
+ method: "DELETE",
461
+ service: SERVICE,
462
+ path: `/groups/members/${encodeURIComponent(groupId)}/${encodeURIComponent(userId)}`
463
+ });
464
+ },
465
+ async getGroupProjects(groupId) {
466
+ return client.request({
467
+ method: "GET",
468
+ service: SERVICE,
469
+ path: `/groups/projects/${encodeURIComponent(groupId)}`
470
+ });
471
+ },
472
+ async addGroupProject(groupId, projectId) {
473
+ return client.request({
474
+ method: "POST",
475
+ service: SERVICE,
476
+ path: `/groups/projects/${encodeURIComponent(groupId)}/${encodeURIComponent(projectId)}`
477
+ });
478
+ },
479
+ async removeGroupProject(groupId, projectId) {
480
+ return client.request({
481
+ method: "DELETE",
482
+ service: SERVICE,
483
+ path: `/groups/projects/${encodeURIComponent(groupId)}/${encodeURIComponent(projectId)}`
484
+ });
485
+ },
486
+ // Settings
487
+ async getSettings() {
488
+ return client.request({
489
+ method: "GET",
490
+ service: SERVICE,
491
+ path: "/settings/"
492
+ });
493
+ },
494
+ async mergeSetting(setting) {
495
+ return client.request({
496
+ method: "PUT",
497
+ service: SERVICE,
498
+ path: "/settings/",
499
+ body: setting
500
+ });
501
+ },
502
+ // Subscription
503
+ async getCurrentSubscription() {
504
+ return client.request({
505
+ method: "GET",
506
+ service: SERVICE,
507
+ path: "/subscriptions/current"
508
+ });
509
+ },
510
+ // Backup
511
+ async createShortTermProjectBackup(body) {
512
+ return client.request({
513
+ method: "POST",
514
+ service: SERVICE,
515
+ path: "/backups/project/short-term/create",
516
+ body
517
+ });
518
+ },
519
+ async createShortTermFullBackup() {
520
+ return client.request({
521
+ method: "POST",
522
+ service: SERVICE,
523
+ path: "/backups/full/short-term/create"
524
+ });
525
+ },
526
+ // Analyses
527
+ async getLastAnalysis() {
528
+ return client.request({
529
+ method: "GET",
530
+ service: SERVICE,
531
+ path: "/analyses/last"
532
+ });
533
+ },
534
+ async getAnalysis(analysisId) {
535
+ return client.request({
536
+ method: "GET",
537
+ service: SERVICE,
538
+ path: `/analyses/${encodeURIComponent(analysisId)}`
539
+ });
540
+ },
541
+ async saveAnalysis(analysis) {
542
+ return client.request({
543
+ method: "POST",
544
+ service: SERVICE,
545
+ path: "/analyses/",
546
+ body: analysis
547
+ });
548
+ }
549
+ };
550
+ }
551
+
552
+ // src/util/errors.ts
553
+ import chalk from "chalk";
554
+ function handleError(error) {
555
+ if (error instanceof ApiError) {
556
+ console.error(chalk.red("Error:"), error.toUserMessage());
557
+ process.exit(1);
558
+ }
559
+ if (error instanceof NetworkError) {
560
+ console.error(chalk.red("Network error:"), error.message);
561
+ process.exit(1);
562
+ }
563
+ if (error instanceof Error) {
564
+ console.error(chalk.red("Error:"), error.message);
565
+ process.exit(1);
566
+ }
567
+ console.error(chalk.red("Error:"), String(error));
568
+ process.exit(1);
569
+ }
570
+
571
+ // src/commands/auth/login.ts
572
+ function registerLoginCommand(parent) {
573
+ parent.command("login").description("Authenticate with the Diafunc platform").option("--token <token>", "API token (dfat_...) for token-based auth").option("--endpoint <url>", "Override the endpoint URL for this login").action(async (options) => {
574
+ try {
575
+ const config = loadConfig();
576
+ const profile = config.profiles[config.currentProfile];
577
+ if (!profile) {
578
+ console.error(chalk2.red(`Profile "${config.currentProfile}" not found. Run 'diafunc config profile add' first.`));
579
+ process.exit(1);
580
+ }
581
+ if (options.endpoint) {
582
+ profile.endpoint = options.endpoint;
583
+ }
584
+ if (options.token) {
585
+ profile.auth = {
586
+ type: "api-token",
587
+ token: options.token
588
+ };
589
+ saveConfig(config);
590
+ const client = createHttpClient();
591
+ const admin = createAdminService(client);
592
+ const user = await admin.getMyUser();
593
+ console.log(chalk2.green("Authenticated successfully."));
594
+ console.log(` User: ${chalk2.bold(user.name)}`);
595
+ console.log(` Email: ${user.email}`);
596
+ console.log(` Profile: ${config.currentProfile}`);
597
+ console.log(` Endpoint: ${profile.endpoint}`);
598
+ } else {
599
+ const { input, password } = await import("@inquirer/prompts");
600
+ const username = await input({
601
+ message: "Username or email:"
602
+ });
603
+ const pwd = await password({
604
+ message: "Password:"
605
+ });
606
+ const endpoint = profile.endpoint.replace(/\/+$/, "");
607
+ const response = await fetch(`${endpoint}/api/v1/admin/sessions/`, {
608
+ method: "POST",
609
+ headers: { "Content-Type": "application/json" },
610
+ body: JSON.stringify({
611
+ userNameOrEmail: username,
612
+ password: pwd
613
+ })
614
+ });
615
+ if (!response.ok) {
616
+ const text = await response.text();
617
+ console.error(chalk2.red("Login failed:"), text || response.statusText);
618
+ process.exit(1);
619
+ }
620
+ const session = await response.json();
621
+ profile.auth = {
622
+ type: "session",
623
+ accessToken: session.accessToken.raw,
624
+ refreshToken: session.refreshToken.raw,
625
+ accessTokenExpiry: session.accessToken.expiry
626
+ };
627
+ saveConfig(config);
628
+ const client = createHttpClient();
629
+ const admin = createAdminService(client);
630
+ const user = await admin.getMyUser();
631
+ console.log(chalk2.green("Logged in successfully."));
632
+ console.log(` User: ${chalk2.bold(user.name)}`);
633
+ console.log(` Email: ${user.email}`);
634
+ console.log(` Profile: ${config.currentProfile}`);
635
+ console.log(` Endpoint: ${profile.endpoint}`);
636
+ }
637
+ } catch (error) {
638
+ handleError(error);
639
+ }
640
+ });
641
+ }
642
+
643
+ // src/commands/auth/logout.ts
644
+ import chalk3 from "chalk";
645
+ function registerLogoutCommand(parent) {
646
+ parent.command("logout").description("Remove stored credentials for the active profile").action(() => {
647
+ const config = loadConfig();
648
+ const profile = config.profiles[config.currentProfile];
649
+ if (!profile) {
650
+ console.error(chalk3.red(`Profile "${config.currentProfile}" not found.`));
651
+ process.exit(1);
652
+ }
653
+ if (!profile.auth) {
654
+ console.log(chalk3.dim("No credentials stored for this profile."));
655
+ return;
656
+ }
657
+ delete profile.auth;
658
+ saveConfig(config);
659
+ console.log(chalk3.green(`Logged out from profile "${config.currentProfile}".`));
660
+ });
661
+ }
662
+
663
+ // src/commands/auth/status.ts
664
+ import chalk5 from "chalk";
665
+
666
+ // src/output/human.ts
667
+ import chalk4 from "chalk";
668
+ import Table from "cli-table3";
669
+ function formatHuman(data, columns) {
670
+ if (Array.isArray(data)) {
671
+ if (data.length === 0) {
672
+ console.log(chalk4.dim("No results."));
673
+ return;
674
+ }
675
+ const cols = columns ?? Object.keys(data[0]);
676
+ const table = new Table({
677
+ head: cols.map((c) => chalk4.bold(c)),
678
+ style: { head: [], border: [] }
679
+ });
680
+ for (const row of data) {
681
+ const r = row;
682
+ table.push(cols.map((c) => formatValue(r[c])));
683
+ }
684
+ console.log(table.toString());
685
+ } else if (data && typeof data === "object") {
686
+ const obj = data;
687
+ const table = new Table({
688
+ style: { head: [], border: [] }
689
+ });
690
+ for (const [key, value] of Object.entries(obj)) {
691
+ table.push({ [chalk4.bold(key)]: formatValue(value) });
692
+ }
693
+ console.log(table.toString());
694
+ } else {
695
+ console.log(String(data));
696
+ }
697
+ }
698
+ function formatValue(value) {
699
+ if (value === null || value === void 0) return chalk4.dim("\u2014");
700
+ if (typeof value === "boolean") return value ? chalk4.green("true") : chalk4.red("false");
701
+ if (typeof value === "number") return chalk4.cyan(String(value));
702
+ return String(value);
703
+ }
704
+
705
+ // src/output/json.ts
706
+ function formatJson(data) {
707
+ console.log(JSON.stringify(data, null, 2));
708
+ }
709
+
710
+ // src/output/table.ts
711
+ function formatTable(data, columns) {
712
+ if (Array.isArray(data)) {
713
+ if (data.length === 0) return;
714
+ const cols = columns ?? Object.keys(data[0]);
715
+ console.log(cols.join(" "));
716
+ for (const row of data) {
717
+ const r = row;
718
+ console.log(cols.map((c) => String(r[c] ?? "")).join(" "));
719
+ }
720
+ } else if (data && typeof data === "object") {
721
+ const obj = data;
722
+ for (const [key, value] of Object.entries(obj)) {
723
+ console.log(`${key} ${String(value ?? "")}`);
724
+ }
725
+ } else {
726
+ console.log(String(data));
727
+ }
728
+ }
729
+
730
+ // src/output/formatter.ts
731
+ function format(data, options) {
732
+ switch (options.format) {
733
+ case "json":
734
+ formatJson(data);
735
+ break;
736
+ case "table":
737
+ formatTable(data, options.columns);
738
+ break;
739
+ case "human":
740
+ default:
741
+ formatHuman(data, options.columns);
742
+ break;
743
+ }
744
+ }
745
+
746
+ // src/commands/auth/status.ts
747
+ function registerStatusCommand(parent) {
748
+ parent.command("status").description("Show current authentication status").action(async (_options, cmd) => {
749
+ try {
750
+ const config = loadConfig();
751
+ const globalOpts = cmd.optsWithGlobals();
752
+ const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
753
+ const profile = config.profiles[config.currentProfile];
754
+ if (!profile?.auth) {
755
+ if (outputFormat === "json") {
756
+ console.log(JSON.stringify({ authenticated: false, profile: config.currentProfile }));
757
+ } else {
758
+ console.log(chalk5.yellow("Not authenticated."), `Run 'diafunc auth login' to configure credentials.`);
759
+ console.log(` Profile: ${config.currentProfile}`);
760
+ console.log(` Endpoint: ${profile?.endpoint ?? "not configured"}`);
761
+ }
762
+ return;
763
+ }
764
+ const client = createHttpClient();
765
+ const admin = createAdminService(client);
766
+ const user = await admin.getMyUser();
767
+ const data = {
768
+ authenticated: true,
769
+ profile: config.currentProfile,
770
+ endpoint: profile.endpoint,
771
+ authType: profile.auth.type,
772
+ userId: user.id,
773
+ userName: user.name,
774
+ email: user.email,
775
+ role: user.role,
776
+ remainingCredits: user.remainingCredits
777
+ };
778
+ format(data, { format: outputFormat });
779
+ } catch (error) {
780
+ handleError(error);
781
+ }
782
+ });
783
+ }
784
+
785
+ // src/commands/auth/token.ts
786
+ import chalk6 from "chalk";
787
+
788
+ // src/client/services/storage.ts
789
+ var SERVICE2 = "storage";
790
+ function enc(s) {
791
+ return encodeURIComponent(s);
792
+ }
793
+ function entityPath(ref) {
794
+ return `/${enc(ref.projectId)}/${enc(ref.projectBranch)}/${enc(ref.entityId)}/${enc(ref.entityBranch)}`;
795
+ }
796
+ function createStorageService(client) {
797
+ return {
798
+ // --- Entities ---
799
+ async entityExists(ref) {
800
+ return client.request({
801
+ method: "GET",
802
+ service: SERVICE2,
803
+ path: `/entities/exists${entityPath(ref)}`
804
+ });
805
+ },
806
+ async getEntity(ref, content = false) {
807
+ return client.request({
808
+ method: "GET",
809
+ service: SERVICE2,
810
+ path: `/entities/actual${entityPath(ref)}`,
811
+ query: content ? { content: true } : void 0
812
+ });
813
+ },
814
+ async getEntityContent(ref) {
815
+ return client.requestRaw({
816
+ method: "GET",
817
+ service: SERVICE2,
818
+ path: `/entities/contents/actual${entityPath(ref)}`
819
+ });
820
+ },
821
+ async saveEntities(entities) {
822
+ return client.request({
823
+ method: "PUT",
824
+ service: SERVICE2,
825
+ path: "/entities/actual",
826
+ body: entities
827
+ });
828
+ },
829
+ async deleteEntity(ref) {
830
+ return client.request({
831
+ method: "DELETE",
832
+ service: SERVICE2,
833
+ path: `/entities/actual${entityPath(ref)}`
834
+ });
835
+ },
836
+ async saveEntityContentBase64(ref, base64Content) {
837
+ return client.request({
838
+ method: "PUT",
839
+ service: SERVICE2,
840
+ path: `/entities/contents/actual${entityPath(ref)}`,
841
+ rawBody: base64Content,
842
+ contentType: "text/plain"
843
+ });
844
+ },
845
+ async uploadEntityContent(ref, formData) {
846
+ return client.request({
847
+ method: "PUT",
848
+ service: SERVICE2,
849
+ path: `/entities/contents/actual${entityPath(ref)}`,
850
+ rawBody: formData
851
+ });
852
+ },
853
+ async deleteEntityContent(ref) {
854
+ return client.request({
855
+ method: "DELETE",
856
+ service: SERVICE2,
857
+ path: `/entities/contents/actual${entityPath(ref)}`
858
+ });
859
+ },
860
+ async getEntityHistory(ref, version) {
861
+ return client.request({
862
+ method: "GET",
863
+ service: SERVICE2,
864
+ path: `/entities/history${entityPath(ref)}/${version}`
865
+ });
866
+ },
867
+ async getEntityHistoryRange(ref, fromVersion, toVersion) {
868
+ return client.request({
869
+ method: "GET",
870
+ service: SERVICE2,
871
+ path: `/entities/history${entityPath(ref)}/${fromVersion}/${toVersion}`
872
+ });
873
+ },
874
+ async renameEntity(ref, newEntityId) {
875
+ return client.request({
876
+ method: "PUT",
877
+ service: SERVICE2,
878
+ path: `/entities/ids${entityPath(ref)}/${enc(newEntityId)}`
879
+ });
880
+ },
881
+ async revertEntity(ref, version) {
882
+ return client.request({
883
+ method: "PUT",
884
+ service: SERVICE2,
885
+ path: `/entities/revert${entityPath(ref)}/${version}`
886
+ });
887
+ },
888
+ // --- Entity Sets ---
889
+ async searchEntityIds(projectId, projectBranch, body) {
890
+ return client.request({
891
+ method: "POST",
892
+ service: SERVICE2,
893
+ path: "/entity-ids/search",
894
+ body
895
+ });
896
+ },
897
+ // --- Linked Entities ---
898
+ async getLinkedEntities(direction, ref) {
899
+ return client.request({
900
+ method: "GET",
901
+ service: SERVICE2,
902
+ path: `/linked-entities/${enc(direction)}${entityPath(ref)}`
903
+ });
904
+ },
905
+ async saveLinkedEntities(ref, linkId, entities) {
906
+ return client.request({
907
+ method: "PUT",
908
+ service: SERVICE2,
909
+ path: `/linked-entities/${enc(ref.projectId)}/${enc(ref.projectBranch)}/${enc(ref.entityId)}/${enc(ref.entityBranch)}/${enc(linkId)}`,
910
+ body: entities
911
+ });
912
+ },
913
+ // --- Links ---
914
+ async getLinks(direction, ref) {
915
+ return client.request({
916
+ method: "GET",
917
+ service: SERVICE2,
918
+ path: `/links/actual/${enc(direction)}${entityPath(ref)}`
919
+ });
920
+ },
921
+ async getLinkIds(direction, ref) {
922
+ return client.request({
923
+ method: "GET",
924
+ service: SERVICE2,
925
+ path: `/links/ids/actual/${enc(direction)}${entityPath(ref)}`
926
+ });
927
+ },
928
+ async createLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch, link) {
929
+ return client.request({
930
+ method: "POST",
931
+ service: SERVICE2,
932
+ path: `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}/${enc(targetEntityId)}/${enc(targetEntityBranch)}`,
933
+ body: link
934
+ });
935
+ },
936
+ async deleteLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch) {
937
+ let path5 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
938
+ if (targetEntityId && targetEntityBranch) {
939
+ path5 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
940
+ }
941
+ return client.request({
942
+ method: "DELETE",
943
+ service: SERVICE2,
944
+ path: path5
945
+ });
946
+ },
947
+ // --- Events ---
948
+ async getEvents(ref) {
949
+ return client.request({
950
+ method: "GET",
951
+ service: SERVICE2,
952
+ path: `/events/actual${entityPath(ref)}`
953
+ });
954
+ },
955
+ async getEvent(ref, eventId, occurrenceId) {
956
+ return client.request({
957
+ method: "GET",
958
+ service: SERVICE2,
959
+ path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`
960
+ });
961
+ },
962
+ async createEvents(events) {
963
+ return client.request({
964
+ method: "POST",
965
+ service: SERVICE2,
966
+ path: "/events/",
967
+ body: events
968
+ });
969
+ },
970
+ async consumeEvents(body) {
971
+ return client.request({
972
+ method: "POST",
973
+ service: SERVICE2,
974
+ path: "/events/consume",
975
+ body
976
+ });
977
+ },
978
+ async deleteEvent(ref, eventId, occurrenceId) {
979
+ return client.request({
980
+ method: "DELETE",
981
+ service: SERVICE2,
982
+ path: `/events/actual${entityPath(ref)}/${enc(eventId)}/${enc(occurrenceId)}`
983
+ });
984
+ },
985
+ // --- Tables ---
986
+ async getTableSnapshot(ref, request) {
987
+ return client.request({
988
+ method: "POST",
989
+ service: SERVICE2,
990
+ path: `/tables${entityPath(ref)}/snapshots`,
991
+ body: request ?? {}
992
+ });
993
+ },
994
+ async appendRow(ref) {
995
+ return client.request({
996
+ method: "POST",
997
+ service: SERVICE2,
998
+ path: `/tables${entityPath(ref)}/rows`
999
+ });
1000
+ },
1001
+ async deleteRow(ref, rowIndex) {
1002
+ return client.request({
1003
+ method: "DELETE",
1004
+ service: SERVICE2,
1005
+ path: `/tables${entityPath(ref)}/rows/${rowIndex}`
1006
+ });
1007
+ },
1008
+ async appendColumn(ref) {
1009
+ return client.request({
1010
+ method: "POST",
1011
+ service: SERVICE2,
1012
+ path: `/tables${entityPath(ref)}/columns`
1013
+ });
1014
+ },
1015
+ async deleteColumn(ref, columnIndex) {
1016
+ return client.request({
1017
+ method: "DELETE",
1018
+ service: SERVICE2,
1019
+ path: `/tables${entityPath(ref)}/columns/${columnIndex}`
1020
+ });
1021
+ },
1022
+ async mergeCells(ref, cells) {
1023
+ return client.request({
1024
+ method: "PUT",
1025
+ service: SERVICE2,
1026
+ path: `/tables${entityPath(ref)}/cells`,
1027
+ body: cells
1028
+ });
1029
+ },
1030
+ async deleteCell(ref, rowIndex, columnIndex) {
1031
+ return client.request({
1032
+ method: "DELETE",
1033
+ service: SERVICE2,
1034
+ path: `/tables${entityPath(ref)}/cells/${rowIndex}/${columnIndex}`
1035
+ });
1036
+ },
1037
+ async clearTable(ref) {
1038
+ return client.request({
1039
+ method: "POST",
1040
+ service: SERVICE2,
1041
+ path: `/tables${entityPath(ref)}/clear`
1042
+ });
1043
+ },
1044
+ // --- Table Import/Export ---
1045
+ async importTable(ref, formData, columnHeaders = true) {
1046
+ return client.request({
1047
+ method: "PUT",
1048
+ service: SERVICE2,
1049
+ path: `/table-imports${entityPath(ref)}`,
1050
+ query: { columnHeaders },
1051
+ rawBody: formData
1052
+ });
1053
+ },
1054
+ async getImport(ref, importId) {
1055
+ return client.request({
1056
+ method: "GET",
1057
+ service: SERVICE2,
1058
+ path: `/imports${entityPath(ref)}/${enc(importId)}`
1059
+ });
1060
+ },
1061
+ async exportTableCsv(ref) {
1062
+ return client.requestRaw({
1063
+ method: "POST",
1064
+ service: SERVICE2,
1065
+ path: `/table-exports${entityPath(ref)}/csv`
1066
+ });
1067
+ },
1068
+ async exportTableExcel(ref) {
1069
+ return client.requestRaw({
1070
+ method: "POST",
1071
+ service: SERVICE2,
1072
+ path: `/table-exports${entityPath(ref)}/excel`
1073
+ });
1074
+ },
1075
+ // --- Branches ---
1076
+ async getProjectBranches(projectId) {
1077
+ return client.request({
1078
+ method: "GET",
1079
+ service: SERVICE2,
1080
+ path: `/project-branches/${enc(projectId)}`
1081
+ });
1082
+ },
1083
+ async createProjectBranch(request) {
1084
+ return client.request({
1085
+ method: "POST",
1086
+ service: SERVICE2,
1087
+ path: "/project-branches/",
1088
+ body: request
1089
+ });
1090
+ },
1091
+ async deleteProjectBranch(projectId, projectBranch) {
1092
+ return client.request({
1093
+ method: "DELETE",
1094
+ service: SERVICE2,
1095
+ path: `/project-branches/${enc(projectId)}/${enc(projectBranch)}`
1096
+ });
1097
+ },
1098
+ async getEntityBranches(projectId, projectBranch, entityId) {
1099
+ return client.request({
1100
+ method: "GET",
1101
+ service: SERVICE2,
1102
+ path: `/entity-branches/${enc(projectId)}/${enc(projectBranch)}/${enc(entityId)}`
1103
+ });
1104
+ },
1105
+ async createEntityBranch(request) {
1106
+ return client.request({
1107
+ method: "POST",
1108
+ service: SERVICE2,
1109
+ path: "/entity-branches/",
1110
+ body: request
1111
+ });
1112
+ },
1113
+ // --- Merge & Fork ---
1114
+ async merge(request) {
1115
+ return client.request({
1116
+ method: "POST",
1117
+ service: SERVICE2,
1118
+ path: "/merge/",
1119
+ body: request
1120
+ });
1121
+ },
1122
+ async fork(request) {
1123
+ return client.request({
1124
+ method: "POST",
1125
+ service: SERVICE2,
1126
+ path: "/fork/",
1127
+ body: request
1128
+ });
1129
+ },
1130
+ // --- Project Search ---
1131
+ async searchProject(projectId, projectBranch, body) {
1132
+ return client.request({
1133
+ method: "POST",
1134
+ service: SERVICE2,
1135
+ path: `/project-searches/${enc(projectId)}/${enc(projectBranch)}`,
1136
+ body
1137
+ });
1138
+ }
1139
+ };
1140
+ }
1141
+
1142
+ // src/client/services/evaluation.ts
1143
+ var SERVICE3 = "evaluation";
1144
+ function enc2(s) {
1145
+ return encodeURIComponent(s);
1146
+ }
1147
+ function createEvaluationService(client) {
1148
+ return {
1149
+ // Calls
1150
+ async call(request, async = false) {
1151
+ return client.request({
1152
+ method: "POST",
1153
+ service: SERVICE3,
1154
+ path: "/calls/",
1155
+ body: request,
1156
+ query: async ? { async: true } : void 0
1157
+ });
1158
+ },
1159
+ // Evaluations
1160
+ async getEvaluations(projectId, projectBranch, functionId, functionBranch, year, month, day, hour) {
1161
+ return client.request({
1162
+ method: "GET",
1163
+ service: SERVICE3,
1164
+ path: `/evaluations/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}`
1165
+ });
1166
+ },
1167
+ async getEvaluation(projectId, projectBranch, functionId, functionBranch, year, month, day, hour, evaluationId, result = false) {
1168
+ return client.request({
1169
+ method: "GET",
1170
+ service: SERVICE3,
1171
+ path: `/evaluations/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}/${enc2(evaluationId)}`,
1172
+ query: result ? { result: true } : void 0
1173
+ });
1174
+ },
1175
+ // Last Evaluation
1176
+ async getLastEvaluation(projectId, projectBranch, functionId, functionBranch) {
1177
+ return client.request({
1178
+ method: "GET",
1179
+ service: SERVICE3,
1180
+ path: `/last-evaluation/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}`
1181
+ });
1182
+ },
1183
+ // Outputs
1184
+ async getOutputs(projectId, evaluationId) {
1185
+ return client.request({
1186
+ method: "GET",
1187
+ service: SERVICE3,
1188
+ path: `/output/${enc2(projectId)}/${enc2(evaluationId)}`
1189
+ });
1190
+ },
1191
+ // Logs
1192
+ async getLogs(projectId, projectBranch, functionId, functionBranch, year, month, day, hour) {
1193
+ return client.request({
1194
+ method: "GET",
1195
+ service: SERVICE3,
1196
+ path: `/log/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}`
1197
+ });
1198
+ },
1199
+ // Source Code
1200
+ async getSourceCode(projectId, projectBranch, functionId, functionBranch, sourceCodeHash, sourceCodeId) {
1201
+ return client.request({
1202
+ method: "GET",
1203
+ service: SERVICE3,
1204
+ path: `/sourcecodes/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(sourceCodeHash)}/${enc2(sourceCodeId)}`
1205
+ });
1206
+ },
1207
+ // Stop
1208
+ async stopEvaluation(projectId, projectBranch, functionId, functionBranch, year, month, day, hour, evaluationId) {
1209
+ return client.request({
1210
+ method: "POST",
1211
+ service: SERVICE3,
1212
+ path: `/stop/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${year}/${month}/${day}/${hour}/${enc2(evaluationId)}`
1213
+ });
1214
+ },
1215
+ // Triggers
1216
+ async getTriggers(projectId, projectBranch, functionId, functionBranch) {
1217
+ return client.request({
1218
+ method: "GET",
1219
+ service: SERVICE3,
1220
+ path: `/triggers/actual/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}`
1221
+ });
1222
+ },
1223
+ async getTrigger(projectId, projectBranch, functionId, functionBranch, triggerId) {
1224
+ return client.request({
1225
+ method: "GET",
1226
+ service: SERVICE3,
1227
+ path: `/triggers/actual/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(triggerId)}`
1228
+ });
1229
+ },
1230
+ async saveTrigger(trigger) {
1231
+ return client.request({
1232
+ method: "PUT",
1233
+ service: SERVICE3,
1234
+ path: "/triggers/",
1235
+ body: trigger
1236
+ });
1237
+ },
1238
+ async deleteTrigger(projectId, projectBranch, functionId, functionBranch, triggerId) {
1239
+ return client.request({
1240
+ method: "DELETE",
1241
+ service: SERVICE3,
1242
+ path: `/triggers/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(triggerId)}`
1243
+ });
1244
+ },
1245
+ // Engines
1246
+ async getEngines() {
1247
+ return client.request({
1248
+ method: "GET",
1249
+ service: SERVICE3,
1250
+ path: "/engines/"
1251
+ });
1252
+ }
1253
+ };
1254
+ }
1255
+
1256
+ // src/client/services/scheduler.ts
1257
+ var SERVICE4 = "scheduler";
1258
+ function createSchedulerService(client) {
1259
+ return {
1260
+ async scheduleCall(request) {
1261
+ return client.request({
1262
+ method: "POST",
1263
+ service: SERVICE4,
1264
+ path: "/calls/",
1265
+ body: request
1266
+ });
1267
+ }
1268
+ };
1269
+ }
1270
+
1271
+ // src/client/services/language.ts
1272
+ var SERVICE5 = "language";
1273
+ function enc3(s) {
1274
+ return encodeURIComponent(s);
1275
+ }
1276
+ function createLanguageService(client) {
1277
+ return {
1278
+ // Chat (blocking)
1279
+ async chat(request) {
1280
+ return client.request({
1281
+ method: "POST",
1282
+ service: SERVICE5,
1283
+ path: "/chat/",
1284
+ body: request
1285
+ });
1286
+ },
1287
+ // Chat (streaming) — returns raw response for SSE parsing
1288
+ async chatStream(request) {
1289
+ return client.requestRaw({
1290
+ method: "POST",
1291
+ service: SERVICE5,
1292
+ path: "/chat/stream",
1293
+ body: request
1294
+ });
1295
+ },
1296
+ // File upload
1297
+ async upload(formData) {
1298
+ return client.request({
1299
+ method: "POST",
1300
+ service: SERVICE5,
1301
+ path: "/upload/",
1302
+ rawBody: formData
1303
+ });
1304
+ },
1305
+ // Token usage
1306
+ async getUsage() {
1307
+ return client.request({
1308
+ method: "GET",
1309
+ service: SERVICE5,
1310
+ path: "/usage/"
1311
+ });
1312
+ },
1313
+ // Sessions
1314
+ async getSessions() {
1315
+ return client.request({
1316
+ method: "GET",
1317
+ service: SERVICE5,
1318
+ path: "/sessions/"
1319
+ });
1320
+ },
1321
+ async getSession(sessionId) {
1322
+ return client.request({
1323
+ method: "GET",
1324
+ service: SERVICE5,
1325
+ path: `/sessions/${enc3(sessionId)}`
1326
+ });
1327
+ },
1328
+ async deleteSession(sessionId) {
1329
+ return client.request({
1330
+ method: "DELETE",
1331
+ service: SERVICE5,
1332
+ path: `/sessions/${enc3(sessionId)}`
1333
+ });
1334
+ },
1335
+ async getSessionMessages(sessionId) {
1336
+ return client.request({
1337
+ method: "GET",
1338
+ service: SERVICE5,
1339
+ path: `/sessions/${enc3(sessionId)}/messages`
1340
+ });
1341
+ },
1342
+ async renameSession(sessionId, title) {
1343
+ return client.request({
1344
+ method: "PUT",
1345
+ service: SERVICE5,
1346
+ path: `/sessions/${enc3(sessionId)}/title`,
1347
+ rawBody: title,
1348
+ contentType: "text/plain"
1349
+ });
1350
+ }
1351
+ };
1352
+ }
1353
+
1354
+ // src/client/services/index-search.ts
1355
+ var SERVICE6 = "index";
1356
+ function enc4(s) {
1357
+ return encodeURIComponent(s);
1358
+ }
1359
+ function createIndexService(client) {
1360
+ return {
1361
+ async rebuildAll() {
1362
+ return client.request({
1363
+ method: "POST",
1364
+ service: SERVICE6,
1365
+ path: "/indexes/rebuild"
1366
+ });
1367
+ },
1368
+ async rebuildProject(projectId) {
1369
+ return client.request({
1370
+ method: "POST",
1371
+ service: SERVICE6,
1372
+ path: `/indexes/rebuild/${enc4(projectId)}`
1373
+ });
1374
+ }
1375
+ };
1376
+ }
1377
+
1378
+ // src/client/api.ts
1379
+ function createApiClient(options = {}) {
1380
+ const http = createHttpClient(options);
1381
+ return {
1382
+ http,
1383
+ admin: createAdminService(http),
1384
+ storage: createStorageService(http),
1385
+ evaluation: createEvaluationService(http),
1386
+ scheduler: createSchedulerService(http),
1387
+ language: createLanguageService(http),
1388
+ index: createIndexService(http)
1389
+ };
1390
+ }
1391
+
1392
+ // src/commands/auth/token.ts
1393
+ var VALID_SCOPES = [
1394
+ "project:read",
1395
+ "project:write",
1396
+ "storage:read",
1397
+ "storage:write",
1398
+ "evaluation:read",
1399
+ "evaluation:execute"
1400
+ ];
1401
+ function registerTokenCommands(parent) {
1402
+ const token = parent.command("token").description("Manage API tokens");
1403
+ token.command("create").description("Create a new API token").requiredOption("--name <name>", "Token name").requiredOption("--resource <id>", "Resource ID (project or group)").requiredOption("--scopes <scopes>", `Comma-separated scopes: ${VALID_SCOPES.join(", ")}`).option("--resource-type <type>", "Resource type (project or group)", "project").option("--days <days>", "Validity in days (default: 365)", "365").action(async (options, cmd) => {
1404
+ try {
1405
+ const config = loadConfig();
1406
+ const globalOpts = cmd.optsWithGlobals();
1407
+ const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
1408
+ const scopes = options.scopes.split(",").map((s) => s.trim());
1409
+ for (const scope of scopes) {
1410
+ if (!VALID_SCOPES.includes(scope)) {
1411
+ console.error(chalk6.red(`Invalid scope: "${scope}".`), `Valid scopes: ${VALID_SCOPES.join(", ")}`);
1412
+ process.exit(1);
1413
+ }
1414
+ }
1415
+ const api = createApiClient();
1416
+ const result = await api.admin.createApiToken({
1417
+ name: options.name,
1418
+ resourceId: options.resource,
1419
+ resourceType: options.resourceType,
1420
+ scopes,
1421
+ validityDays: parseInt(options.days, 10)
1422
+ });
1423
+ if (outputFormat === "human") {
1424
+ console.log(chalk6.green("API token created successfully."));
1425
+ console.log();
1426
+ console.log(` Token: ${chalk6.bold(result.token)}`);
1427
+ console.log(` Token ID: ${result.tokenId}`);
1428
+ console.log(` Name: ${result.name}`);
1429
+ console.log(` Expires: ${result.expiresAt}`);
1430
+ console.log();
1431
+ console.log(chalk6.yellow("Save this token \u2014 it will not be shown again."));
1432
+ } else {
1433
+ format(result, { format: outputFormat });
1434
+ }
1435
+ } catch (error) {
1436
+ handleError(error);
1437
+ }
1438
+ });
1439
+ token.command("list").description("List API tokens").option("--resource <id>", "Filter by resource ID").action(async (options, cmd) => {
1440
+ try {
1441
+ const config = loadConfig();
1442
+ const globalOpts = cmd.optsWithGlobals();
1443
+ const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
1444
+ const api = createApiClient();
1445
+ const tokens = options.resource ? await api.admin.getApiTokensByResource(options.resource) : await api.admin.getApiTokens();
1446
+ format(tokens, {
1447
+ format: outputFormat,
1448
+ columns: ["tokenId", "name", "resourceId", "scopes", "createdAt", "expiresAt"]
1449
+ });
1450
+ } catch (error) {
1451
+ handleError(error);
1452
+ }
1453
+ });
1454
+ token.command("revoke").description("Revoke an API token").argument("<tokenId>", "Token ID to revoke").action(async (tokenId) => {
1455
+ try {
1456
+ const api = createApiClient();
1457
+ await api.admin.revokeApiToken(tokenId);
1458
+ console.log(chalk6.green(`Token ${tokenId} revoked.`));
1459
+ } catch (error) {
1460
+ handleError(error);
1461
+ }
1462
+ });
1463
+ }
1464
+
1465
+ // src/commands/auth/index.ts
1466
+ function registerAuthCommands(program) {
1467
+ const auth = program.command("auth").description("Authentication and credential management");
1468
+ registerLoginCommand(auth);
1469
+ registerLogoutCommand(auth);
1470
+ registerStatusCommand(auth);
1471
+ registerTokenCommands(auth);
1472
+ }
1473
+
1474
+ // src/commands/config/index.ts
1475
+ import chalk7 from "chalk";
1476
+ function registerConfigCommands(program) {
1477
+ const config = program.command("config").description("Manage CLI configuration");
1478
+ config.command("set").description("Set a configuration value").argument("<key>", "Config key (e.g., defaults.project, defaults.branch, defaults.output)").argument("<value>", "Config value").action((key, value) => {
1479
+ const cfg = loadConfig();
1480
+ setNestedValue(cfg, key, value);
1481
+ saveConfig(cfg);
1482
+ console.log(chalk7.green(`Set ${key} = ${value}`));
1483
+ });
1484
+ config.command("get").description("Get a configuration value").argument("<key>", "Config key").action((key) => {
1485
+ const cfg = loadConfig();
1486
+ const value = getNestedValue(cfg, key);
1487
+ if (value === void 0) {
1488
+ console.log(chalk7.dim("(not set)"));
1489
+ } else {
1490
+ console.log(String(value));
1491
+ }
1492
+ });
1493
+ config.command("list").description("Show all configuration").action((_options, cmd) => {
1494
+ const cfg = loadConfig();
1495
+ const globalOpts = cmd.optsWithGlobals();
1496
+ const outputFormat = globalOpts.output ?? "human";
1497
+ if (outputFormat === "human") {
1498
+ console.log(chalk7.bold("Config file:"), CONFIG_FILE);
1499
+ console.log(chalk7.bold("Active profile:"), cfg.currentProfile);
1500
+ console.log();
1501
+ console.log(chalk7.bold("Profiles:"));
1502
+ for (const [name, profile2] of Object.entries(cfg.profiles)) {
1503
+ const active = name === cfg.currentProfile ? chalk7.green(" (active)") : "";
1504
+ const authType = profile2.auth?.type ?? "none";
1505
+ console.log(` ${chalk7.bold(name)}${active}`);
1506
+ console.log(` Endpoint: ${profile2.endpoint}`);
1507
+ console.log(` Auth: ${authType}`);
1508
+ }
1509
+ if (Object.keys(cfg.defaults).length > 0) {
1510
+ console.log();
1511
+ console.log(chalk7.bold("Defaults:"));
1512
+ for (const [key, value] of Object.entries(cfg.defaults)) {
1513
+ console.log(` ${key}: ${value}`);
1514
+ }
1515
+ }
1516
+ } else {
1517
+ format(cfg, { format: outputFormat });
1518
+ }
1519
+ });
1520
+ const profile = config.command("profile").description("Manage profiles");
1521
+ profile.command("add").description("Add a new profile").argument("<name>", "Profile name").option("--endpoint <url>", "API endpoint URL", "https://diafunc.com").option("--token <token>", "API token to store").action((name, options) => {
1522
+ const cfg = loadConfig();
1523
+ if (cfg.profiles[name]) {
1524
+ console.error(chalk7.red(`Profile "${name}" already exists. Use 'diafunc config profile use' to switch to it.`));
1525
+ process.exit(1);
1526
+ }
1527
+ cfg.profiles[name] = {
1528
+ endpoint: options.endpoint,
1529
+ ...options.token ? { auth: { type: "api-token", token: options.token } } : {}
1530
+ };
1531
+ saveConfig(cfg);
1532
+ console.log(chalk7.green(`Profile "${name}" added.`));
1533
+ });
1534
+ profile.command("use").description("Switch to a profile").argument("<name>", "Profile name").action((name) => {
1535
+ const cfg = loadConfig();
1536
+ if (!cfg.profiles[name]) {
1537
+ console.error(chalk7.red(`Profile "${name}" not found.`));
1538
+ console.log(`Available profiles: ${Object.keys(cfg.profiles).join(", ")}`);
1539
+ process.exit(1);
1540
+ }
1541
+ cfg.currentProfile = name;
1542
+ saveConfig(cfg);
1543
+ console.log(chalk7.green(`Switched to profile "${name}".`));
1544
+ });
1545
+ profile.command("list").description("List all profiles").action((_options, cmd) => {
1546
+ const cfg = loadConfig();
1547
+ const globalOpts = cmd.optsWithGlobals();
1548
+ const outputFormat = globalOpts.output ?? cfg.defaults.output ?? "human";
1549
+ const profiles = Object.entries(cfg.profiles).map(([name, p]) => ({
1550
+ name,
1551
+ endpoint: p.endpoint,
1552
+ auth: p.auth?.type ?? "none",
1553
+ active: name === cfg.currentProfile
1554
+ }));
1555
+ format(profiles, {
1556
+ format: outputFormat,
1557
+ columns: ["name", "endpoint", "auth", "active"]
1558
+ });
1559
+ });
1560
+ profile.command("remove").description("Remove a profile").argument("<name>", "Profile name").action((name) => {
1561
+ const cfg = loadConfig();
1562
+ if (!cfg.profiles[name]) {
1563
+ console.error(chalk7.red(`Profile "${name}" not found.`));
1564
+ process.exit(1);
1565
+ }
1566
+ if (name === cfg.currentProfile) {
1567
+ console.error(chalk7.red(`Cannot remove the active profile. Switch to another profile first.`));
1568
+ process.exit(1);
1569
+ }
1570
+ delete cfg.profiles[name];
1571
+ saveConfig(cfg);
1572
+ console.log(chalk7.green(`Profile "${name}" removed.`));
1573
+ });
1574
+ }
1575
+ function setNestedValue(obj, path5, value) {
1576
+ const keys = path5.split(".");
1577
+ let current = obj;
1578
+ for (let i = 0; i < keys.length - 1; i++) {
1579
+ const key = keys[i];
1580
+ if (!(key in current) || typeof current[key] !== "object" || current[key] === null) {
1581
+ current[key] = {};
1582
+ }
1583
+ current = current[key];
1584
+ }
1585
+ current[keys[keys.length - 1]] = value;
1586
+ }
1587
+ function getNestedValue(obj, path5) {
1588
+ const keys = path5.split(".");
1589
+ let current = obj;
1590
+ for (const key of keys) {
1591
+ if (current === null || current === void 0 || typeof current !== "object") {
1592
+ return void 0;
1593
+ }
1594
+ current = current[key];
1595
+ }
1596
+ return current;
1597
+ }
1598
+
1599
+ // src/commands/project/index.ts
1600
+ import chalk8 from "chalk";
1601
+ function getOutputFormat(cmd) {
1602
+ const config = loadConfig();
1603
+ const globalOpts = cmd.optsWithGlobals();
1604
+ return globalOpts.output ?? config.defaults.output ?? "human";
1605
+ }
1606
+ function registerProjectCommands(program) {
1607
+ const project = program.command("project").description("Manage projects");
1608
+ project.command("list").description("List projects").option("--all", "List all projects (admin)").action(async (options, cmd) => {
1609
+ try {
1610
+ const outputFormat = getOutputFormat(cmd);
1611
+ const api = createApiClient();
1612
+ const projects = options.all ? await api.admin.getAllProjects() : await api.admin.getProjects();
1613
+ format(projects, {
1614
+ format: outputFormat,
1615
+ columns: ["projectId", "groupId", "visibility", "language", "active", "locked"]
1616
+ });
1617
+ } catch (error) {
1618
+ handleError(error);
1619
+ }
1620
+ });
1621
+ project.command("get").description("Get project details").argument("<projectId>", "Project ID").action(async (projectId, _options, cmd) => {
1622
+ try {
1623
+ const outputFormat = getOutputFormat(cmd);
1624
+ const api = createApiClient();
1625
+ const p = await api.admin.getProject(projectId);
1626
+ format(p, { format: outputFormat });
1627
+ } catch (error) {
1628
+ handleError(error);
1629
+ }
1630
+ });
1631
+ project.command("create").description("Create a new project").option("--visibility <visibility>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--language <language>", "Project language", "Java").action(async (options, cmd) => {
1632
+ try {
1633
+ const outputFormat = getOutputFormat(cmd);
1634
+ const api = createApiClient();
1635
+ const p = await api.admin.createProject({
1636
+ visibility: options.visibility.toUpperCase(),
1637
+ language: options.language,
1638
+ active: true
1639
+ });
1640
+ if (outputFormat === "human") {
1641
+ console.log(chalk8.green("Project created."));
1642
+ console.log(` Project ID: ${chalk8.bold(p.projectId)}`);
1643
+ console.log(` Visibility: ${p.visibility}`);
1644
+ console.log(` Language: ${p.language}`);
1645
+ } else {
1646
+ format(p, { format: outputFormat });
1647
+ }
1648
+ } catch (error) {
1649
+ handleError(error);
1650
+ }
1651
+ });
1652
+ project.command("delete").description("Delete a project").argument("<projectId>", "Project ID").action(async (projectId) => {
1653
+ try {
1654
+ const api = createApiClient();
1655
+ await api.admin.deleteProject(projectId);
1656
+ console.log(chalk8.green(`Project "${projectId}" deleted.`));
1657
+ } catch (error) {
1658
+ handleError(error);
1659
+ }
1660
+ });
1661
+ project.command("lock").description("Lock a project").argument("<projectId>", "Project ID").action(async (projectId) => {
1662
+ try {
1663
+ const api = createApiClient();
1664
+ await api.admin.lockProject(projectId);
1665
+ console.log(chalk8.green(`Project "${projectId}" locked.`));
1666
+ } catch (error) {
1667
+ handleError(error);
1668
+ }
1669
+ });
1670
+ project.command("unlock").description("Unlock a project").argument("<projectId>", "Project ID").action(async (projectId) => {
1671
+ try {
1672
+ const api = createApiClient();
1673
+ await api.admin.unlockProject(projectId);
1674
+ console.log(chalk8.green(`Project "${projectId}" unlocked.`));
1675
+ } catch (error) {
1676
+ handleError(error);
1677
+ }
1678
+ });
1679
+ const members = project.command("members").description("Manage project members");
1680
+ members.command("list").description("List project members").argument("<projectId>", "Project ID").action(async (projectId, _options, cmd) => {
1681
+ try {
1682
+ const outputFormat = getOutputFormat(cmd);
1683
+ const api = createApiClient();
1684
+ const memberList = await api.admin.getProjectMembers(projectId);
1685
+ format(memberList, {
1686
+ format: outputFormat,
1687
+ columns: ["userId", "role", "joined", "invitedByUserId"]
1688
+ });
1689
+ } catch (error) {
1690
+ handleError(error);
1691
+ }
1692
+ });
1693
+ members.command("invite").description("Invite a user to a project").argument("<projectId>", "Project ID").argument("<userId>", "User ID to invite").argument("<role>", "Role (OWNER, ADMIN, DEVELOPER, GUEST)").action(async (projectId, userId, role) => {
1694
+ try {
1695
+ const api = createApiClient();
1696
+ await api.admin.inviteProjectMember(projectId, userId, role.toUpperCase());
1697
+ console.log(chalk8.green(`Invited ${userId} to "${projectId}" as ${role.toUpperCase()}.`));
1698
+ } catch (error) {
1699
+ handleError(error);
1700
+ }
1701
+ });
1702
+ members.command("join").description("Join a project").argument("<projectId>", "Project ID").argument("<userId>", "User ID").action(async (projectId, userId) => {
1703
+ try {
1704
+ const api = createApiClient();
1705
+ await api.admin.joinProject(projectId, userId);
1706
+ console.log(chalk8.green(`Joined project "${projectId}".`));
1707
+ } catch (error) {
1708
+ handleError(error);
1709
+ }
1710
+ });
1711
+ members.command("remove").description("Remove a member from a project").argument("<projectId>", "Project ID").argument("<userId>", "User ID to remove").action(async (projectId, userId) => {
1712
+ try {
1713
+ const api = createApiClient();
1714
+ await api.admin.removeProjectMember(projectId, userId);
1715
+ console.log(chalk8.green(`Removed ${userId} from "${projectId}".`));
1716
+ } catch (error) {
1717
+ handleError(error);
1718
+ }
1719
+ });
1720
+ }
1721
+
1722
+ // src/commands/entity/index.ts
1723
+ import chalk9 from "chalk";
1724
+ import * as fs2 from "fs";
1725
+
1726
+ // src/util/references.ts
1727
+ function parseEntityReference(ref, overrides) {
1728
+ const config = loadConfig();
1729
+ const defaultProject = overrides?.project ?? config.defaults.project;
1730
+ const defaultBranch = overrides?.branch ?? config.defaults.branch ?? "main";
1731
+ if (!ref.includes("/") && ref.includes(":")) {
1732
+ const [entityId, entityBranch] = ref.split(":");
1733
+ if (!defaultProject) {
1734
+ throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
1735
+ }
1736
+ return {
1737
+ projectId: defaultProject,
1738
+ projectBranch: defaultBranch,
1739
+ entityId,
1740
+ entityBranch: entityBranch || defaultBranch
1741
+ };
1742
+ }
1743
+ const parts = ref.split("/");
1744
+ if (parts.length === 1) {
1745
+ if (!defaultProject) {
1746
+ throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
1747
+ }
1748
+ return {
1749
+ projectId: defaultProject,
1750
+ projectBranch: defaultBranch,
1751
+ entityId: parts[0],
1752
+ entityBranch: defaultBranch
1753
+ };
1754
+ }
1755
+ if (parts.length === 2) {
1756
+ return {
1757
+ projectId: parts[0],
1758
+ projectBranch: defaultBranch,
1759
+ entityId: parts[1],
1760
+ entityBranch: defaultBranch
1761
+ };
1762
+ }
1763
+ if (parts.length === 3) {
1764
+ if (parts[1] === "") {
1765
+ return {
1766
+ projectId: parts[0],
1767
+ projectBranch: defaultBranch,
1768
+ entityId: parts[2],
1769
+ entityBranch: defaultBranch
1770
+ };
1771
+ }
1772
+ return {
1773
+ projectId: parts[0],
1774
+ projectBranch: parts[1],
1775
+ entityId: parts[2],
1776
+ entityBranch: defaultBranch
1777
+ };
1778
+ }
1779
+ if (parts.length === 4) {
1780
+ return {
1781
+ projectId: parts[0],
1782
+ projectBranch: parts[1] || defaultBranch,
1783
+ entityId: parts[2],
1784
+ entityBranch: parts[3] || defaultBranch
1785
+ };
1786
+ }
1787
+ throw new Error(
1788
+ `Invalid entity reference: "${ref}". Expected format: entityId, entityId:branch, or projectId/projectBranch/entityId/entityBranch`
1789
+ );
1790
+ }
1791
+
1792
+ // src/commands/entity/index.ts
1793
+ function getOutputFormat2(cmd) {
1794
+ const config = loadConfig();
1795
+ const globalOpts = cmd.optsWithGlobals();
1796
+ return globalOpts.output ?? config.defaults.output ?? "human";
1797
+ }
1798
+ function getOverrides(cmd) {
1799
+ const opts = cmd.optsWithGlobals();
1800
+ return { project: opts.project, branch: opts.branch };
1801
+ }
1802
+ function registerEntityCommands(program) {
1803
+ const entity = program.command("entity").description("Manage entities");
1804
+ entity.command("list").description("List entities in a project (via linked entities from project root)").argument("<projectRef>", "Project reference (projectId or projectId/branch)").action(async (projectRef, _options, cmd) => {
1805
+ try {
1806
+ const outputFormat = getOutputFormat2(cmd);
1807
+ const overrides = getOverrides(cmd);
1808
+ const ref = parseEntityReference(projectRef + "/" + projectRef, overrides);
1809
+ const api = createApiClient();
1810
+ const entities = await api.storage.getLinkedEntities("FORWARD", {
1811
+ projectId: ref.projectId,
1812
+ projectBranch: ref.projectBranch,
1813
+ entityId: ref.projectId,
1814
+ entityBranch: ref.projectBranch
1815
+ });
1816
+ const summary = entities.map((e) => ({
1817
+ entityId: e.entityId,
1818
+ type: e.type,
1819
+ tags: e.tags.join(", "),
1820
+ version: e.version,
1821
+ modified: new Date(e.modified).toISOString()
1822
+ }));
1823
+ format(summary, {
1824
+ format: outputFormat,
1825
+ columns: ["entityId", "type", "tags", "version", "modified"]
1826
+ });
1827
+ } catch (error) {
1828
+ handleError(error);
1829
+ }
1830
+ });
1831
+ entity.command("get").description("Get entity metadata").argument("<ref>", "Entity reference").option("--content", "Include content").action(async (ref, options, cmd) => {
1832
+ try {
1833
+ const outputFormat = getOutputFormat2(cmd);
1834
+ const overrides = getOverrides(cmd);
1835
+ const resolved = parseEntityReference(ref, overrides);
1836
+ const api = createApiClient();
1837
+ const e = await api.storage.getEntity(resolved, options.content);
1838
+ if (outputFormat === "human") {
1839
+ const summary = {
1840
+ projectId: e.projectId,
1841
+ projectBranch: e.projectBranch,
1842
+ entityId: e.entityId,
1843
+ entityBranch: e.entityBranch,
1844
+ type: e.type,
1845
+ tags: e.tags.join(", ") || "\u2014",
1846
+ version: e.version,
1847
+ head: e.head,
1848
+ created: new Date(e.created).toISOString(),
1849
+ modified: new Date(e.modified).toISOString(),
1850
+ contentAvailable: e.contentAvailable,
1851
+ contentType: e.contentType,
1852
+ contentSize: e.contentSize
1853
+ };
1854
+ format(summary, { format: outputFormat });
1855
+ } else {
1856
+ format(e, { format: outputFormat });
1857
+ }
1858
+ } catch (error) {
1859
+ handleError(error);
1860
+ }
1861
+ });
1862
+ entity.command("delete").description("Delete an entity").argument("<ref>", "Entity reference").action(async (ref, _options, cmd) => {
1863
+ try {
1864
+ const overrides = getOverrides(cmd);
1865
+ const resolved = parseEntityReference(ref, overrides);
1866
+ const api = createApiClient();
1867
+ await api.storage.deleteEntity(resolved);
1868
+ console.log(chalk9.green(`Entity "${resolved.entityId}" deleted.`));
1869
+ } catch (error) {
1870
+ handleError(error);
1871
+ }
1872
+ });
1873
+ entity.command("history").description("Get entity version history").argument("<ref>", "Entity reference").option("--from <version>", "From version").option("--to <version>", "To version").action(async (ref, options, cmd) => {
1874
+ try {
1875
+ const outputFormat = getOutputFormat2(cmd);
1876
+ const overrides = getOverrides(cmd);
1877
+ const resolved = parseEntityReference(ref, overrides);
1878
+ const api = createApiClient();
1879
+ if (options.from && options.to) {
1880
+ const entities = await api.storage.getEntityHistoryRange(
1881
+ resolved,
1882
+ parseInt(options.from, 10),
1883
+ parseInt(options.to, 10)
1884
+ );
1885
+ const summary = entities.map((e) => ({
1886
+ version: e.version,
1887
+ modified: new Date(e.modified).toISOString(),
1888
+ head: e.head
1889
+ }));
1890
+ format(summary, { format: outputFormat, columns: ["version", "modified", "head"] });
1891
+ } else if (options.from) {
1892
+ const e = await api.storage.getEntityHistory(resolved, parseInt(options.from, 10));
1893
+ format(e, { format: outputFormat });
1894
+ } else {
1895
+ const e = await api.storage.getEntity(resolved);
1896
+ console.log(`Current version: ${e.version}, head: ${e.head}`);
1897
+ console.log(`Use --from <v> --to <v> to view a version range.`);
1898
+ }
1899
+ } catch (error) {
1900
+ handleError(error);
1901
+ }
1902
+ });
1903
+ entity.command("revert").description("Revert an entity to a previous version").argument("<ref>", "Entity reference").argument("<version>", "Version to revert to").action(async (ref, version, _options, cmd) => {
1904
+ try {
1905
+ const overrides = getOverrides(cmd);
1906
+ const resolved = parseEntityReference(ref, overrides);
1907
+ const api = createApiClient();
1908
+ await api.storage.revertEntity(resolved, parseInt(version, 10));
1909
+ console.log(chalk9.green(`Entity "${resolved.entityId}" reverted to version ${version}.`));
1910
+ } catch (error) {
1911
+ handleError(error);
1912
+ }
1913
+ });
1914
+ entity.command("rename").description("Rename an entity").argument("<ref>", "Entity reference").argument("<newId>", "New entity ID").action(async (ref, newId, _options, cmd) => {
1915
+ try {
1916
+ const overrides = getOverrides(cmd);
1917
+ const resolved = parseEntityReference(ref, overrides);
1918
+ const api = createApiClient();
1919
+ await api.storage.renameEntity(resolved, newId);
1920
+ console.log(chalk9.green(`Entity renamed from "${resolved.entityId}" to "${newId}".`));
1921
+ } catch (error) {
1922
+ handleError(error);
1923
+ }
1924
+ });
1925
+ const content = entity.command("content").description("Manage entity content");
1926
+ content.command("get").description("Download entity content").argument("<ref>", "Entity reference").option("--out <file>", "Output file (defaults to stdout)").action(async (ref, options, cmd) => {
1927
+ try {
1928
+ const overrides = getOverrides(cmd);
1929
+ const resolved = parseEntityReference(ref, overrides);
1930
+ const api = createApiClient();
1931
+ const response = await api.storage.getEntityContent(resolved);
1932
+ if (options.out) {
1933
+ const buffer = Buffer.from(await response.arrayBuffer());
1934
+ fs2.writeFileSync(options.out, buffer);
1935
+ console.log(chalk9.green(`Content saved to ${options.out}`));
1936
+ } else {
1937
+ const text = await response.text();
1938
+ process.stdout.write(text);
1939
+ }
1940
+ } catch (error) {
1941
+ handleError(error);
1942
+ }
1943
+ });
1944
+ content.command("set").description("Upload entity content from a file").argument("<ref>", "Entity reference").argument("<file>", "File to upload").action(async (ref, file, _options, cmd) => {
1945
+ try {
1946
+ const overrides = getOverrides(cmd);
1947
+ const resolved = parseEntityReference(ref, overrides);
1948
+ const api = createApiClient();
1949
+ const fileBuffer = fs2.readFileSync(file);
1950
+ const base64 = fileBuffer.toString("base64");
1951
+ await api.storage.saveEntityContentBase64(resolved, base64);
1952
+ console.log(chalk9.green(`Content uploaded from "${file}" to entity "${resolved.entityId}".`));
1953
+ } catch (error) {
1954
+ handleError(error);
1955
+ }
1956
+ });
1957
+ content.command("delete").description("Delete entity content").argument("<ref>", "Entity reference").action(async (ref, _options, cmd) => {
1958
+ try {
1959
+ const overrides = getOverrides(cmd);
1960
+ const resolved = parseEntityReference(ref, overrides);
1961
+ const api = createApiClient();
1962
+ await api.storage.deleteEntityContent(resolved);
1963
+ console.log(chalk9.green(`Content deleted from entity "${resolved.entityId}".`));
1964
+ } catch (error) {
1965
+ handleError(error);
1966
+ }
1967
+ });
1968
+ }
1969
+
1970
+ // src/commands/link/index.ts
1971
+ import chalk10 from "chalk";
1972
+ function getOutputFormat3(cmd) {
1973
+ const config = loadConfig();
1974
+ const globalOpts = cmd.optsWithGlobals();
1975
+ return globalOpts.output ?? config.defaults.output ?? "human";
1976
+ }
1977
+ function getOverrides2(cmd) {
1978
+ const opts = cmd.optsWithGlobals();
1979
+ return { project: opts.project, branch: opts.branch };
1980
+ }
1981
+ function registerLinkCommands(program) {
1982
+ const link = program.command("link").description("Manage links between entities");
1983
+ link.command("list").description("List links for an entity").argument("<ref>", "Source entity reference").option("--direction <dir>", "Link direction: FORWARD or BACKWARD", "FORWARD").action(async (ref, options, cmd) => {
1984
+ try {
1985
+ const outputFormat = getOutputFormat3(cmd);
1986
+ const overrides = getOverrides2(cmd);
1987
+ const resolved = parseEntityReference(ref, overrides);
1988
+ const api = createApiClient();
1989
+ const direction = options.direction.toUpperCase();
1990
+ const links = await api.storage.getLinks(direction, resolved);
1991
+ const summary = links.map((l) => ({
1992
+ linkId: l.linkId,
1993
+ targetEntityId: l.targetEntityId,
1994
+ targetEntityBranch: l.targetEntityBranch,
1995
+ type: l.type,
1996
+ version: l.version
1997
+ }));
1998
+ format(summary, {
1999
+ format: outputFormat,
2000
+ columns: ["linkId", "targetEntityId", "targetEntityBranch", "type", "version"]
2001
+ });
2002
+ } catch (error) {
2003
+ handleError(error);
2004
+ }
2005
+ });
2006
+ link.command("create").description("Create a link between two entities").argument("<sourceRef>", "Source entity reference").argument("<linkId>", "Link ID").argument("<targetRef>", "Target entity reference").action(async (sourceRef, linkId, targetRef, _options, cmd) => {
2007
+ try {
2008
+ const overrides = getOverrides2(cmd);
2009
+ const source = parseEntityReference(sourceRef, overrides);
2010
+ const target = parseEntityReference(targetRef, overrides);
2011
+ const api = createApiClient();
2012
+ await api.storage.createLink(
2013
+ source.projectId,
2014
+ source.projectBranch,
2015
+ source.entityId,
2016
+ source.entityBranch,
2017
+ linkId,
2018
+ target.entityId,
2019
+ target.entityBranch
2020
+ );
2021
+ console.log(chalk10.green(`Link "${linkId}" created: ${source.entityId} \u2192 ${target.entityId}`));
2022
+ } catch (error) {
2023
+ handleError(error);
2024
+ }
2025
+ });
2026
+ link.command("delete").description("Delete a link").argument("<sourceRef>", "Source entity reference").argument("<linkId>", "Link ID").argument("[targetRef]", "Target entity reference (optional, deletes all targets if omitted)").action(async (sourceRef, linkId, targetRef, _options, cmd) => {
2027
+ try {
2028
+ const overrides = getOverrides2(cmd);
2029
+ const source = parseEntityReference(sourceRef, overrides);
2030
+ const api = createApiClient();
2031
+ if (targetRef) {
2032
+ const target = parseEntityReference(targetRef, overrides);
2033
+ await api.storage.deleteLink(
2034
+ source.projectId,
2035
+ source.projectBranch,
2036
+ source.entityId,
2037
+ source.entityBranch,
2038
+ linkId,
2039
+ target.entityId,
2040
+ target.entityBranch
2041
+ );
2042
+ console.log(chalk10.green(`Link "${linkId}" deleted: ${source.entityId} \u2192 ${target.entityId}`));
2043
+ } else {
2044
+ await api.storage.deleteLink(
2045
+ source.projectId,
2046
+ source.projectBranch,
2047
+ source.entityId,
2048
+ source.entityBranch,
2049
+ linkId
2050
+ );
2051
+ console.log(chalk10.green(`All links with ID "${linkId}" from "${source.entityId}" deleted.`));
2052
+ }
2053
+ } catch (error) {
2054
+ handleError(error);
2055
+ }
2056
+ });
2057
+ }
2058
+
2059
+ // src/commands/event/index.ts
2060
+ import chalk11 from "chalk";
2061
+ function getOutputFormat4(cmd) {
2062
+ const config = loadConfig();
2063
+ const globalOpts = cmd.optsWithGlobals();
2064
+ return globalOpts.output ?? config.defaults.output ?? "human";
2065
+ }
2066
+ function getOverrides3(cmd) {
2067
+ const opts = cmd.optsWithGlobals();
2068
+ return { project: opts.project, branch: opts.branch };
2069
+ }
2070
+ function registerEventCommands(program) {
2071
+ const event = program.command("event").description("Manage events");
2072
+ event.command("list").description("List events for an entity").argument("<ref>", "Entity reference").action(async (ref, _options, cmd) => {
2073
+ try {
2074
+ const outputFormat = getOutputFormat4(cmd);
2075
+ const overrides = getOverrides3(cmd);
2076
+ const resolved = parseEntityReference(ref, overrides);
2077
+ const api = createApiClient();
2078
+ const events = await api.storage.getEvents(resolved);
2079
+ const summary = events.map((e) => ({
2080
+ eventId: e.eventId,
2081
+ occurrenceId: e.occurrenceId,
2082
+ type: e.type,
2083
+ duration: e.duration,
2084
+ created: new Date(e.created).toISOString()
2085
+ }));
2086
+ format(summary, {
2087
+ format: outputFormat,
2088
+ columns: ["eventId", "occurrenceId", "type", "duration", "created"]
2089
+ });
2090
+ } catch (error) {
2091
+ handleError(error);
2092
+ }
2093
+ });
2094
+ event.command("get").description("Get a specific event").argument("<ref>", "Entity reference").argument("<eventId>", "Event ID").argument("<occurrenceId>", "Occurrence ID").action(async (ref, eventId, occurrenceId, _options, cmd) => {
2095
+ try {
2096
+ const outputFormat = getOutputFormat4(cmd);
2097
+ const overrides = getOverrides3(cmd);
2098
+ const resolved = parseEntityReference(ref, overrides);
2099
+ const api = createApiClient();
2100
+ const event2 = await api.storage.getEvent(resolved, eventId, occurrenceId);
2101
+ format(event2, { format: outputFormat });
2102
+ } catch (error) {
2103
+ handleError(error);
2104
+ }
2105
+ });
2106
+ event.command("delete").description("Delete an event").argument("<ref>", "Entity reference").argument("<eventId>", "Event ID").argument("<occurrenceId>", "Occurrence ID").action(async (ref, eventId, occurrenceId, _options, cmd) => {
2107
+ try {
2108
+ const overrides = getOverrides3(cmd);
2109
+ const resolved = parseEntityReference(ref, overrides);
2110
+ const api = createApiClient();
2111
+ await api.storage.deleteEvent(resolved, eventId, occurrenceId);
2112
+ console.log(chalk11.green(`Event "${eventId}/${occurrenceId}" deleted.`));
2113
+ } catch (error) {
2114
+ handleError(error);
2115
+ }
2116
+ });
2117
+ }
2118
+
2119
+ // src/commands/branch/index.ts
2120
+ import chalk12 from "chalk";
2121
+ function getOutputFormat5(cmd) {
2122
+ const config = loadConfig();
2123
+ const globalOpts = cmd.optsWithGlobals();
2124
+ return globalOpts.output ?? config.defaults.output ?? "human";
2125
+ }
2126
+ function getOverrides4(cmd) {
2127
+ const opts = cmd.optsWithGlobals();
2128
+ return { project: opts.project, branch: opts.branch };
2129
+ }
2130
+ function registerBranchCommands(program) {
2131
+ const branch = program.command("branch").description("Manage branches");
2132
+ branch.command("list").description("List branches for a project").argument("[projectId]", "Project ID (uses default if omitted)").action(async (projectId, _options, cmd) => {
2133
+ try {
2134
+ const outputFormat = getOutputFormat5(cmd);
2135
+ const overrides = getOverrides4(cmd);
2136
+ const config = loadConfig();
2137
+ const pid = projectId ?? overrides.project ?? config.defaults.project;
2138
+ if (!pid) {
2139
+ console.error(chalk12.red("No project specified. Pass a project ID or set defaults.project."));
2140
+ process.exit(1);
2141
+ }
2142
+ const api = createApiClient();
2143
+ const branches = await api.storage.getProjectBranches(pid);
2144
+ if (outputFormat === "json") {
2145
+ format(branches, { format: outputFormat });
2146
+ } else {
2147
+ for (const b of branches) {
2148
+ console.log(b);
2149
+ }
2150
+ }
2151
+ } catch (error) {
2152
+ handleError(error);
2153
+ }
2154
+ });
2155
+ branch.command("create").description("Create a new project branch").argument("<projectId>", "Project ID").argument("<branchName>", "New branch name").option("--source <branch>", "Source branch to copy from", "main").action(async (projectId, branchName, options) => {
2156
+ try {
2157
+ const api = createApiClient();
2158
+ await api.storage.createProjectBranch({
2159
+ projectId,
2160
+ sourceProjectBranch: options.source,
2161
+ targetProjectBranch: branchName
2162
+ });
2163
+ console.log(chalk12.green(`Branch "${branchName}" created in project "${projectId}" from "${options.source}".`));
2164
+ } catch (error) {
2165
+ handleError(error);
2166
+ }
2167
+ });
2168
+ branch.command("delete").description("Delete a project branch").argument("<projectId>", "Project ID").argument("<branchName>", "Branch name to delete").action(async (projectId, branchName) => {
2169
+ try {
2170
+ const api = createApiClient();
2171
+ await api.storage.deleteProjectBranch(projectId, branchName);
2172
+ console.log(chalk12.green(`Branch "${branchName}" deleted from project "${projectId}".`));
2173
+ } catch (error) {
2174
+ handleError(error);
2175
+ }
2176
+ });
2177
+ branch.command("merge").description("Merge an entity from one branch to another").requiredOption("--source <ref>", "Source entity reference (projectId/branch/entityId/entityBranch)").requiredOption("--target <ref>", "Target project reference (projectId/branch)").option("--link-id <linkId>", "Link ID for the merge", "main").option("--deep", "Deep merge (include linked entities)", false).action(async (options, cmd) => {
2178
+ try {
2179
+ const overrides = getOverrides4(cmd);
2180
+ const source = parseEntityReference(options.source, overrides);
2181
+ const targetParts = options.target.split("/");
2182
+ const api = createApiClient();
2183
+ await api.storage.merge({
2184
+ sourceEntityReference: source,
2185
+ targetProjectReference: {
2186
+ projectId: targetParts[0],
2187
+ projectBranch: targetParts[1] || "main"
2188
+ },
2189
+ linkFromEntityReference: null,
2190
+ linkId: options.linkId,
2191
+ deepMerge: options.deep
2192
+ });
2193
+ console.log(chalk12.green("Merge completed."));
2194
+ } catch (error) {
2195
+ handleError(error);
2196
+ }
2197
+ });
2198
+ branch.command("fork").description("Fork a project").argument("<projectId>", "Source project ID").argument("<forkProjectId>", "New forked project ID").option("--branch <branch>", "Source branch", "main").option("--name <name>", "Forked project name").option("--description <desc>", "Forked project description", "").action(async (projectId, forkProjectId, options) => {
2199
+ try {
2200
+ const api = createApiClient();
2201
+ await api.storage.fork({
2202
+ projectId,
2203
+ projectBranch: options.branch,
2204
+ forkProjectId,
2205
+ forkProjectName: options.name ?? forkProjectId,
2206
+ forkProjectDescription: options.description
2207
+ });
2208
+ console.log(chalk12.green(`Project "${projectId}" forked to "${forkProjectId}".`));
2209
+ } catch (error) {
2210
+ handleError(error);
2211
+ }
2212
+ });
2213
+ }
2214
+
2215
+ // src/commands/table/index.ts
2216
+ import chalk13 from "chalk";
2217
+ import * as fs3 from "fs";
2218
+ import * as path2 from "path";
2219
+ function getOutputFormat6(cmd) {
2220
+ const config = loadConfig();
2221
+ const globalOpts = cmd.optsWithGlobals();
2222
+ return globalOpts.output ?? config.defaults.output ?? "human";
2223
+ }
2224
+ function getOverrides5(cmd) {
2225
+ const opts = cmd.optsWithGlobals();
2226
+ return { project: opts.project, branch: opts.branch };
2227
+ }
2228
+ function registerTableCommands(program) {
2229
+ const table = program.command("table").description("Manage tables");
2230
+ table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Row range (e.g., 0:10)").option("--cols <range>", "Column range (e.g., 0:5)").action(async (ref, options, cmd) => {
2231
+ try {
2232
+ const outputFormat = getOutputFormat6(cmd);
2233
+ const overrides = getOverrides5(cmd);
2234
+ const resolved = parseEntityReference(ref, overrides);
2235
+ const api = createApiClient();
2236
+ const request = {};
2237
+ if (options.rows) {
2238
+ const [from, to] = options.rows.split(":").map(Number);
2239
+ if (!isNaN(from)) request.fromRow = from;
2240
+ if (!isNaN(to)) request.toRow = to;
2241
+ }
2242
+ if (options.cols) {
2243
+ const [from, to] = options.cols.split(":").map(Number);
2244
+ if (!isNaN(from)) request.fromColumn = from;
2245
+ if (!isNaN(to)) request.toColumn = to;
2246
+ }
2247
+ const snapshot = await api.storage.getTableSnapshot(resolved, request);
2248
+ if (outputFormat === "json") {
2249
+ format(snapshot, { format: outputFormat });
2250
+ return;
2251
+ }
2252
+ const colMap = new Map(snapshot.columns.map((c) => [c.index, c]));
2253
+ const sortedCols = [...snapshot.columns].sort((a, b) => a.index - b.index);
2254
+ const colNames = sortedCols.map((c) => c.name || `col${c.index}`);
2255
+ const cellMap = /* @__PURE__ */ new Map();
2256
+ for (const cell2 of snapshot.cells) {
2257
+ cellMap.set(`${cell2.rowIndex}:${cell2.columnIndex}`, cell2.value ?? "");
2258
+ }
2259
+ const sortedRows = [...snapshot.rows].sort((a, b) => a.index - b.index);
2260
+ const tableData = sortedRows.map((row2) => {
2261
+ const obj = {};
2262
+ for (const col of sortedCols) {
2263
+ obj[col.name || `col${col.index}`] = cellMap.get(`${row2.index}:${col.index}`) ?? "";
2264
+ }
2265
+ return obj;
2266
+ });
2267
+ if (outputFormat === "table") {
2268
+ console.log(colNames.join(" "));
2269
+ for (const row2 of tableData) {
2270
+ console.log(colNames.map((c) => row2[c] ?? "").join(" "));
2271
+ }
2272
+ } else {
2273
+ console.log(chalk13.dim(`${snapshot.rows.length} rows \xD7 ${snapshot.columns.length} columns`));
2274
+ format(tableData, { format: outputFormat, columns: colNames });
2275
+ }
2276
+ } catch (error) {
2277
+ handleError(error);
2278
+ }
2279
+ });
2280
+ table.command("import").description("Import data from a CSV or Excel file").argument("<ref>", "Table entity reference").argument("<file>", "File to import (CSV or Excel)").option("--no-column-headers", "File does not have column headers").action(async (ref, file, options, cmd) => {
2281
+ try {
2282
+ const overrides = getOverrides5(cmd);
2283
+ const resolved = parseEntityReference(ref, overrides);
2284
+ if (!fs3.existsSync(file)) {
2285
+ console.error(chalk13.red(`File not found: ${file}`));
2286
+ process.exit(1);
2287
+ }
2288
+ const api = createApiClient();
2289
+ const fileBuffer = fs3.readFileSync(file);
2290
+ const blob = new Blob([fileBuffer]);
2291
+ const formData = new FormData();
2292
+ formData.append("content", blob, path2.basename(file));
2293
+ const columnHeaders = options.columnHeaders !== false;
2294
+ console.log(`Importing ${path2.basename(file)} ...`);
2295
+ const importId = await api.storage.importTable(resolved, formData, columnHeaders);
2296
+ console.log(`Import started (ID: ${importId}). Waiting for completion ...`);
2297
+ const pollInterval = 1e3;
2298
+ const maxAttempts = 300;
2299
+ for (let i = 0; i < maxAttempts; i++) {
2300
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
2301
+ const imp = await api.storage.getImport(resolved, importId);
2302
+ if (imp.finished !== null) {
2303
+ if (imp.succeeded) {
2304
+ console.log(chalk13.green(`Import completed successfully (${imp.duration}ms).`));
2305
+ } else {
2306
+ console.error(chalk13.red(`Import failed: ${imp.error}`));
2307
+ process.exit(1);
2308
+ }
2309
+ return;
2310
+ }
2311
+ }
2312
+ console.error(chalk13.yellow("Import still in progress. Check status later."));
2313
+ } catch (error) {
2314
+ handleError(error);
2315
+ }
2316
+ });
2317
+ table.command("export").description("Export table data").argument("<ref>", "Table entity reference").argument("<format>", "Export format: csv or excel").option("--out <file>", "Output file").action(async (ref, fmt, options, cmd) => {
2318
+ try {
2319
+ const overrides = getOverrides5(cmd);
2320
+ const resolved = parseEntityReference(ref, overrides);
2321
+ const api = createApiClient();
2322
+ let response;
2323
+ let defaultExt;
2324
+ if (fmt.toLowerCase() === "csv") {
2325
+ response = await api.storage.exportTableCsv(resolved);
2326
+ defaultExt = ".csv";
2327
+ } else if (fmt.toLowerCase() === "excel" || fmt.toLowerCase() === "xlsx") {
2328
+ response = await api.storage.exportTableExcel(resolved);
2329
+ defaultExt = ".xlsx";
2330
+ } else {
2331
+ console.error(chalk13.red(`Unknown format: "${fmt}". Use "csv" or "excel".`));
2332
+ process.exit(1);
2333
+ }
2334
+ const outFile = options.out ?? `${resolved.entityId}${defaultExt}`;
2335
+ const buffer = Buffer.from(await response.arrayBuffer());
2336
+ fs3.writeFileSync(outFile, buffer);
2337
+ console.log(chalk13.green(`Table exported to ${outFile}`));
2338
+ } catch (error) {
2339
+ handleError(error);
2340
+ }
2341
+ });
2342
+ const row = table.command("row").description("Manage table rows");
2343
+ row.command("add").description("Append a row to a table").argument("<ref>", "Table entity reference").action(async (ref, _options, cmd) => {
2344
+ try {
2345
+ const overrides = getOverrides5(cmd);
2346
+ const resolved = parseEntityReference(ref, overrides);
2347
+ const api = createApiClient();
2348
+ await api.storage.appendRow(resolved);
2349
+ console.log(chalk13.green("Row appended."));
2350
+ } catch (error) {
2351
+ handleError(error);
2352
+ }
2353
+ });
2354
+ row.command("remove").description("Remove a row from a table").argument("<ref>", "Table entity reference").argument("<index>", "Row index").action(async (ref, index, _options, cmd) => {
2355
+ try {
2356
+ const overrides = getOverrides5(cmd);
2357
+ const resolved = parseEntityReference(ref, overrides);
2358
+ const api = createApiClient();
2359
+ await api.storage.deleteRow(resolved, parseInt(index, 10));
2360
+ console.log(chalk13.green(`Row ${index} removed.`));
2361
+ } catch (error) {
2362
+ handleError(error);
2363
+ }
2364
+ });
2365
+ const column = table.command("column").description("Manage table columns");
2366
+ column.command("add").description("Append a column to a table").argument("<ref>", "Table entity reference").action(async (ref, _options, cmd) => {
2367
+ try {
2368
+ const overrides = getOverrides5(cmd);
2369
+ const resolved = parseEntityReference(ref, overrides);
2370
+ const api = createApiClient();
2371
+ await api.storage.appendColumn(resolved);
2372
+ console.log(chalk13.green("Column appended."));
2373
+ } catch (error) {
2374
+ handleError(error);
2375
+ }
2376
+ });
2377
+ column.command("remove").description("Remove a column from a table").argument("<ref>", "Table entity reference").argument("<index>", "Column index").action(async (ref, index, _options, cmd) => {
2378
+ try {
2379
+ const overrides = getOverrides5(cmd);
2380
+ const resolved = parseEntityReference(ref, overrides);
2381
+ const api = createApiClient();
2382
+ await api.storage.deleteColumn(resolved, parseInt(index, 10));
2383
+ console.log(chalk13.green(`Column ${index} removed.`));
2384
+ } catch (error) {
2385
+ handleError(error);
2386
+ }
2387
+ });
2388
+ const cell = table.command("cell").description("Manage table cells");
2389
+ cell.command("set").description("Set a cell value").argument("<ref>", "Table entity reference").argument("<row>", "Row index").argument("<col>", "Column index").argument("<value>", "Cell value").action(async (ref, row2, col, value, _options, cmd) => {
2390
+ try {
2391
+ const overrides = getOverrides5(cmd);
2392
+ const resolved = parseEntityReference(ref, overrides);
2393
+ const api = createApiClient();
2394
+ await api.storage.mergeCells(resolved, [{
2395
+ rowIndex: parseInt(row2, 10),
2396
+ columnIndex: parseInt(col, 10),
2397
+ value,
2398
+ type: "text"
2399
+ }]);
2400
+ console.log(chalk13.green(`Cell [${row2}, ${col}] set to "${value}".`));
2401
+ } catch (error) {
2402
+ handleError(error);
2403
+ }
2404
+ });
2405
+ cell.command("delete").description("Delete a cell value").argument("<ref>", "Table entity reference").argument("<row>", "Row index").argument("<col>", "Column index").action(async (ref, row2, col, _options, cmd) => {
2406
+ try {
2407
+ const overrides = getOverrides5(cmd);
2408
+ const resolved = parseEntityReference(ref, overrides);
2409
+ const api = createApiClient();
2410
+ await api.storage.deleteCell(resolved, parseInt(row2, 10), parseInt(col, 10));
2411
+ console.log(chalk13.green(`Cell [${row2}, ${col}] deleted.`));
2412
+ } catch (error) {
2413
+ handleError(error);
2414
+ }
2415
+ });
2416
+ table.command("clear").description("Clear all data from a table").argument("<ref>", "Table entity reference").action(async (ref, _options, cmd) => {
2417
+ try {
2418
+ const overrides = getOverrides5(cmd);
2419
+ const resolved = parseEntityReference(ref, overrides);
2420
+ const api = createApiClient();
2421
+ await api.storage.clearTable(resolved);
2422
+ console.log(chalk13.green("Table cleared."));
2423
+ } catch (error) {
2424
+ handleError(error);
2425
+ }
2426
+ });
2427
+ }
2428
+
2429
+ // src/commands/function/index.ts
2430
+ import chalk14 from "chalk";
2431
+ import { randomUUID } from "crypto";
2432
+ function getOutputFormat7(cmd) {
2433
+ const config = loadConfig();
2434
+ const globalOpts = cmd.optsWithGlobals();
2435
+ return globalOpts.output ?? config.defaults.output ?? "human";
2436
+ }
2437
+ function getOverrides6(cmd) {
2438
+ const opts = cmd.optsWithGlobals();
2439
+ return { project: opts.project, branch: opts.branch };
2440
+ }
2441
+ function createTimeUuid() {
2442
+ const now = /* @__PURE__ */ new Date();
2443
+ return {
2444
+ evaluationId: randomUUID(),
2445
+ year: now.getUTCFullYear(),
2446
+ month: now.getUTCMonth() + 1,
2447
+ day: now.getUTCDate(),
2448
+ hour: now.getUTCHours()
2449
+ };
2450
+ }
2451
+ function registerFunctionCommands(program) {
2452
+ const fn = program.command("function").description("Execute and manage functions");
2453
+ fn.command("call").description("Execute a function").argument("<ref>", "Function entity reference").option("--async", "Execute asynchronously").option("--args <json>", "Arguments as JSON object").option("--target <ref>", "Target entity reference").action(async (ref, options, cmd) => {
2454
+ try {
2455
+ const outputFormat = getOutputFormat7(cmd);
2456
+ const overrides = getOverrides6(cmd);
2457
+ const resolved = parseEntityReference(ref, overrides);
2458
+ const api = createApiClient();
2459
+ const time = createTimeUuid();
2460
+ let args = null;
2461
+ let types = null;
2462
+ if (options.args) {
2463
+ args = JSON.parse(options.args);
2464
+ types = {};
2465
+ for (const [key, value] of Object.entries(args)) {
2466
+ if (typeof value === "number") types[key] = "number";
2467
+ else if (typeof value === "boolean") types[key] = "bool";
2468
+ else types[key] = "string";
2469
+ }
2470
+ }
2471
+ let targetEntityId = null;
2472
+ let targetEntityBranch = null;
2473
+ if (options.target) {
2474
+ const targetRef = parseEntityReference(options.target, overrides);
2475
+ targetEntityId = targetRef.entityId;
2476
+ targetEntityBranch = targetRef.entityBranch;
2477
+ }
2478
+ const isAsync = !!options.async;
2479
+ if (isAsync && outputFormat === "human") {
2480
+ console.log("Launching function asynchronously ...");
2481
+ }
2482
+ const result = await api.evaluation.call({
2483
+ evaluationId: time.evaluationId,
2484
+ projectId: resolved.projectId,
2485
+ projectBranch: resolved.projectBranch,
2486
+ functionId: resolved.entityId,
2487
+ functionBranch: resolved.entityBranch,
2488
+ targetEntityId,
2489
+ targetEntityBranch,
2490
+ arguments: args,
2491
+ types,
2492
+ requested: Date.now(),
2493
+ provideOutputs: true,
2494
+ removeFunction: false
2495
+ }, isAsync);
2496
+ if (isAsync) {
2497
+ if (outputFormat === "human") {
2498
+ console.log(chalk14.green("Function launched."));
2499
+ console.log(` Evaluation ID: ${result.evaluationId}`);
2500
+ } else {
2501
+ format({ evaluationId: result.evaluationId }, { format: outputFormat });
2502
+ }
2503
+ } else {
2504
+ if (outputFormat === "human") {
2505
+ if (result.successful) {
2506
+ console.log(chalk14.green("Function completed successfully."));
2507
+ if (result.result) {
2508
+ console.log(` Result: ${result.result}`);
2509
+ }
2510
+ const duration = result.completed - result.started;
2511
+ console.log(` Duration: ${duration}ms`);
2512
+ } else {
2513
+ console.log(chalk14.red("Function failed."));
2514
+ console.log(` Error: ${result.error}`);
2515
+ if (result.lineNumber > 0) {
2516
+ console.log(` Line: ${result.lineNumber}, Column: ${result.columnNumber}`);
2517
+ }
2518
+ }
2519
+ if (result.outputs?.length) {
2520
+ console.log();
2521
+ console.log(chalk14.bold("Outputs:"));
2522
+ for (const out of result.outputs) {
2523
+ console.log(` [${out.type}] ${out.output}`);
2524
+ }
2525
+ }
2526
+ } else {
2527
+ format(result, { format: outputFormat });
2528
+ }
2529
+ }
2530
+ } catch (error) {
2531
+ handleError(error);
2532
+ }
2533
+ });
2534
+ fn.command("evaluations").description("List evaluations for a function").argument("<ref>", "Function entity reference").requiredOption("--date <date>", "Date and hour (YYYY-MM-DD-HH in UTC)").action(async (ref, options, cmd) => {
2535
+ try {
2536
+ const outputFormat = getOutputFormat7(cmd);
2537
+ const overrides = getOverrides6(cmd);
2538
+ const resolved = parseEntityReference(ref, overrides);
2539
+ const api = createApiClient();
2540
+ const parts = options.date.split("-").map(Number);
2541
+ const [year, month, day, hour] = parts;
2542
+ const evaluations = await api.evaluation.getEvaluations(
2543
+ resolved.projectId,
2544
+ resolved.projectBranch,
2545
+ resolved.entityId,
2546
+ resolved.entityBranch,
2547
+ year,
2548
+ month,
2549
+ day,
2550
+ hour
2551
+ );
2552
+ const summary = evaluations.map((e) => ({
2553
+ evaluationId: e.evaluationId,
2554
+ active: e.active,
2555
+ successful: e.successful,
2556
+ language: e.language,
2557
+ started: e.started ? new Date(e.started).toISOString() : "\u2014",
2558
+ duration: e.completed && e.started ? `${e.completed - e.started}ms` : "\u2014"
2559
+ }));
2560
+ format(summary, {
2561
+ format: outputFormat,
2562
+ columns: ["evaluationId", "active", "successful", "language", "started", "duration"]
2563
+ });
2564
+ } catch (error) {
2565
+ handleError(error);
2566
+ }
2567
+ });
2568
+ fn.command("outputs").description("Get outputs for an evaluation").argument("<projectId>", "Project ID").argument("<evaluationId>", "Evaluation ID").action(async (projectId, evaluationId, _options, cmd) => {
2569
+ try {
2570
+ const outputFormat = getOutputFormat7(cmd);
2571
+ const api = createApiClient();
2572
+ const outputs = await api.evaluation.getOutputs(projectId, evaluationId);
2573
+ if (outputFormat === "human") {
2574
+ if (outputs.length === 0) {
2575
+ console.log(chalk14.dim("No outputs."));
2576
+ }
2577
+ for (const out of outputs) {
2578
+ const time = new Date(out.timestamp).toISOString();
2579
+ console.log(`${chalk14.dim(time)} [${out.type}] ${out.output}`);
2580
+ }
2581
+ } else {
2582
+ format(outputs, { format: outputFormat });
2583
+ }
2584
+ } catch (error) {
2585
+ handleError(error);
2586
+ }
2587
+ });
2588
+ fn.command("logs").description("Get logs for a function evaluation").argument("<ref>", "Function entity reference").requiredOption("--date <date>", "Date and hour (YYYY-MM-DD-HH in UTC)").action(async (ref, options, cmd) => {
2589
+ try {
2590
+ const outputFormat = getOutputFormat7(cmd);
2591
+ const overrides = getOverrides6(cmd);
2592
+ const resolved = parseEntityReference(ref, overrides);
2593
+ const api = createApiClient();
2594
+ const parts = options.date.split("-").map(Number);
2595
+ const [year, month, day, hour] = parts;
2596
+ const logs = await api.evaluation.getLogs(
2597
+ resolved.projectId,
2598
+ resolved.projectBranch,
2599
+ resolved.entityId,
2600
+ resolved.entityBranch,
2601
+ year,
2602
+ month,
2603
+ day,
2604
+ hour
2605
+ );
2606
+ format(logs, { format: outputFormat });
2607
+ } catch (error) {
2608
+ handleError(error);
2609
+ }
2610
+ });
2611
+ fn.command("stop").description("Stop a running evaluation").argument("<ref>", "Function entity reference").requiredOption("--date <date>", "Date and hour (YYYY-MM-DD-HH in UTC)").argument("<evaluationId>", "Evaluation ID").action(async (ref, evaluationId, options, cmd) => {
2612
+ try {
2613
+ const overrides = getOverrides6(cmd);
2614
+ const resolved = parseEntityReference(ref, overrides);
2615
+ const api = createApiClient();
2616
+ const parts = options.date.split("-").map(Number);
2617
+ const [year, month, day, hour] = parts;
2618
+ await api.evaluation.stopEvaluation(
2619
+ resolved.projectId,
2620
+ resolved.projectBranch,
2621
+ resolved.entityId,
2622
+ resolved.entityBranch,
2623
+ year,
2624
+ month,
2625
+ day,
2626
+ hour,
2627
+ evaluationId
2628
+ );
2629
+ console.log(chalk14.green(`Evaluation ${evaluationId} stopped.`));
2630
+ } catch (error) {
2631
+ handleError(error);
2632
+ }
2633
+ });
2634
+ fn.command("engines").description("List available engines").action(async (_options, cmd) => {
2635
+ try {
2636
+ const outputFormat = getOutputFormat7(cmd);
2637
+ const api = createApiClient();
2638
+ const engines = await api.evaluation.getEngines();
2639
+ format(engines, { format: outputFormat });
2640
+ } catch (error) {
2641
+ handleError(error);
2642
+ }
2643
+ });
2644
+ }
2645
+
2646
+ // src/commands/trigger/index.ts
2647
+ import chalk15 from "chalk";
2648
+ function getOutputFormat8(cmd) {
2649
+ const config = loadConfig();
2650
+ const globalOpts = cmd.optsWithGlobals();
2651
+ return globalOpts.output ?? config.defaults.output ?? "human";
2652
+ }
2653
+ function getOverrides7(cmd) {
2654
+ const opts = cmd.optsWithGlobals();
2655
+ return { project: opts.project, branch: opts.branch };
2656
+ }
2657
+ function registerTriggerCommands(program) {
2658
+ const trigger = program.command("trigger").description("Manage function triggers");
2659
+ trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
2660
+ try {
2661
+ const outputFormat = getOutputFormat8(cmd);
2662
+ const overrides = getOverrides7(cmd);
2663
+ const resolved = parseEntityReference(ref, overrides);
2664
+ const api = createApiClient();
2665
+ const triggers = await api.evaluation.getTriggers(
2666
+ resolved.projectId,
2667
+ resolved.projectBranch,
2668
+ resolved.entityId,
2669
+ resolved.entityBranch
2670
+ );
2671
+ const summary = triggers.map((t) => ({
2672
+ triggerId: t.triggerId,
2673
+ type: t.type,
2674
+ active: t.active,
2675
+ expression: t.expression ?? "\u2014",
2676
+ fired: t.fired,
2677
+ persistent: t.persistent
2678
+ }));
2679
+ format(summary, {
2680
+ format: outputFormat,
2681
+ columns: ["triggerId", "type", "active", "expression", "fired", "persistent"]
2682
+ });
2683
+ } catch (error) {
2684
+ handleError(error);
2685
+ }
2686
+ });
2687
+ trigger.command("get").description("Get a specific trigger").argument("<ref>", "Function entity reference").argument("<triggerId>", "Trigger ID").action(async (ref, triggerId, _options, cmd) => {
2688
+ try {
2689
+ const outputFormat = getOutputFormat8(cmd);
2690
+ const overrides = getOverrides7(cmd);
2691
+ const resolved = parseEntityReference(ref, overrides);
2692
+ const api = createApiClient();
2693
+ const t = await api.evaluation.getTrigger(
2694
+ resolved.projectId,
2695
+ resolved.projectBranch,
2696
+ resolved.entityId,
2697
+ resolved.entityBranch,
2698
+ triggerId
2699
+ );
2700
+ format(t, { format: outputFormat });
2701
+ } catch (error) {
2702
+ handleError(error);
2703
+ }
2704
+ });
2705
+ trigger.command("delete").description("Delete a trigger").argument("<ref>", "Function entity reference").argument("<triggerId>", "Trigger ID").action(async (ref, triggerId, _options, cmd) => {
2706
+ try {
2707
+ const overrides = getOverrides7(cmd);
2708
+ const resolved = parseEntityReference(ref, overrides);
2709
+ const api = createApiClient();
2710
+ await api.evaluation.deleteTrigger(
2711
+ resolved.projectId,
2712
+ resolved.projectBranch,
2713
+ resolved.entityId,
2714
+ resolved.entityBranch,
2715
+ triggerId
2716
+ );
2717
+ console.log(chalk15.green(`Trigger "${triggerId}" deleted.`));
2718
+ } catch (error) {
2719
+ handleError(error);
2720
+ }
2721
+ });
2722
+ }
2723
+
2724
+ // src/commands/schedule/index.ts
2725
+ import chalk16 from "chalk";
2726
+ import { randomUUID as randomUUID2 } from "crypto";
2727
+ function getOutputFormat9(cmd) {
2728
+ const config = loadConfig();
2729
+ const globalOpts = cmd.optsWithGlobals();
2730
+ return globalOpts.output ?? config.defaults.output ?? "human";
2731
+ }
2732
+ function getOverrides8(cmd) {
2733
+ const opts = cmd.optsWithGlobals();
2734
+ return { project: opts.project, branch: opts.branch };
2735
+ }
2736
+ function registerScheduleCommands(program) {
2737
+ const schedule = program.command("schedule").description("Schedule function execution");
2738
+ schedule.command("call").description("Schedule a function call").argument("<ref>", "Function entity reference").option("--args <json>", "Arguments as JSON object").option("--target <ref>", "Target entity reference").action(async (ref, options, cmd) => {
2739
+ try {
2740
+ const outputFormat = getOutputFormat9(cmd);
2741
+ const overrides = getOverrides8(cmd);
2742
+ const resolved = parseEntityReference(ref, overrides);
2743
+ const api = createApiClient();
2744
+ let args = null;
2745
+ let types = null;
2746
+ if (options.args) {
2747
+ args = JSON.parse(options.args);
2748
+ types = {};
2749
+ for (const [key, value] of Object.entries(args)) {
2750
+ if (typeof value === "number") types[key] = "number";
2751
+ else if (typeof value === "boolean") types[key] = "bool";
2752
+ else types[key] = "string";
2753
+ }
2754
+ }
2755
+ let targetEntityId = null;
2756
+ let targetEntityBranch = null;
2757
+ if (options.target) {
2758
+ const targetRef = parseEntityReference(options.target, overrides);
2759
+ targetEntityId = targetRef.entityId;
2760
+ targetEntityBranch = targetRef.entityBranch;
2761
+ }
2762
+ const result = await api.scheduler.scheduleCall({
2763
+ evaluationId: randomUUID2(),
2764
+ projectId: resolved.projectId,
2765
+ projectBranch: resolved.projectBranch,
2766
+ functionId: resolved.entityId,
2767
+ functionBranch: resolved.entityBranch,
2768
+ targetEntityId,
2769
+ targetEntityBranch,
2770
+ arguments: args,
2771
+ types,
2772
+ requested: Date.now(),
2773
+ provideOutputs: true,
2774
+ removeFunction: false
2775
+ });
2776
+ if (outputFormat === "human") {
2777
+ console.log(chalk16.green("Function scheduled."));
2778
+ } else {
2779
+ format(result, { format: outputFormat });
2780
+ }
2781
+ } catch (error) {
2782
+ handleError(error);
2783
+ }
2784
+ });
2785
+ }
2786
+
2787
+ // src/commands/chat/index.ts
2788
+ import chalk17 from "chalk";
2789
+ import * as fs4 from "fs";
2790
+ import * as path3 from "path";
2791
+ function getOutputFormat10(cmd) {
2792
+ const config = loadConfig();
2793
+ const globalOpts = cmd.optsWithGlobals();
2794
+ return globalOpts.output ?? config.defaults.output ?? "human";
2795
+ }
2796
+ function registerChatCommands(program) {
2797
+ const chat = program.command("chat").description("AI chat");
2798
+ chat.command("send").description("Send a chat message (blocking)").argument("<message>", "Message to send").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
2799
+ try {
2800
+ const outputFormat = getOutputFormat10(cmd);
2801
+ const api = createApiClient();
2802
+ const response = await api.language.chat({
2803
+ message,
2804
+ sessionId: options.session,
2805
+ projectId: options.project,
2806
+ projectBranch: options.branch
2807
+ });
2808
+ if (outputFormat === "human") {
2809
+ console.log(response.content);
2810
+ console.log();
2811
+ console.log(chalk17.dim(`Session: ${response.sessionId} | Tokens: ${response.inputTokens} in, ${response.outputTokens} out`));
2812
+ } else {
2813
+ format(response, { format: outputFormat });
2814
+ }
2815
+ } catch (error) {
2816
+ handleError(error);
2817
+ }
2818
+ });
2819
+ chat.command("stream").description("Send a chat message (streaming)").argument("<message>", "Message to send").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
2820
+ try {
2821
+ const outputFormat = getOutputFormat10(cmd);
2822
+ const api = createApiClient();
2823
+ const response = await api.language.chatStream({
2824
+ message,
2825
+ sessionId: options.session,
2826
+ projectId: options.project,
2827
+ projectBranch: options.branch
2828
+ });
2829
+ if (outputFormat === "json") {
2830
+ const events = [];
2831
+ const reader = response.body.getReader();
2832
+ const decoder = new TextDecoder();
2833
+ let buffer = "";
2834
+ while (true) {
2835
+ const { done, value } = await reader.read();
2836
+ if (done) break;
2837
+ buffer += decoder.decode(value, { stream: true });
2838
+ const lines = buffer.split("\n");
2839
+ buffer = lines.pop() ?? "";
2840
+ for (const line of lines) {
2841
+ if (line.startsWith("data:")) {
2842
+ const data = line.slice(5).trim();
2843
+ if (data) {
2844
+ try {
2845
+ events.push(JSON.parse(data));
2846
+ } catch {
2847
+ }
2848
+ }
2849
+ }
2850
+ }
2851
+ }
2852
+ format(events, { format: "json" });
2853
+ } else {
2854
+ const reader = response.body.getReader();
2855
+ const decoder = new TextDecoder();
2856
+ let buffer = "";
2857
+ let sessionId = "";
2858
+ while (true) {
2859
+ const { done, value } = await reader.read();
2860
+ if (done) break;
2861
+ buffer += decoder.decode(value, { stream: true });
2862
+ const lines = buffer.split("\n");
2863
+ buffer = lines.pop() ?? "";
2864
+ for (const line of lines) {
2865
+ if (line.startsWith("data:")) {
2866
+ const data = line.slice(5).trim();
2867
+ if (!data) continue;
2868
+ try {
2869
+ const event = JSON.parse(data);
2870
+ if (event.type === "token" && event.content) {
2871
+ process.stdout.write(event.content);
2872
+ } else if (event.type === "done") {
2873
+ sessionId = event.sessionId ?? "";
2874
+ console.log();
2875
+ console.log();
2876
+ console.log(chalk17.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
2877
+ } else if (event.type === "error") {
2878
+ console.error(chalk17.red(`
2879
+ Error: ${event.content}`));
2880
+ }
2881
+ } catch {
2882
+ }
2883
+ }
2884
+ }
2885
+ }
2886
+ }
2887
+ } catch (error) {
2888
+ handleError(error);
2889
+ }
2890
+ });
2891
+ chat.command("upload").description("Upload a file for chat context").argument("<file>", "File to upload").action(async (file) => {
2892
+ try {
2893
+ if (!fs4.existsSync(file)) {
2894
+ console.error(chalk17.red(`File not found: ${file}`));
2895
+ process.exit(1);
2896
+ }
2897
+ const api = createApiClient();
2898
+ const fileBuffer = fs4.readFileSync(file);
2899
+ const blob = new Blob([fileBuffer]);
2900
+ const formData = new FormData();
2901
+ formData.append("file", blob, path3.basename(file));
2902
+ const result = await api.language.upload(formData);
2903
+ console.log(chalk17.green(`File uploaded: ${result}`));
2904
+ } catch (error) {
2905
+ handleError(error);
2906
+ }
2907
+ });
2908
+ const session = chat.command("session").description("Manage chat sessions");
2909
+ session.command("list").description("List chat sessions").action(async (_options, cmd) => {
2910
+ try {
2911
+ const outputFormat = getOutputFormat10(cmd);
2912
+ const api = createApiClient();
2913
+ const sessions = await api.language.getSessions();
2914
+ format(sessions, {
2915
+ format: outputFormat,
2916
+ columns: ["sessionId", "title", "projectId", "modified"]
2917
+ });
2918
+ } catch (error) {
2919
+ handleError(error);
2920
+ }
2921
+ });
2922
+ session.command("delete").description("Delete a chat session").argument("<sessionId>", "Session ID").action(async (sessionId) => {
2923
+ try {
2924
+ const api = createApiClient();
2925
+ await api.language.deleteSession(sessionId);
2926
+ console.log(chalk17.green(`Session "${sessionId}" deleted.`));
2927
+ } catch (error) {
2928
+ handleError(error);
2929
+ }
2930
+ });
2931
+ chat.command("usage").description("Show token usage").action(async (_options, cmd) => {
2932
+ try {
2933
+ const outputFormat = getOutputFormat10(cmd);
2934
+ const api = createApiClient();
2935
+ const usage = await api.language.getUsage();
2936
+ format(usage, { format: outputFormat });
2937
+ } catch (error) {
2938
+ handleError(error);
2939
+ }
2940
+ });
2941
+ }
2942
+
2943
+ // src/commands/search/index.ts
2944
+ function getOutputFormat11(cmd) {
2945
+ const config = loadConfig();
2946
+ const globalOpts = cmd.optsWithGlobals();
2947
+ return globalOpts.output ?? config.defaults.output ?? "human";
2948
+ }
2949
+ function registerSearchCommands(program) {
2950
+ program.command("search").description("Search entities across projects").argument("<query>", "Search query").option("--project <id>", "Limit search to a project").option("--branch <branch>", "Project branch", "main").action(async (query, options, cmd) => {
2951
+ try {
2952
+ const outputFormat = getOutputFormat11(cmd);
2953
+ const api = createApiClient();
2954
+ if (options.project) {
2955
+ const results = await api.storage.searchProject(
2956
+ options.project,
2957
+ options.branch,
2958
+ { query }
2959
+ );
2960
+ format(results, { format: outputFormat });
2961
+ } else {
2962
+ const config = loadConfig();
2963
+ const overrides = cmd.optsWithGlobals();
2964
+ const projectId = overrides.project ?? config.defaults.project;
2965
+ if (projectId) {
2966
+ const results = await api.storage.searchProject(
2967
+ projectId,
2968
+ options.branch,
2969
+ { query }
2970
+ );
2971
+ format(results, { format: outputFormat });
2972
+ } else {
2973
+ console.log("Specify --project or set defaults.project for project-scoped search.");
2974
+ }
2975
+ }
2976
+ } catch (error) {
2977
+ handleError(error);
2978
+ }
2979
+ });
2980
+ }
2981
+
2982
+ // src/commands/group/index.ts
2983
+ import chalk18 from "chalk";
2984
+ function getOutputFormat12(cmd) {
2985
+ const config = loadConfig();
2986
+ const globalOpts = cmd.optsWithGlobals();
2987
+ return globalOpts.output ?? config.defaults.output ?? "human";
2988
+ }
2989
+ function registerGroupCommands(program) {
2990
+ const group = program.command("group").description("Manage groups");
2991
+ group.command("list").description("List groups").option("--all", "List all groups (admin)").action(async (options, cmd) => {
2992
+ try {
2993
+ const outputFormat = getOutputFormat12(cmd);
2994
+ const api = createApiClient();
2995
+ const groups = options.all ? await api.admin.getAllGroups() : await api.admin.getGroups();
2996
+ format(groups, { format: outputFormat, columns: ["groupId", "name"] });
2997
+ } catch (error) {
2998
+ handleError(error);
2999
+ }
3000
+ });
3001
+ group.command("get").description("Get group details").argument("<groupId>", "Group ID").action(async (groupId, _options, cmd) => {
3002
+ try {
3003
+ const outputFormat = getOutputFormat12(cmd);
3004
+ const api = createApiClient();
3005
+ const g = await api.admin.getGroup(groupId);
3006
+ format(g, { format: outputFormat });
3007
+ } catch (error) {
3008
+ handleError(error);
3009
+ }
3010
+ });
3011
+ group.command("create").description("Create a new group").argument("<groupId>", "Group ID").option("--name <name>", "Group name").action(async (groupId, options) => {
3012
+ try {
3013
+ const api = createApiClient();
3014
+ await api.admin.createGroup({ groupId, name: options.name ?? groupId });
3015
+ console.log(chalk18.green(`Group "${groupId}" created.`));
3016
+ } catch (error) {
3017
+ handleError(error);
3018
+ }
3019
+ });
3020
+ group.command("delete").description("Delete a group").argument("<groupId>", "Group ID").action(async (groupId) => {
3021
+ try {
3022
+ const api = createApiClient();
3023
+ await api.admin.deleteGroup(groupId);
3024
+ console.log(chalk18.green(`Group "${groupId}" deleted.`));
3025
+ } catch (error) {
3026
+ handleError(error);
3027
+ }
3028
+ });
3029
+ const members = group.command("members").description("Manage group members");
3030
+ members.command("list").description("List group members").argument("<groupId>", "Group ID").action(async (groupId, _options, cmd) => {
3031
+ try {
3032
+ const outputFormat = getOutputFormat12(cmd);
3033
+ const api = createApiClient();
3034
+ const memberList = await api.admin.getGroupMembers(groupId);
3035
+ format(memberList, { format: outputFormat, columns: ["userId", "role", "joined"] });
3036
+ } catch (error) {
3037
+ handleError(error);
3038
+ }
3039
+ });
3040
+ members.command("invite").description("Invite a user to a group").argument("<groupId>", "Group ID").argument("<userId>", "User ID").argument("<role>", "Role").action(async (groupId, userId, role) => {
3041
+ try {
3042
+ const api = createApiClient();
3043
+ await api.admin.inviteGroupMember(groupId, userId, role.toUpperCase());
3044
+ console.log(chalk18.green(`Invited ${userId} to group "${groupId}" as ${role.toUpperCase()}.`));
3045
+ } catch (error) {
3046
+ handleError(error);
3047
+ }
3048
+ });
3049
+ members.command("remove").description("Remove a member from a group").argument("<groupId>", "Group ID").argument("<userId>", "User ID").action(async (groupId, userId) => {
3050
+ try {
3051
+ const api = createApiClient();
3052
+ await api.admin.removeGroupMember(groupId, userId);
3053
+ console.log(chalk18.green(`Removed ${userId} from group "${groupId}".`));
3054
+ } catch (error) {
3055
+ handleError(error);
3056
+ }
3057
+ });
3058
+ const projects = group.command("projects").description("Manage group projects");
3059
+ projects.command("list").description("List group projects").argument("<groupId>", "Group ID").action(async (groupId, _options, cmd) => {
3060
+ try {
3061
+ const outputFormat = getOutputFormat12(cmd);
3062
+ const api = createApiClient();
3063
+ const projectList = await api.admin.getGroupProjects(groupId);
3064
+ format(projectList, { format: outputFormat, columns: ["projectId", "visibility", "language"] });
3065
+ } catch (error) {
3066
+ handleError(error);
3067
+ }
3068
+ });
3069
+ projects.command("add").description("Add a project to a group").argument("<groupId>", "Group ID").argument("<projectId>", "Project ID").action(async (groupId, projectId) => {
3070
+ try {
3071
+ const api = createApiClient();
3072
+ await api.admin.addGroupProject(groupId, projectId);
3073
+ console.log(chalk18.green(`Project "${projectId}" added to group "${groupId}".`));
3074
+ } catch (error) {
3075
+ handleError(error);
3076
+ }
3077
+ });
3078
+ projects.command("remove").description("Remove a project from a group").argument("<groupId>", "Group ID").argument("<projectId>", "Project ID").action(async (groupId, projectId) => {
3079
+ try {
3080
+ const api = createApiClient();
3081
+ await api.admin.removeGroupProject(groupId, projectId);
3082
+ console.log(chalk18.green(`Project "${projectId}" removed from group "${groupId}".`));
3083
+ } catch (error) {
3084
+ handleError(error);
3085
+ }
3086
+ });
3087
+ }
3088
+
3089
+ // src/commands/admin/index.ts
3090
+ import chalk19 from "chalk";
3091
+ function getOutputFormat13(cmd) {
3092
+ const config = loadConfig();
3093
+ const globalOpts = cmd.optsWithGlobals();
3094
+ return globalOpts.output ?? config.defaults.output ?? "human";
3095
+ }
3096
+ function registerAdminCommands(program) {
3097
+ const admin = program.command("admin").description("Administration commands");
3098
+ const users = admin.command("users").description("Manage users");
3099
+ users.command("list").description("List all users (admin)").action(async (_options, cmd) => {
3100
+ try {
3101
+ const outputFormat = getOutputFormat13(cmd);
3102
+ const api = createApiClient();
3103
+ const userList = await api.admin.getUsers();
3104
+ const summary = userList.map((u) => ({
3105
+ id: u.id,
3106
+ name: u.name,
3107
+ email: u.email,
3108
+ role: u.role,
3109
+ remainingCredits: u.remainingCredits
3110
+ }));
3111
+ format(summary, {
3112
+ format: outputFormat,
3113
+ columns: ["id", "name", "email", "role", "remainingCredits"]
3114
+ });
3115
+ } catch (error) {
3116
+ handleError(error);
3117
+ }
3118
+ });
3119
+ users.command("get").description("Get current user details").action(async (_options, cmd) => {
3120
+ try {
3121
+ const outputFormat = getOutputFormat13(cmd);
3122
+ const api = createApiClient();
3123
+ const user = await api.admin.getMyUser();
3124
+ format(user, { format: outputFormat });
3125
+ } catch (error) {
3126
+ handleError(error);
3127
+ }
3128
+ });
3129
+ admin.command("subscription").description("Show current subscription").action(async (_options, cmd) => {
3130
+ try {
3131
+ const outputFormat = getOutputFormat13(cmd);
3132
+ const api = createApiClient();
3133
+ const sub = await api.admin.getCurrentSubscription();
3134
+ format(sub, { format: outputFormat });
3135
+ } catch (error) {
3136
+ handleError(error);
3137
+ }
3138
+ });
3139
+ const settings = admin.command("settings").description("Manage settings");
3140
+ settings.command("get").description("Get current settings").action(async (_options, cmd) => {
3141
+ try {
3142
+ const outputFormat = getOutputFormat13(cmd);
3143
+ const api = createApiClient();
3144
+ const s = await api.admin.getSettings();
3145
+ format(s, { format: outputFormat });
3146
+ } catch (error) {
3147
+ handleError(error);
3148
+ }
3149
+ });
3150
+ settings.command("set").description("Update a setting").argument("<key>", "Setting key").argument("<value>", "Setting value").action(async (key, value) => {
3151
+ try {
3152
+ const api = createApiClient();
3153
+ await api.admin.mergeSetting({ [key]: value });
3154
+ console.log(chalk19.green(`Setting "${key}" updated.`));
3155
+ } catch (error) {
3156
+ handleError(error);
3157
+ }
3158
+ });
3159
+ const backup = admin.command("backup").description("Manage backups");
3160
+ backup.command("create-full").description("Create a full system backup").action(async () => {
3161
+ try {
3162
+ const api = createApiClient();
3163
+ await api.admin.createShortTermFullBackup();
3164
+ console.log(chalk19.green("Full backup initiated."));
3165
+ } catch (error) {
3166
+ handleError(error);
3167
+ }
3168
+ });
3169
+ backup.command("project").description("Create a project backup").argument("<projectId>", "Project ID").action(async (projectId) => {
3170
+ try {
3171
+ const api = createApiClient();
3172
+ await api.admin.createShortTermProjectBackup({ projectId });
3173
+ console.log(chalk19.green(`Project backup for "${projectId}" initiated.`));
3174
+ } catch (error) {
3175
+ handleError(error);
3176
+ }
3177
+ });
3178
+ }
3179
+
3180
+ // src/commands/status/summary.ts
3181
+ import chalk20 from "chalk";
3182
+
3183
+ // src/client/services/status.ts
3184
+ function createStatusService() {
3185
+ const config = loadConfig();
3186
+ const endpoint = resolveEndpoint(config);
3187
+ async function fetchJson(path5) {
3188
+ const url = `${endpoint}/status/v1${path5}`;
3189
+ const response = await fetch(url, {
3190
+ headers: { "Accept": "application/json" }
3191
+ });
3192
+ if (!response.ok) {
3193
+ throw new Error(`Status API error: HTTP ${response.status} from ${url}`);
3194
+ }
3195
+ return response.json();
3196
+ }
3197
+ return {
3198
+ getSummary: () => fetchJson("/summary"),
3199
+ getComponents: () => fetchJson("/components"),
3200
+ getIncidents: (window = "24h") => fetchJson(`/incidents?window=${window}`),
3201
+ getVersion: () => fetchJson("/version")
3202
+ };
3203
+ }
3204
+
3205
+ // src/commands/status/summary.ts
3206
+ var STATE_COLORS = {
3207
+ UP: chalk20.green,
3208
+ DEGRADED: chalk20.yellow,
3209
+ DOWN: chalk20.red,
3210
+ UNKNOWN: chalk20.gray
3211
+ };
3212
+ function stateColor(state) {
3213
+ return STATE_COLORS[state] ?? chalk20.gray;
3214
+ }
3215
+ function stateSymbol(state) {
3216
+ switch (state) {
3217
+ case "UP":
3218
+ return chalk20.green("\u25CF");
3219
+ case "DEGRADED":
3220
+ return chalk20.yellow("\u25CF");
3221
+ case "DOWN":
3222
+ return chalk20.red("\u25CF");
3223
+ default:
3224
+ return chalk20.gray("\u25CB");
3225
+ }
3226
+ }
3227
+ function registerSummaryCommand(parent) {
3228
+ parent.command("summary", { isDefault: true }).description("Show overall platform status").action(async (_options, cmd) => {
3229
+ try {
3230
+ const globalOpts = cmd.optsWithGlobals();
3231
+ const outputFormat = globalOpts.output ?? "human";
3232
+ const status = createStatusService();
3233
+ const [summary, version] = await Promise.all([
3234
+ status.getSummary(),
3235
+ status.getVersion()
3236
+ ]);
3237
+ if (outputFormat !== "human") {
3238
+ format({ ...summary, version }, { format: outputFormat });
3239
+ return;
3240
+ }
3241
+ const overallLabel = summary.overall === "UP" ? "All Systems Operational" : summary.overall === "DEGRADED" ? "Partial Degradation" : summary.overall === "DOWN" ? "Major Outage" : "Unknown";
3242
+ console.log();
3243
+ console.log(` ${stateSymbol(summary.overall)} ${stateColor(summary.overall)(overallLabel)}`);
3244
+ console.log();
3245
+ for (const domain of summary.domains) {
3246
+ const label = stateColor(domain.state)(domain.state.padEnd(10));
3247
+ console.log(` ${stateSymbol(domain.state)} ${label} ${domain.name}`);
3248
+ }
3249
+ console.log();
3250
+ if (summary.openIncidents > 0) {
3251
+ console.log(chalk20.yellow(` ${summary.openIncidents} active incident(s)`));
3252
+ } else {
3253
+ console.log(chalk20.dim(" No active incidents"));
3254
+ }
3255
+ console.log(chalk20.dim(`
3256
+ Platform v${version.platformVersion} \u2022 ${new Date(summary.timestamp).toLocaleString()}`));
3257
+ console.log();
3258
+ } catch (error) {
3259
+ handleError(error);
3260
+ }
3261
+ });
3262
+ }
3263
+
3264
+ // src/commands/status/component.ts
3265
+ import chalk21 from "chalk";
3266
+ function stateSymbol2(state) {
3267
+ switch (state) {
3268
+ case "UP":
3269
+ return chalk21.green("\u25CF");
3270
+ case "DEGRADED":
3271
+ return chalk21.yellow("\u25CF");
3272
+ case "DOWN":
3273
+ return chalk21.red("\u25CF");
3274
+ default:
3275
+ return chalk21.gray("\u25CB");
3276
+ }
3277
+ }
3278
+ function registerComponentCommand(parent) {
3279
+ parent.command("component <id>").description("Show detailed status of a specific component").action(async (id, _options, cmd) => {
3280
+ try {
3281
+ const globalOpts = cmd.optsWithGlobals();
3282
+ const outputFormat = globalOpts.output ?? "human";
3283
+ const status = createStatusService();
3284
+ const components = await status.getComponents();
3285
+ const match = components.find((c) => c.id === id || c.id === id + "-service");
3286
+ if (!match) {
3287
+ const available = components.map((c) => c.id).join(", ");
3288
+ console.error(chalk21.red(`Component "${id}" not found. Available: ${available}`));
3289
+ process.exit(1);
3290
+ }
3291
+ if (outputFormat !== "human") {
3292
+ format(match, { format: outputFormat });
3293
+ return;
3294
+ }
3295
+ console.log();
3296
+ console.log(` ${stateSymbol2(match.state)} ${chalk21.bold(match.id)} ${match.version ? chalk21.dim("v" + match.version) : ""}`);
3297
+ console.log(` State: ${match.state}`);
3298
+ if (match.lastCheckAt) {
3299
+ console.log(` Last check: ${new Date(match.lastCheckAt).toLocaleString()}`);
3300
+ }
3301
+ if (match.checks.length > 0) {
3302
+ console.log();
3303
+ console.log(" Checks:");
3304
+ for (const check of match.checks) {
3305
+ const cat = check.category ? chalk21.dim(` (${check.category})`) : "";
3306
+ console.log(` ${stateSymbol2(check.state)} ${check.name}${cat}`);
3307
+ }
3308
+ }
3309
+ console.log();
3310
+ } catch (error) {
3311
+ handleError(error);
3312
+ }
3313
+ });
3314
+ }
3315
+
3316
+ // src/commands/status/incidents.ts
3317
+ import chalk22 from "chalk";
3318
+ var SEVERITY_COLORS = {
3319
+ ERROR: chalk22.red,
3320
+ WARNING: chalk22.yellow,
3321
+ INFO: chalk22.blue,
3322
+ MAINTENANCE: chalk22.cyan
3323
+ };
3324
+ function registerIncidentsCommand(parent) {
3325
+ parent.command("incidents").description("List recent incidents").option("-w, --window <window>", "Time window (e.g. 24h, 48h)", "24h").action(async (options, cmd) => {
3326
+ try {
3327
+ const globalOpts = cmd.optsWithGlobals();
3328
+ const outputFormat = globalOpts.output ?? "human";
3329
+ const status = createStatusService();
3330
+ const incidents = await status.getIncidents(options.window);
3331
+ if (outputFormat !== "human") {
3332
+ format(incidents, { format: outputFormat });
3333
+ return;
3334
+ }
3335
+ if (incidents.length === 0) {
3336
+ console.log(chalk22.dim(`
3337
+ No incidents in the last ${options.window}.
3338
+ `));
3339
+ return;
3340
+ }
3341
+ console.log();
3342
+ for (const incident of incidents) {
3343
+ const color = SEVERITY_COLORS[incident.severity] ?? chalk22.gray;
3344
+ const severity = color(incident.severity.padEnd(8));
3345
+ const time = incident.startedAt ? new Date(incident.startedAt).toLocaleString() : "";
3346
+ const resolved = incident.resolvedAt ? chalk22.green(" [resolved]") : chalk22.yellow(" [open]");
3347
+ console.log(` ${severity} ${incident.summary}${resolved}`);
3348
+ console.log(chalk22.dim(` ${time}`));
3349
+ for (const update of incident.updates) {
3350
+ const updateTime = new Date(update.at).toLocaleTimeString();
3351
+ console.log(chalk22.dim(` ${updateTime} ${update.status} ${update.message}`));
3352
+ }
3353
+ console.log();
3354
+ }
3355
+ } catch (error) {
3356
+ handleError(error);
3357
+ }
3358
+ });
3359
+ }
3360
+
3361
+ // src/commands/status/index.ts
3362
+ function registerStatusCommands(program) {
3363
+ const status = program.command("status").description("Platform health and status");
3364
+ registerSummaryCommand(status);
3365
+ registerComponentCommand(status);
3366
+ registerIncidentsCommand(status);
3367
+ }
3368
+
3369
+ // src/commands/analyze/index.ts
3370
+ import chalk23 from "chalk";
3371
+ import * as fs5 from "fs";
3372
+ import * as path4 from "path";
3373
+ import { randomUUID as randomUUID3 } from "crypto";
3374
+ function createEntity(projectId, entityId, entityType, name, description, attributes, tags, contentType, content) {
3375
+ const now = Date.now();
3376
+ const entity = {
3377
+ projectId,
3378
+ projectBranch: "main",
3379
+ entityId,
3380
+ entityBranch: "main",
3381
+ head: true,
3382
+ version: 1,
3383
+ type: entityType,
3384
+ attributes: {},
3385
+ attributeTypes: {},
3386
+ metaAttributes: {},
3387
+ metaAttributeTypes: {},
3388
+ tags,
3389
+ modified: now,
3390
+ created: now,
3391
+ versioned: false,
3392
+ versionTtl: null,
3393
+ retain: false,
3394
+ contentAvailable: content !== null,
3395
+ contentLoaded: content !== null,
3396
+ contentType,
3397
+ contentSize: null,
3398
+ content
3399
+ };
3400
+ if (name !== null) {
3401
+ entity.attributeTypes["name"] = "text";
3402
+ entity.attributes["name"] = name;
3403
+ }
3404
+ if (description !== null) {
3405
+ entity.attributeTypes["description"] = "text";
3406
+ entity.attributes["description"] = description;
3407
+ }
3408
+ if (attributes) {
3409
+ for (const [key, value] of Object.entries(attributes)) {
3410
+ if (typeof value === "string") {
3411
+ entity.attributeTypes[key] = "text";
3412
+ entity.attributes[key] = value;
3413
+ } else if (typeof value === "number") {
3414
+ entity.attributeTypes[key] = "integer";
3415
+ entity.attributes[key] = String(value);
3416
+ }
3417
+ }
3418
+ }
3419
+ return entity;
3420
+ }
3421
+ function generateSourceCode(rawDataTableId, analysisChapterId, timeHours) {
3422
+ return `var rawDataTable = diafunc.table("${rawDataTableId}");
3423
+ var analysisChapter = diafunc.chapter("${analysisChapterId}");
3424
+
3425
+ return diafunc
3426
+ .analyze()
3427
+ .automatic()
3428
+ .from(rawDataTable)
3429
+ .to(analysisChapter)
3430
+ .hours(${timeHours});`;
3431
+ }
3432
+ function stringToBinary(str) {
3433
+ return Buffer.from(str).toString("base64");
3434
+ }
3435
+ function registerAnalyzeCommand(program) {
3436
+ program.command("analyze").description("Run an automatic analysis on a data file").argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Project name (derived from filename if omitted)").option("--description <text>", "Project description", "").option("--visibility <vis>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--time <hours>", "Computation time in hours", "4").option("--budget <credits>", "Credit budget", "400").option("--resume [id]", "Resume a previous analysis").option("--open", "Open in browser on completion").action(async (file, options, cmd) => {
3437
+ try {
3438
+ const api = createApiClient();
3439
+ if (options.resume !== void 0) {
3440
+ await resumeAnalysis(api, options.resume === true ? void 0 : options.resume, cmd);
3441
+ return;
3442
+ }
3443
+ if (!file) {
3444
+ console.error(chalk23.red("Please provide a data file to analyze, or use --resume."));
3445
+ process.exit(1);
3446
+ }
3447
+ if (!fs5.existsSync(file)) {
3448
+ console.error(chalk23.red(`File not found: ${file}`));
3449
+ process.exit(1);
3450
+ }
3451
+ const projectName = options.name ?? path4.basename(file, path4.extname(file));
3452
+ const visibility = options.visibility.toUpperCase();
3453
+ const analysis = {
3454
+ userId: null,
3455
+ analysisId: randomUUID3(),
3456
+ phase: "PREPARATION",
3457
+ step: "CREATE_PROJECT",
3458
+ projectName,
3459
+ projectDescription: options.description,
3460
+ visibility,
3461
+ time: options.time,
3462
+ budget: options.budget,
3463
+ projectId: null,
3464
+ notebookId: null,
3465
+ rawDataTableId: null,
3466
+ analysisFunctionId: null,
3467
+ analysisChapterId: null,
3468
+ year: null,
3469
+ month: null,
3470
+ day: null,
3471
+ hour: null,
3472
+ evaluationId: null,
3473
+ started: null
3474
+ };
3475
+ process.stdout.write(`Creating project "${projectName}" ...`);
3476
+ await createProjectStructure(api, analysis);
3477
+ console.log(chalk23.green(" done"));
3478
+ process.stdout.write(`Importing ${path4.basename(file)} ...`);
3479
+ await importData(api, analysis, file);
3480
+ console.log(chalk23.green(" done"));
3481
+ process.stdout.write("Launching analysis ...");
3482
+ await launchAnalysis(api, analysis);
3483
+ console.log(chalk23.green(" done"));
3484
+ console.log();
3485
+ await monitorAnalysis(api, analysis, cmd);
3486
+ } catch (error) {
3487
+ handleError(error);
3488
+ }
3489
+ });
3490
+ }
3491
+ async function createProjectStructure(api, analysis) {
3492
+ const project = await api.admin.createProject({
3493
+ visibility: analysis.visibility,
3494
+ language: "Java",
3495
+ active: true
3496
+ });
3497
+ analysis.projectId = project.projectId;
3498
+ await api.storage.createProjectBranch({
3499
+ projectId: project.projectId,
3500
+ sourceProjectBranch: null,
3501
+ targetProjectBranch: "main"
3502
+ });
3503
+ const projectEntity = createEntity(
3504
+ project.projectId,
3505
+ project.projectId,
3506
+ "project",
3507
+ analysis.projectName,
3508
+ analysis.projectDescription,
3509
+ null,
3510
+ [],
3511
+ null,
3512
+ null
3513
+ );
3514
+ await api.storage.saveEntities([projectEntity]);
3515
+ const notebookId = randomUUID3();
3516
+ analysis.notebookId = notebookId;
3517
+ const notebookEntity = createEntity(
3518
+ project.projectId,
3519
+ notebookId,
3520
+ "notebook",
3521
+ analysis.projectName,
3522
+ null,
3523
+ null,
3524
+ [],
3525
+ null,
3526
+ null
3527
+ );
3528
+ const projectRef = {
3529
+ projectId: project.projectId,
3530
+ projectBranch: "main",
3531
+ entityId: project.projectId,
3532
+ entityBranch: "main"
3533
+ };
3534
+ await api.storage.saveLinkedEntities(projectRef, "main", [notebookEntity]);
3535
+ const analysisChapterId = randomUUID3();
3536
+ analysis.analysisChapterId = analysisChapterId;
3537
+ const foundationChapterId = randomUUID3();
3538
+ const notebookRef = {
3539
+ projectId: project.projectId,
3540
+ projectBranch: "main",
3541
+ entityId: notebookId,
3542
+ entityBranch: "main"
3543
+ };
3544
+ await api.storage.saveLinkedEntities(notebookRef, "sections", [
3545
+ createEntity(project.projectId, randomUUID3(), "text", null, null, { index: 0, text: "This notebook is an analysis of your data." }, ["introduction"], null, null),
3546
+ createEntity(project.projectId, randomUUID3(), "contents", null, null, { index: 1 }, [], null, null),
3547
+ createEntity(project.projectId, analysisChapterId, "chapter", "Analysis", null, { index: 2 }, ["analysis"], null, null),
3548
+ createEntity(project.projectId, foundationChapterId, "chapter", "Foundation", null, { index: 3 }, ["foundation"], null, null)
3549
+ ]);
3550
+ const rawDataChapterId = randomUUID3();
3551
+ const analysisFunctionChapterId = randomUUID3();
3552
+ const foundationRef = {
3553
+ projectId: project.projectId,
3554
+ projectBranch: "main",
3555
+ entityId: foundationChapterId,
3556
+ entityBranch: "main"
3557
+ };
3558
+ await api.storage.saveLinkedEntities(foundationRef, "sections", [
3559
+ createEntity(project.projectId, rawDataChapterId, "chapter", "Raw Data", null, { index: 0 }, ["raw-data"], null, null),
3560
+ createEntity(project.projectId, analysisFunctionChapterId, "chapter", "Analysis Function", null, { index: 1 }, ["analysis-function"], null, null)
3561
+ ]);
3562
+ const rawDataTableId = randomUUID3();
3563
+ analysis.rawDataTableId = rawDataTableId;
3564
+ const rawDataRef = {
3565
+ projectId: project.projectId,
3566
+ projectBranch: "main",
3567
+ entityId: rawDataChapterId,
3568
+ entityBranch: "main"
3569
+ };
3570
+ await api.storage.saveLinkedEntities(rawDataRef, "sections", [
3571
+ createEntity(project.projectId, rawDataTableId, "table", "Raw Data Table", null, { index: 0 }, [], null, null)
3572
+ ]);
3573
+ const analysisFunctionId = randomUUID3();
3574
+ analysis.analysisFunctionId = analysisFunctionId;
3575
+ const sourceCode = generateSourceCode(rawDataTableId, analysisChapterId, analysis.time);
3576
+ const content = stringToBinary(JSON.stringify({ sourceCode }));
3577
+ const funcRef = {
3578
+ projectId: project.projectId,
3579
+ projectBranch: "main",
3580
+ entityId: analysisFunctionChapterId,
3581
+ entityBranch: "main"
3582
+ };
3583
+ await api.storage.saveLinkedEntities(funcRef, "sections", [
3584
+ createEntity(project.projectId, analysisFunctionId, "function", "Analysis Function", null, { index: 1, language: "Java" }, [], "text/plain", content)
3585
+ ]);
3586
+ analysis.step = "UPLOAD_DATA";
3587
+ await api.admin.saveAnalysis(analysis);
3588
+ }
3589
+ async function importData(api, analysis, file) {
3590
+ const ref = {
3591
+ projectId: analysis.projectId,
3592
+ projectBranch: "main",
3593
+ entityId: analysis.rawDataTableId,
3594
+ entityBranch: "main"
3595
+ };
3596
+ const fileBuffer = fs5.readFileSync(file);
3597
+ const blob = new Blob([fileBuffer]);
3598
+ const formData = new FormData();
3599
+ formData.append("content", blob, path4.basename(file));
3600
+ const importId = await api.storage.importTable(ref, formData, true);
3601
+ for (let i = 0; i < 300; i++) {
3602
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
3603
+ const imp = await api.storage.getImport(ref, importId);
3604
+ if (imp.finished !== null) {
3605
+ if (!imp.succeeded) {
3606
+ throw new Error(`Import failed: ${imp.error}`);
3607
+ }
3608
+ break;
3609
+ }
3610
+ }
3611
+ analysis.step = "LAUNCH_ANALYSIS";
3612
+ await api.admin.saveAnalysis(analysis);
3613
+ }
3614
+ async function launchAnalysis(api, analysis) {
3615
+ const funcRef = {
3616
+ projectId: analysis.projectId,
3617
+ projectBranch: "main",
3618
+ entityId: analysis.analysisFunctionId,
3619
+ entityBranch: "main"
3620
+ };
3621
+ const sourceCode = generateSourceCode(analysis.rawDataTableId, analysis.analysisChapterId, analysis.time);
3622
+ const content = stringToBinary(JSON.stringify({ sourceCode }));
3623
+ await api.storage.saveEntityContentBase64(funcRef, content);
3624
+ const now = /* @__PURE__ */ new Date();
3625
+ analysis.evaluationId = randomUUID3();
3626
+ analysis.year = now.getUTCFullYear();
3627
+ analysis.month = now.getUTCMonth() + 1;
3628
+ analysis.day = now.getUTCDate();
3629
+ analysis.hour = now.getUTCHours();
3630
+ await api.evaluation.call({
3631
+ evaluationId: analysis.evaluationId,
3632
+ projectId: analysis.projectId,
3633
+ projectBranch: "main",
3634
+ functionId: analysis.analysisFunctionId,
3635
+ functionBranch: "main",
3636
+ targetEntityId: null,
3637
+ targetEntityBranch: null,
3638
+ arguments: null,
3639
+ types: null,
3640
+ requested: Date.now(),
3641
+ provideOutputs: true,
3642
+ removeFunction: false
3643
+ }, true);
3644
+ analysis.phase = "ANALYSIS";
3645
+ analysis.started = Date.now();
3646
+ await api.admin.saveAnalysis(analysis);
3647
+ }
3648
+ async function monitorAnalysis(api, analysis, cmd) {
3649
+ const config = loadConfig();
3650
+ const globalOpts = cmd.optsWithGlobals();
3651
+ const outputFormat = globalOpts.output ?? config.defaults.output ?? "human";
3652
+ const computationMs = parseFloat(analysis.time) * 60 * 60 * 1e3;
3653
+ const seenOutputIds = /* @__PURE__ */ new Set();
3654
+ for (let i = 0; ; i++) {
3655
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
3656
+ try {
3657
+ const evaluation = await api.evaluation.getEvaluation(
3658
+ analysis.projectId,
3659
+ "main",
3660
+ analysis.analysisFunctionId,
3661
+ "main",
3662
+ analysis.year,
3663
+ analysis.month,
3664
+ analysis.day,
3665
+ analysis.hour,
3666
+ analysis.evaluationId,
3667
+ true
3668
+ );
3669
+ if (!evaluation.active) {
3670
+ analysis.phase = "COMPLETION";
3671
+ await api.admin.saveAnalysis(analysis);
3672
+ console.log();
3673
+ if (evaluation.successful) {
3674
+ const duration = evaluation.completed - evaluation.started;
3675
+ const durationStr = formatDuration(duration);
3676
+ if (outputFormat === "human") {
3677
+ console.log(chalk23.green(`Analysis complete! (${durationStr})`));
3678
+ if (evaluation.result) {
3679
+ console.log(` Result: ${evaluation.result}`);
3680
+ }
3681
+ const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
3682
+ console.log(` Project: ${endpoint}/lab/${analysis.projectId}/main/entities/${analysis.notebookId}/main`);
3683
+ } else {
3684
+ format({
3685
+ status: "completed",
3686
+ successful: true,
3687
+ duration,
3688
+ result: evaluation.result,
3689
+ projectId: analysis.projectId
3690
+ }, { format: outputFormat });
3691
+ }
3692
+ } else {
3693
+ if (outputFormat === "human") {
3694
+ console.log(chalk23.red("Analysis failed."));
3695
+ console.log(` Error: ${evaluation.error}`);
3696
+ } else {
3697
+ format({
3698
+ status: "failed",
3699
+ error: evaluation.error,
3700
+ projectId: analysis.projectId
3701
+ }, { format: outputFormat });
3702
+ }
3703
+ }
3704
+ return;
3705
+ }
3706
+ } catch {
3707
+ }
3708
+ try {
3709
+ const outputs = await api.evaluation.getOutputs(analysis.projectId, analysis.evaluationId);
3710
+ for (const out of outputs) {
3711
+ if (!seenOutputIds.has(out.outputId)) {
3712
+ seenOutputIds.add(out.outputId);
3713
+ if (outputFormat === "human") {
3714
+ console.log(` ${chalk23.dim("Output:")} ${out.output}`);
3715
+ }
3716
+ }
3717
+ }
3718
+ } catch {
3719
+ }
3720
+ if (outputFormat === "human" && i % 5 === 0) {
3721
+ const elapsed = Date.now() - analysis.started;
3722
+ const progress = Math.min(elapsed / computationMs, 1);
3723
+ const pct = Math.round(progress * 100);
3724
+ const bar = "\u2588".repeat(Math.round(progress * 30)) + "\u2591".repeat(30 - Math.round(progress * 30));
3725
+ process.stdout.write(`\r Analysis in progress [${bar}] ${pct}% `);
3726
+ }
3727
+ }
3728
+ }
3729
+ async function resumeAnalysis(api, analysisId, cmd) {
3730
+ let analysis;
3731
+ if (analysisId) {
3732
+ analysis = await api.admin.getAnalysis(analysisId);
3733
+ } else {
3734
+ const result = await api.admin.getLastAnalysis();
3735
+ if (!result.analysis) {
3736
+ console.log(chalk23.dim("No previous analysis found."));
3737
+ return;
3738
+ }
3739
+ analysis = result.analysis;
3740
+ }
3741
+ if (analysis.phase === "COMPLETION") {
3742
+ console.log(chalk23.dim("Analysis already completed."));
3743
+ return;
3744
+ }
3745
+ if (analysis.phase === "ANALYSIS") {
3746
+ console.log(`Resuming analysis monitoring for project "${analysis.projectId}" ...`);
3747
+ await monitorAnalysis(api, analysis, cmd);
3748
+ } else {
3749
+ console.log(`Analysis in preparation phase (step: ${analysis.step}). Cannot resume \u2014 start a new analysis.`);
3750
+ }
3751
+ }
3752
+ function formatDuration(ms) {
3753
+ const seconds = Math.floor(ms / 1e3);
3754
+ const minutes = Math.floor(seconds / 60);
3755
+ const hours = Math.floor(minutes / 60);
3756
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
3757
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
3758
+ return `${seconds}s`;
3759
+ }
3760
+
3761
+ // src/commands/completion/index.ts
3762
+ var BASH_COMPLETION = `#!/bin/bash
3763
+ _diafunc_completions() {
3764
+ local cur prev commands subcommands
3765
+ cur="\${COMP_WORDS[COMP_CWORD]}"
3766
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
3767
+
3768
+ commands="auth config project entity link event branch table function trigger schedule chat search group admin analyze help"
3769
+
3770
+ case "\${COMP_WORDS[1]}" in
3771
+ auth)
3772
+ subcommands="login logout status token"
3773
+ if [[ "\${COMP_WORDS[2]}" == "token" ]]; then
3774
+ COMPREPLY=($(compgen -W "create list revoke" -- "\${cur}"))
3775
+ else
3776
+ COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}"))
3777
+ fi
3778
+ ;;
3779
+ config)
3780
+ subcommands="set get list profile"
3781
+ if [[ "\${COMP_WORDS[2]}" == "profile" ]]; then
3782
+ COMPREPLY=($(compgen -W "add use list remove" -- "\${cur}"))
3783
+ else
3784
+ COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}"))
3785
+ fi
3786
+ ;;
3787
+ project)
3788
+ subcommands="list get create delete lock unlock members"
3789
+ if [[ "\${COMP_WORDS[2]}" == "members" ]]; then
3790
+ COMPREPLY=($(compgen -W "list invite join remove" -- "\${cur}"))
3791
+ else
3792
+ COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}"))
3793
+ fi
3794
+ ;;
3795
+ entity)
3796
+ subcommands="list get delete history revert rename content"
3797
+ if [[ "\${COMP_WORDS[2]}" == "content" ]]; then
3798
+ COMPREPLY=($(compgen -W "get set delete" -- "\${cur}"))
3799
+ else
3800
+ COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}"))
3801
+ fi
3802
+ ;;
3803
+ link)
3804
+ COMPREPLY=($(compgen -W "list create delete" -- "\${cur}"))
3805
+ ;;
3806
+ event)
3807
+ COMPREPLY=($(compgen -W "list get delete" -- "\${cur}"))
3808
+ ;;
3809
+ branch)
3810
+ COMPREPLY=($(compgen -W "list create delete merge fork" -- "\${cur}"))
3811
+ ;;
3812
+ table)
3813
+ subcommands="view import export row column cell clear"
3814
+ case "\${COMP_WORDS[2]}" in
3815
+ row) COMPREPLY=($(compgen -W "add remove" -- "\${cur}")) ;;
3816
+ column) COMPREPLY=($(compgen -W "add remove" -- "\${cur}")) ;;
3817
+ cell) COMPREPLY=($(compgen -W "set delete" -- "\${cur}")) ;;
3818
+ *) COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}")) ;;
3819
+ esac
3820
+ ;;
3821
+ function)
3822
+ COMPREPLY=($(compgen -W "call evaluations outputs logs stop engines" -- "\${cur}"))
3823
+ ;;
3824
+ trigger)
3825
+ COMPREPLY=($(compgen -W "list get delete" -- "\${cur}"))
3826
+ ;;
3827
+ schedule)
3828
+ COMPREPLY=($(compgen -W "call" -- "\${cur}"))
3829
+ ;;
3830
+ chat)
3831
+ subcommands="send stream upload session usage"
3832
+ if [[ "\${COMP_WORDS[2]}" == "session" ]]; then
3833
+ COMPREPLY=($(compgen -W "list delete" -- "\${cur}"))
3834
+ else
3835
+ COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}"))
3836
+ fi
3837
+ ;;
3838
+ group)
3839
+ subcommands="list get create delete members projects"
3840
+ case "\${COMP_WORDS[2]}" in
3841
+ members) COMPREPLY=($(compgen -W "list invite remove" -- "\${cur}")) ;;
3842
+ projects) COMPREPLY=($(compgen -W "list add remove" -- "\${cur}")) ;;
3843
+ *) COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}")) ;;
3844
+ esac
3845
+ ;;
3846
+ admin)
3847
+ subcommands="users subscription settings backup"
3848
+ case "\${COMP_WORDS[2]}" in
3849
+ users) COMPREPLY=($(compgen -W "list get" -- "\${cur}")) ;;
3850
+ settings) COMPREPLY=($(compgen -W "get set" -- "\${cur}")) ;;
3851
+ backup) COMPREPLY=($(compgen -W "create-full project" -- "\${cur}")) ;;
3852
+ *) COMPREPLY=($(compgen -W "\${subcommands}" -- "\${cur}")) ;;
3853
+ esac
3854
+ ;;
3855
+ *)
3856
+ COMPREPLY=($(compgen -W "\${commands}" -- "\${cur}"))
3857
+ ;;
3858
+ esac
3859
+ }
3860
+ complete -F _diafunc_completions diafunc`;
3861
+ var ZSH_COMPLETION = `#compdef diafunc
3862
+
3863
+ _diafunc() {
3864
+ local -a commands
3865
+ commands=(
3866
+ 'auth:Authentication and credential management'
3867
+ 'config:Manage CLI configuration'
3868
+ 'project:Manage projects'
3869
+ 'entity:Manage entities'
3870
+ 'link:Manage links between entities'
3871
+ 'event:Manage events'
3872
+ 'branch:Manage branches'
3873
+ 'table:Manage tables'
3874
+ 'function:Execute and manage functions'
3875
+ 'trigger:Manage function triggers'
3876
+ 'schedule:Schedule function execution'
3877
+ 'chat:AI chat'
3878
+ 'search:Search entities across projects'
3879
+ 'group:Manage groups'
3880
+ 'admin:Administration commands'
3881
+ 'analyze:Run an automatic analysis on a data file'
3882
+ )
3883
+
3884
+ _arguments -C \\
3885
+ '(-V --version)'{-V,--version}'[output the version number]' \\
3886
+ '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\
3887
+ '(-o --output)'{-o,--output}'[Output format]:format:(human json table)' \\
3888
+ '--project[Default project ID override]:project:' \\
3889
+ '--branch[Default branch override]:branch:' \\
3890
+ '(-h --help)'{-h,--help}'[display help]' \\
3891
+ '1: :->command' \\
3892
+ '*::arg:->args'
3893
+
3894
+ case $state in
3895
+ command)
3896
+ _describe 'command' commands
3897
+ ;;
3898
+ args)
3899
+ case \${words[1]} in
3900
+ auth) _diafunc_auth ;;
3901
+ config) _diafunc_config ;;
3902
+ project) _diafunc_project ;;
3903
+ entity) _diafunc_entity ;;
3904
+ link) _values 'subcommand' list create delete ;;
3905
+ event) _values 'subcommand' list get delete ;;
3906
+ branch) _values 'subcommand' list create delete merge fork ;;
3907
+ table) _diafunc_table ;;
3908
+ function) _values 'subcommand' call evaluations outputs logs stop engines ;;
3909
+ trigger) _values 'subcommand' list get delete ;;
3910
+ schedule) _values 'subcommand' call ;;
3911
+ chat) _diafunc_chat ;;
3912
+ group) _diafunc_group ;;
3913
+ admin) _diafunc_admin ;;
3914
+ analyze) _files '*.csv' '*.xlsx' '*.xls' ;;
3915
+ esac
3916
+ ;;
3917
+ esac
3918
+ }
3919
+
3920
+ _diafunc_auth() { _values 'subcommand' login logout status token; }
3921
+ _diafunc_config() { _values 'subcommand' set get list profile; }
3922
+ _diafunc_project() { _values 'subcommand' list get create delete lock unlock members; }
3923
+ _diafunc_entity() { _values 'subcommand' list get delete history revert rename content; }
3924
+ _diafunc_table() { _values 'subcommand' view import export row column cell clear; }
3925
+ _diafunc_chat() { _values 'subcommand' send stream upload session usage; }
3926
+ _diafunc_group() { _values 'subcommand' list get create delete members projects; }
3927
+ _diafunc_admin() { _values 'subcommand' users subscription settings backup; }
3928
+
3929
+ _diafunc "$@"`;
3930
+ var FISH_COMPLETION = `# Fish completions for diafunc
3931
+ set -l commands auth config project entity link event branch table function trigger schedule chat search group admin analyze
3932
+
3933
+ # Disable file completions by default
3934
+ complete -c diafunc -f
3935
+
3936
+ # Top-level commands
3937
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a auth -d "Authentication and credential management"
3938
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a config -d "Manage CLI configuration"
3939
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a project -d "Manage projects"
3940
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a entity -d "Manage entities"
3941
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a link -d "Manage links between entities"
3942
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a event -d "Manage events"
3943
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a branch -d "Manage branches"
3944
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a table -d "Manage tables"
3945
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a function -d "Execute and manage functions"
3946
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a trigger -d "Manage function triggers"
3947
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a schedule -d "Schedule function execution"
3948
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a chat -d "AI chat"
3949
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a search -d "Search entities"
3950
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a group -d "Manage groups"
3951
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a admin -d "Administration commands"
3952
+ complete -c diafunc -n "not __fish_seen_subcommand_from $commands" -a analyze -d "Run automatic analysis"
3953
+
3954
+ # Global flags
3955
+ complete -c diafunc -s p -l profile -d "Profile to use"
3956
+ complete -c diafunc -s o -l output -d "Output format" -a "human json table"
3957
+ complete -c diafunc -l project -d "Default project ID override"
3958
+ complete -c diafunc -l branch -d "Default branch override"
3959
+ complete -c diafunc -l dry-run -d "Preview without executing"
3960
+
3961
+ # auth
3962
+ complete -c diafunc -n "__fish_seen_subcommand_from auth; and not __fish_seen_subcommand_from login logout status token" -a "login logout status token"
3963
+ complete -c diafunc -n "__fish_seen_subcommand_from token; and not __fish_seen_subcommand_from create list revoke" -a "create list revoke"
3964
+
3965
+ # config
3966
+ complete -c diafunc -n "__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from set get list profile" -a "set get list profile"
3967
+ complete -c diafunc -n "__fish_seen_subcommand_from profile; and not __fish_seen_subcommand_from add use list remove" -a "add use list remove"
3968
+
3969
+ # project
3970
+ complete -c diafunc -n "__fish_seen_subcommand_from project; and not __fish_seen_subcommand_from list get create delete lock unlock members" -a "list get create delete lock unlock members"
3971
+
3972
+ # entity
3973
+ complete -c diafunc -n "__fish_seen_subcommand_from entity; and not __fish_seen_subcommand_from list get delete history revert rename content" -a "list get delete history revert rename content"
3974
+
3975
+ # branch
3976
+ complete -c diafunc -n "__fish_seen_subcommand_from branch; and not __fish_seen_subcommand_from list create delete merge fork" -a "list create delete merge fork"
3977
+
3978
+ # table
3979
+ complete -c diafunc -n "__fish_seen_subcommand_from table; and not __fish_seen_subcommand_from view import export row column cell clear" -a "view import export row column cell clear"
3980
+
3981
+ # function
3982
+ complete -c diafunc -n "__fish_seen_subcommand_from function; and not __fish_seen_subcommand_from call evaluations outputs logs stop engines" -a "call evaluations outputs logs stop engines"
3983
+
3984
+ # chat
3985
+ complete -c diafunc -n "__fish_seen_subcommand_from chat; and not __fish_seen_subcommand_from send stream upload session usage" -a "send stream upload session usage"
3986
+
3987
+ # group
3988
+ complete -c diafunc -n "__fish_seen_subcommand_from group; and not __fish_seen_subcommand_from list get create delete members projects" -a "list get create delete members projects"
3989
+
3990
+ # admin
3991
+ complete -c diafunc -n "__fish_seen_subcommand_from admin; and not __fish_seen_subcommand_from users subscription settings backup" -a "users subscription settings backup"
3992
+
3993
+ # analyze accepts files
3994
+ complete -c diafunc -n "__fish_seen_subcommand_from analyze" -F`;
3995
+ function registerCompletionCommand(program) {
3996
+ program.command("completion").description("Generate shell completion scripts").argument("<shell>", "Shell type: bash, zsh, or fish").action((shell) => {
3997
+ switch (shell.toLowerCase()) {
3998
+ case "bash":
3999
+ console.log(BASH_COMPLETION);
4000
+ break;
4001
+ case "zsh":
4002
+ console.log(ZSH_COMPLETION);
4003
+ break;
4004
+ case "fish":
4005
+ console.log(FISH_COMPLETION);
4006
+ break;
4007
+ default:
4008
+ console.error(`Unknown shell: "${shell}". Supported: bash, zsh, fish`);
4009
+ process.exit(1);
4010
+ }
4011
+ });
4012
+ }
4013
+
4014
+ // src/index.ts
4015
+ function createProgram() {
4016
+ const program = new Command();
4017
+ program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version("0.1.0").option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").hook("preAction", (thisCommand) => {
4018
+ const opts = thisCommand.optsWithGlobals();
4019
+ if (opts.dryRun) {
4020
+ setDryRun(true);
4021
+ }
4022
+ });
4023
+ registerAuthCommands(program);
4024
+ registerConfigCommands(program);
4025
+ registerProjectCommands(program);
4026
+ registerEntityCommands(program);
4027
+ registerLinkCommands(program);
4028
+ registerEventCommands(program);
4029
+ registerBranchCommands(program);
4030
+ registerTableCommands(program);
4031
+ registerFunctionCommands(program);
4032
+ registerTriggerCommands(program);
4033
+ registerScheduleCommands(program);
4034
+ registerChatCommands(program);
4035
+ registerSearchCommands(program);
4036
+ registerGroupCommands(program);
4037
+ registerAdminCommands(program);
4038
+ registerStatusCommands(program);
4039
+ registerAnalyzeCommand(program);
4040
+ registerCompletionCommand(program);
4041
+ return program;
4042
+ }
4043
+
4044
+ export {
4045
+ createProgram
4046
+ };
4047
+ //# sourceMappingURL=chunk-63FZ6EJP.js.map