@vee-stack/delta-cli 2.0.3 → 2.0.5

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.
Files changed (135) hide show
  1. package/dist/analyzer/commands/analyze.js +260 -0
  2. package/dist/analyzer/commands/config.js +83 -0
  3. package/dist/analyzer/commands/report.js +38 -0
  4. package/dist/analyzer/generators/report.generator.js +123 -0
  5. package/dist/analyzer/index.js +44 -0
  6. package/dist/analyzer/scanners/project.scanner.js +92 -0
  7. package/dist/analyzer/validators/contracts.validator.js +42 -0
  8. package/dist/analyzer/validators/maintainability.validator.js +40 -0
  9. package/dist/analyzer/validators/observability.validator.js +39 -0
  10. package/dist/analyzer/validators/performance.validator.js +42 -0
  11. package/dist/analyzer/validators/security.validator.js +66 -0
  12. package/dist/analyzer/validators/soc.validator.js +75 -0
  13. package/dist/apps/cli/src/analyzer/commands/analyze.js +256 -0
  14. package/dist/apps/cli/src/analyzer/commands/config.js +83 -0
  15. package/dist/apps/cli/src/analyzer/commands/report.js +38 -0
  16. package/dist/apps/cli/src/analyzer/generators/report.generator.js +123 -0
  17. package/dist/apps/cli/src/analyzer/index.js +44 -0
  18. package/dist/apps/cli/src/analyzer/scanners/project.scanner.js +92 -0
  19. package/dist/apps/cli/src/analyzer/validators/contracts.validator.js +42 -0
  20. package/dist/apps/cli/src/analyzer/validators/maintainability.validator.js +40 -0
  21. package/dist/apps/cli/src/analyzer/validators/observability.validator.js +39 -0
  22. package/dist/apps/cli/src/analyzer/validators/performance.validator.js +42 -0
  23. package/dist/apps/cli/src/analyzer/validators/security.validator.js +66 -0
  24. package/dist/apps/cli/src/analyzer/validators/soc.validator.js +75 -0
  25. package/dist/apps/cli/src/auth/secure-auth.js +312 -0
  26. package/dist/apps/cli/src/commands/analyze.js +286 -0
  27. package/dist/apps/cli/src/commands/auth-new.js +37 -0
  28. package/dist/apps/cli/src/commands/auth.js +122 -0
  29. package/dist/apps/cli/src/commands/config.js +49 -0
  30. package/dist/apps/cli/src/commands/deploy.js +6 -0
  31. package/dist/apps/cli/src/commands/init.js +47 -0
  32. package/dist/apps/cli/src/commands/logout.js +23 -0
  33. package/dist/apps/cli/src/commands/plugins.js +21 -0
  34. package/dist/apps/cli/src/commands/status.js +80 -0
  35. package/dist/apps/cli/src/commands/sync.js +6 -0
  36. package/dist/apps/cli/src/commands/whoami.js +115 -0
  37. package/dist/apps/cli/src/components/Dashboard.js +168 -0
  38. package/dist/apps/cli/src/components/DeltaApp.js +56 -0
  39. package/dist/apps/cli/src/components/UnifiedManager.js +324 -0
  40. package/dist/apps/cli/src/core/audit.js +184 -0
  41. package/dist/apps/cli/src/core/completion.js +294 -0
  42. package/dist/apps/cli/src/core/contracts.js +6 -0
  43. package/dist/apps/cli/src/core/engine.js +124 -0
  44. package/dist/apps/cli/src/core/exit-codes.js +71 -0
  45. package/dist/apps/cli/src/core/hooks.js +181 -0
  46. package/dist/apps/cli/src/core/index.js +7 -0
  47. package/dist/apps/cli/src/core/policy.js +115 -0
  48. package/dist/apps/cli/src/core/profiles.js +161 -0
  49. package/dist/apps/cli/src/core/wizard.js +203 -0
  50. package/dist/apps/cli/src/index.js +636 -0
  51. package/dist/apps/cli/src/interactive/index.js +11 -0
  52. package/dist/apps/cli/src/plugins/GitStatusPlugin.js +99 -0
  53. package/dist/apps/cli/src/providers/ai-provider.js +74 -0
  54. package/dist/apps/cli/src/providers/local-provider.js +302 -0
  55. package/dist/apps/cli/src/providers/remote-provider.js +100 -0
  56. package/dist/apps/cli/src/types/api.js +3 -0
  57. package/dist/apps/cli/src/ui.js +219 -0
  58. package/dist/apps/cli/src/welcome.js +81 -0
  59. package/dist/auth/secure-auth.js +418 -0
  60. package/dist/bundle.js +45 -46
  61. package/dist/commands/analyze.js +363 -0
  62. package/dist/commands/auth-new.js +37 -0
  63. package/dist/commands/auth.js +133 -0
  64. package/dist/commands/config.js +50 -0
  65. package/dist/commands/deploy.js +6 -0
  66. package/dist/commands/init.js +47 -0
  67. package/dist/commands/logout.js +30 -0
  68. package/dist/commands/plugins.js +21 -0
  69. package/dist/commands/status.js +82 -0
  70. package/dist/commands/sync.js +6 -0
  71. package/dist/commands/whoami.js +71 -0
  72. package/dist/components/Dashboard.js +169 -0
  73. package/dist/components/DeltaApp.js +57 -0
  74. package/dist/components/UnifiedManager.js +344 -0
  75. package/dist/core/audit.js +184 -0
  76. package/dist/core/completion.js +294 -0
  77. package/dist/core/contracts.js +6 -0
  78. package/dist/core/engine.js +124 -0
  79. package/dist/core/exit-codes.js +71 -0
  80. package/dist/core/hooks.js +181 -0
  81. package/dist/core/index.js +7 -0
  82. package/dist/core/policy.js +115 -0
  83. package/dist/core/profiles.js +161 -0
  84. package/dist/core/wizard.js +203 -0
  85. package/dist/index.js +387 -0
  86. package/dist/interactive/index.js +11 -0
  87. package/dist/packages/domain/src/constitution/contracts/index.js +43 -0
  88. package/dist/packages/domain/src/constitution/contracts/ts.rules.js +268 -0
  89. package/dist/packages/domain/src/constitution/index.js +139 -0
  90. package/dist/packages/domain/src/constitution/maintainability/index.js +43 -0
  91. package/dist/packages/domain/src/constitution/maintainability/ts.rules.js +344 -0
  92. package/dist/packages/domain/src/constitution/observability/index.js +43 -0
  93. package/dist/packages/domain/src/constitution/observability/ts.rules.js +307 -0
  94. package/dist/packages/domain/src/constitution/performance/index.js +43 -0
  95. package/dist/packages/domain/src/constitution/performance/ts.rules.js +325 -0
  96. package/dist/packages/domain/src/constitution/security/index.js +50 -0
  97. package/dist/packages/domain/src/constitution/security/ts.rules.js +267 -0
  98. package/dist/packages/domain/src/constitution/soc/index.js +43 -0
  99. package/dist/packages/domain/src/constitution/soc/ts.rules.js +360 -0
  100. package/dist/packages/domain/src/contracts/analysis.contract.js +18 -0
  101. package/dist/packages/domain/src/contracts/index.js +7 -0
  102. package/dist/packages/domain/src/contracts/projects.contract.js +18 -0
  103. package/dist/packages/domain/src/control/registry/rules.registry.js +29 -0
  104. package/dist/packages/domain/src/control/schemas/policies.js +6 -0
  105. package/dist/packages/domain/src/core/analysis/discovery.js +163 -0
  106. package/dist/packages/domain/src/core/analysis/engine.contract.js +298 -0
  107. package/dist/packages/domain/src/core/analysis/engine.js +77 -0
  108. package/dist/packages/domain/src/core/analysis/index.js +14 -0
  109. package/dist/packages/domain/src/core/analysis/orchestrator.js +242 -0
  110. package/dist/packages/domain/src/core/comparison/engine.js +29 -0
  111. package/dist/packages/domain/src/core/comparison/index.js +5 -0
  112. package/dist/packages/domain/src/core/documentation/index.js +5 -0
  113. package/dist/packages/domain/src/core/documentation/pipeline.js +41 -0
  114. package/dist/packages/domain/src/core/fs/adapter.js +111 -0
  115. package/dist/packages/domain/src/core/fs/index.js +5 -0
  116. package/dist/packages/domain/src/core/parser/unified-parser.js +166 -0
  117. package/dist/packages/domain/src/index.js +33 -0
  118. package/dist/packages/domain/src/plugin/registry.js +195 -0
  119. package/dist/packages/domain/src/plugin/types.js +6 -0
  120. package/dist/packages/domain/src/ports/analysis.engine.js +7 -0
  121. package/dist/packages/domain/src/ports/audit.logger.js +7 -0
  122. package/dist/packages/domain/src/ports/project.repository.js +7 -0
  123. package/dist/packages/domain/src/rules/index.js +134 -0
  124. package/dist/packages/domain/src/types/analysis.js +6 -0
  125. package/dist/packages/domain/src/types/errors.js +53 -0
  126. package/dist/packages/domain/src/types/fs.js +6 -0
  127. package/dist/packages/domain/src/types/index.js +7 -0
  128. package/dist/plugins/GitStatusPlugin.js +93 -0
  129. package/dist/providers/ai-provider.js +74 -0
  130. package/dist/providers/local-provider.js +304 -0
  131. package/dist/providers/remote-provider.js +100 -0
  132. package/dist/types/api.js +3 -0
  133. package/dist/ui.js +219 -0
  134. package/dist/welcome.js +81 -0
  135. package/package.json +18 -18
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Analyze Command - Run local analysis with optional upload to cloud
3
+ */
4
+ import * as fs from 'fs/promises';
5
+ import * as path from 'path';
6
+ import * as crypto from 'crypto';
7
+ import { loadConfig } from './auth.js';
8
+ import { SecureTokenStore } from '../auth/secure-auth.js';
9
+ import chalk from 'chalk';
10
+ import { icons, startSpinner, stopSpinner, printSuccess, printInfo, printWarning, createTable, printDivider } from '../ui.js';
11
+ function extractApiErrorPayload(payload) {
12
+ if (!payload || typeof payload !== 'object')
13
+ return {};
14
+ const maybeError = payload.error;
15
+ if (!maybeError || typeof maybeError !== 'object')
16
+ return {};
17
+ const e = maybeError;
18
+ return {
19
+ message: typeof e.message === 'string' ? e.message : undefined,
20
+ details: e.details,
21
+ };
22
+ }
23
+ export async function analyzeCommand(projectPath, options) {
24
+ const targetPath = path.resolve(projectPath);
25
+ printInfo('🔍 Starting Delta Analysis Engine...');
26
+ printDivider();
27
+ console.log(`${icons.folder} Project: ${chalk.cyan(targetPath)}`);
28
+ console.log();
29
+ // Phase 1: File Discovery
30
+ startSpinner('Scanning project files...');
31
+ const files = await discoverFiles(targetPath, {
32
+ include: options.include ? [options.include] : ['**/*.{ts,tsx,js,jsx}'],
33
+ exclude: options.exclude ? [options.exclude].concat(['node_modules', 'dist', '.git']) : ['node_modules', 'dist', '.git'],
34
+ maxSize: parseInt(options.maxSize, 10),
35
+ });
36
+ stopSpinner(true, `Found ${files.length} files to analyze`);
37
+ console.log();
38
+ if (files.length === 0) {
39
+ printWarning('No files found matching the criteria');
40
+ printInfo('Try adjusting --include or --exclude patterns');
41
+ process.exit(0);
42
+ }
43
+ // Phase 2: Analysis with Progress
44
+ console.log(`${icons.loading} Analyzing ${files.length} files...`);
45
+ console.log();
46
+ const startTime = Date.now();
47
+ const summary = {
48
+ totalFiles: files.length,
49
+ successfulParses: 0,
50
+ failedParses: 0,
51
+ totalLines: 0,
52
+ totalFunctions: 0,
53
+ totalClasses: 0,
54
+ totalDuration: 0,
55
+ errors: [],
56
+ };
57
+ const findings = [];
58
+ // Process files with progress indication
59
+ for (let i = 0; i < files.length; i++) {
60
+ const file = files[i];
61
+ const progress = Math.round(((i + 1) / files.length) * 100);
62
+ const bar = renderProgressBar(progress);
63
+ // Clear line and print progress
64
+ process.stdout.write(`\r${bar} ${chalk.cyan(`${i + 1}/${files.length}`)} ${chalk.dim(file.split(/[/\\]/).pop() || '')}`);
65
+ try {
66
+ const content = await fs.readFile(file, 'utf-8');
67
+ const lines = content.split('\n');
68
+ summary.totalLines += lines.length;
69
+ summary.successfulParses++;
70
+ // Simple heuristics for demo
71
+ if (content.includes('function '))
72
+ summary.totalFunctions++;
73
+ if (content.includes('class '))
74
+ summary.totalClasses++;
75
+ // Find potential issues
76
+ if (content.includes('eval(')) {
77
+ findings.push({
78
+ file: path.relative(targetPath, file),
79
+ type: 'security',
80
+ severity: 'high',
81
+ message: 'Use of eval() detected',
82
+ });
83
+ }
84
+ if (content.includes('console.log')) {
85
+ findings.push({
86
+ file: path.relative(targetPath, file),
87
+ type: 'maintainability',
88
+ severity: 'low',
89
+ message: 'Console.log statement found',
90
+ });
91
+ }
92
+ }
93
+ catch (error) {
94
+ summary.failedParses++;
95
+ summary.errors.push({
96
+ file: path.relative(targetPath, file),
97
+ error: error instanceof Error ? error.message : String(error),
98
+ });
99
+ }
100
+ }
101
+ // Clear progress line
102
+ process.stdout.write('\r' + ' '.repeat(80) + '\r');
103
+ console.log(`${icons.check} Analysis complete: ${chalk.green(`${summary.successfulParses} successful`)}, ${summary.failedParses > 0 ? chalk.red(`${summary.failedParses} failed`) : ''}`);
104
+ console.log();
105
+ summary.totalDuration = Date.now() - startTime;
106
+ // Build report
107
+ const report = {
108
+ schema_version: '1.0',
109
+ engine_version: '0.5.0',
110
+ created_at: new Date().toISOString(),
111
+ project: {
112
+ name: options.projectName || path.basename(targetPath),
113
+ root_fingerprint: '',
114
+ path: targetPath,
115
+ },
116
+ tools_used: [
117
+ { id: 'delta-core', version: '0.5.0', adapter_version: '0.5.0' },
118
+ ],
119
+ summary: {
120
+ total: findings.length,
121
+ high: findings.filter(f => f.severity === 'high').length,
122
+ medium: findings.filter(f => f.severity === 'medium').length,
123
+ low: findings.filter(f => f.severity === 'low').length,
124
+ },
125
+ findings,
126
+ metadata: summary,
127
+ };
128
+ // Phase 3: Results Display
129
+ printDivider();
130
+ printSuccess('Analysis Complete');
131
+ console.log();
132
+ // Summary table
133
+ const summaryTable = createTable(['Metric', 'Value']);
134
+ summaryTable.push([icons.folder + ' Files Analyzed', summary.totalFiles.toString()], [icons.chart + ' Total Lines', summary.totalLines.toLocaleString()], [icons.gear + ' Functions Found', summary.totalFunctions.toString()], [icons.package + ' Classes Found', summary.totalClasses.toString()], [icons.loading + ' Duration', formatDuration(summary.totalDuration)]);
135
+ console.log(summaryTable.toString());
136
+ console.log();
137
+ // Findings summary
138
+ if (findings.length > 0) {
139
+ printWarning(`Found ${findings.length} issues:`);
140
+ const issuesTable = createTable(['Severity', 'Count']);
141
+ const highCount = findings.filter(f => f.severity === 'high').length;
142
+ const mediumCount = findings.filter(f => f.severity === 'medium').length;
143
+ const lowCount = findings.filter(f => f.severity === 'low').length;
144
+ if (highCount > 0)
145
+ issuesTable.push([chalk.red('🔴 High'), highCount.toString()]);
146
+ if (mediumCount > 0)
147
+ issuesTable.push([chalk.yellow('🟡 Medium'), mediumCount.toString()]);
148
+ if (lowCount > 0)
149
+ issuesTable.push([chalk.blue('🔵 Low'), lowCount.toString()]);
150
+ console.log(issuesTable.toString());
151
+ }
152
+ else {
153
+ printSuccess('✨ No issues found! Great job!');
154
+ }
155
+ console.log();
156
+ // Save report to file
157
+ const outputDir = path.resolve(options.output);
158
+ await fs.mkdir(outputDir, { recursive: true });
159
+ const reportFile = path.join(outputDir, `report-${Date.now()}.json`);
160
+ await fs.writeFile(reportFile, JSON.stringify(report, null, 2));
161
+ printInfo(`${icons.chart} Report saved: ${chalk.cyan(reportFile)}`);
162
+ console.log();
163
+ // Upload to cloud if requested
164
+ if (options.upload) {
165
+ console.log(`${icons.rocket} Uploading to Delta Cloud...`);
166
+ await uploadReport(report);
167
+ }
168
+ }
169
+ async function uploadReport(report) {
170
+ const config = await loadConfig();
171
+ // Get PAT from secure keychain storage, NOT from config file
172
+ const pat = await SecureTokenStore.getAccessToken();
173
+ if (!pat) {
174
+ console.error('❌ Error: Not authenticated. Run: delta login --token <pat>');
175
+ process.exit(1);
176
+ }
177
+ const apiUrl = process.env.DELTA_API_URL || config.apiUrl || 'http://localhost:3000';
178
+ const reportJson = JSON.stringify(report);
179
+ const reportHash = crypto.createHash('sha256').update(reportJson).digest('hex');
180
+ try {
181
+ // Step 1: Init upload session
182
+ const initResponse = await fetch(`${apiUrl}/api/upload/init`, {
183
+ method: 'POST',
184
+ headers: {
185
+ 'Authorization': `Bearer ${pat}`,
186
+ 'Content-Type': 'application/json',
187
+ 'Idempotency-Key': crypto.randomUUID(),
188
+ },
189
+ body: JSON.stringify({
190
+ schemaVersion: '1.0',
191
+ engineVersion: '0.5.0',
192
+ reportHash: reportHash,
193
+ reportSizeBytes: Buffer.byteLength(reportJson),
194
+ toolsUsed: [{ id: 'delta-core', version: '0.5.0', adapterVersion: '0.5.0' }],
195
+ }),
196
+ });
197
+ if (!initResponse.ok) {
198
+ let payload = undefined;
199
+ try {
200
+ payload = await initResponse.json();
201
+ }
202
+ catch {
203
+ payload = await initResponse.text().catch(() => undefined);
204
+ }
205
+ const apiError = extractApiErrorPayload(payload);
206
+ const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
207
+ const message = apiError.message || `Init failed: ${initResponse.status}`;
208
+ throw new Error(message + details);
209
+ }
210
+ const initData = await initResponse.json();
211
+ if (!initData.success) {
212
+ throw new Error(initData.error?.message || 'Upload init failed');
213
+ }
214
+ const uploadId = initData.data.uploadId;
215
+ const secret = initData.data.signing.secret;
216
+ console.log(` Upload session: ${uploadId}`);
217
+ // Step 2: Sign and upload report
218
+ const signature = crypto.createHmac('sha256', secret).update(reportJson).digest('hex');
219
+ const uploadResponse = await fetch(`${apiUrl}/api/upload/${uploadId}`, {
220
+ method: 'PUT',
221
+ headers: {
222
+ 'Authorization': `Bearer ${pat}`,
223
+ 'Content-Type': 'application/json',
224
+ },
225
+ body: JSON.stringify({
226
+ report: Object.assign({}, report, {
227
+ integrity: {
228
+ report_hash: reportHash,
229
+ signature: signature,
230
+ algorithm: 'HMAC-SHA256',
231
+ },
232
+ }),
233
+ }),
234
+ });
235
+ if (!uploadResponse.ok) {
236
+ let payload = undefined;
237
+ try {
238
+ payload = await uploadResponse.json();
239
+ }
240
+ catch {
241
+ payload = await uploadResponse.text().catch(() => undefined);
242
+ }
243
+ const apiError = extractApiErrorPayload(payload);
244
+ const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
245
+ const message = apiError.message || `Upload failed: ${uploadResponse.status}`;
246
+ throw new Error(message + details);
247
+ }
248
+ console.log(' Report uploaded');
249
+ // Step 3: Finalize
250
+ const finalizeResponse = await fetch(`${apiUrl}/api/upload/${uploadId}/finalize`, {
251
+ method: 'POST',
252
+ headers: {
253
+ 'Authorization': `Bearer ${pat}`,
254
+ 'Content-Type': 'application/json',
255
+ 'Idempotency-Key': crypto.randomUUID(),
256
+ },
257
+ body: '{}',
258
+ });
259
+ if (!finalizeResponse.ok) {
260
+ let payload = undefined;
261
+ try {
262
+ payload = await finalizeResponse.json();
263
+ }
264
+ catch {
265
+ payload = await finalizeResponse.text().catch(() => undefined);
266
+ }
267
+ const apiError = extractApiErrorPayload(payload);
268
+ const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
269
+ const message = apiError.message || `Finalize failed: ${finalizeResponse.status}`;
270
+ throw new Error(message + details);
271
+ }
272
+ const finalizeData = await finalizeResponse.json();
273
+ if (!finalizeData.success) {
274
+ throw new Error(finalizeData.error?.message || 'Upload finalize failed');
275
+ }
276
+ console.log(`✅ Report finalized: ${finalizeData.data.reportId}`);
277
+ console.log(` Quota updated`);
278
+ }
279
+ catch (error) {
280
+ console.error('❌ Upload failed:', error instanceof Error ? error.message : String(error));
281
+ process.exit(1);
282
+ }
283
+ }
284
+ async function discoverFiles(rootPath, options) {
285
+ const files = [];
286
+ async function walk(dir) {
287
+ const entries = await fs.readdir(dir, { withFileTypes: true });
288
+ for (const entry of entries) {
289
+ const fullPath = path.join(dir, entry.name);
290
+ if (entry.isDirectory()) {
291
+ // Skip excluded directories
292
+ if (options.exclude.some(e => entry.name.includes(e)))
293
+ continue;
294
+ await walk(fullPath);
295
+ }
296
+ else if (entry.isFile()) {
297
+ // Check include patterns - support glob patterns like **/*.{ts,tsx}
298
+ const shouldInclude = options.include.some(pattern => {
299
+ // Handle brace expansion: **/*.{ts,tsx} → match **/*.ts or **/*.tsx
300
+ if (pattern.includes('{') && pattern.includes('}')) {
301
+ const braceMatch = pattern.match(/\{([^}]+)\}/);
302
+ if (braceMatch) {
303
+ const extensions = braceMatch[1].split(',');
304
+ const basePattern = pattern.replace(/\{[^}]+\}/, '');
305
+ return extensions.some(ext => {
306
+ const fullPattern = basePattern + ext;
307
+ return matchGlob(fullPath, fullPattern);
308
+ });
309
+ }
310
+ }
311
+ return matchGlob(fullPath, pattern);
312
+ });
313
+ if (shouldInclude) {
314
+ // Check file size
315
+ try {
316
+ const stats = await fs.stat(fullPath);
317
+ if (stats.size <= options.maxSize) {
318
+ files.push(fullPath);
319
+ }
320
+ }
321
+ catch {
322
+ // Skip files we can't stat
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+ await walk(rootPath);
329
+ return files;
330
+ }
331
+ function matchGlob(filePath, pattern) {
332
+ // Convert glob pattern to regex
333
+ // **/*.ts → matches any .ts file in any directory
334
+ // *.ts → matches .ts files in current directory
335
+ const fileName = filePath.split(/[/\\]/).pop() || '';
336
+ if (pattern.includes('**')) {
337
+ // Match any directory depth
338
+ const ext = pattern.replace('**/*', '');
339
+ return fileName.endsWith(ext);
340
+ }
341
+ else if (pattern.includes('*')) {
342
+ // Simple wildcard
343
+ const ext = pattern.replace('*', '');
344
+ return fileName.endsWith(ext);
345
+ }
346
+ // Exact match
347
+ return filePath.includes(pattern);
348
+ }
349
+ function renderProgressBar(percentage) {
350
+ const width = 20;
351
+ const filled = Math.round((percentage / 100) * width);
352
+ const empty = width - filled;
353
+ const filledBar = chalk.cyan('█'.repeat(filled));
354
+ const emptyBar = chalk.gray('░'.repeat(empty));
355
+ return `${filledBar}${emptyBar} ${chalk.bold(`${percentage}%`)}`;
356
+ }
357
+ // Helper to format duration
358
+ function formatDuration(ms) {
359
+ if (ms < 1000)
360
+ return `${ms}ms`;
361
+ return `${(ms / 1000).toFixed(2)}s`;
362
+ }
363
+ //# sourceMappingURL=analyze.js.map
@@ -0,0 +1,37 @@
1
+ import chalk from 'chalk';
2
+ import { startOAuthFlow, authenticateWithPAT, SecureTokenStore } from '../auth/secure-auth.js';
3
+ import { printSuccess, printInfo } from '../ui.js';
4
+ import prompts from 'prompts';
5
+ export async function loginCommand(options) {
6
+ // Check if already authenticated
7
+ if (await SecureTokenStore.hasTokens()) {
8
+ const overwrite = await prompts({
9
+ type: 'confirm',
10
+ name: 'value',
11
+ message: chalk.yellow('Already authenticated. Overwrite existing credentials?'),
12
+ initial: false,
13
+ });
14
+ if (!overwrite.value) {
15
+ printInfo('Login cancelled');
16
+ return;
17
+ }
18
+ }
19
+ if (options.token) {
20
+ // PAT authentication
21
+ await authenticateWithPAT(options.token);
22
+ }
23
+ else {
24
+ // OAuth2 flow
25
+ const method = options.method || 'oauth';
26
+ const success = await startOAuthFlow(method);
27
+ if (success) {
28
+ printSuccess('You are now logged in!');
29
+ printInfo('Run "delta whoami" to see your account info');
30
+ }
31
+ }
32
+ }
33
+ export async function logoutCommand() {
34
+ const { logout } = await import('../auth/secure-auth.js');
35
+ await logout();
36
+ }
37
+ //# sourceMappingURL=auth-new.js.map
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Enhanced Auth Commands - Professional CLI with interactive prompts
3
+ */
4
+ import * as fs from 'fs/promises';
5
+ import * as path from 'path';
6
+ import * as os from 'os';
7
+ import { icons, startSpinner, stopSpinner, printHeader, printSection, printSuccess, printError, printInfo, printKeyValue, printCommandHint, createTable, printWelcome, } from '../ui.js';
8
+ import { SecureTokenStore, startOAuthFlow } from '../auth/secure-auth.js';
9
+ const CONFIG_DIR = path.join(os.homedir(), '.delta');
10
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
11
+ async function loadConfig() {
12
+ try {
13
+ const data = await fs.readFile(CONFIG_FILE, 'utf-8');
14
+ return JSON.parse(data);
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ async function saveConfig(config) {
21
+ await fs.mkdir(CONFIG_DIR, { recursive: true });
22
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
23
+ }
24
+ export const authCommands = {
25
+ async login(options) {
26
+ printWelcome();
27
+ printHeader('Authentication');
28
+ const token = options.token ?? process.env.DELTA_PAT;
29
+ // If no token provided, use OAuth2 flow (opens browser)
30
+ if (!token) {
31
+ printInfo('No token provided. Starting OAuth2 authentication...');
32
+ printInfo('A browser window will open for you to sign in.');
33
+ console.log();
34
+ const success = await startOAuthFlow('oauth');
35
+ if (!success) {
36
+ printError('Authentication failed');
37
+ console.log();
38
+ printInfo('You can also authenticate using a Personal Access Token:');
39
+ printCommandHint('delta login --token <your-token>', '');
40
+ process.exit(1);
41
+ }
42
+ // OAuth flow already saved the token, just show success
43
+ printSuccess('Authentication successful! 🎉');
44
+ console.log();
45
+ printCommandHint('delta whoami', 'to see account details');
46
+ printCommandHint('delta analyze', 'to start analyzing code');
47
+ return;
48
+ }
49
+ // PAT Token flow (when token is provided)
50
+ // Validate token format
51
+ if (!token.startsWith('delta_pat_')) {
52
+ printError('Invalid PAT token format', 'Token should start with "delta_pat_"');
53
+ console.log();
54
+ printInfo('You can get your PAT from:');
55
+ printCommandHint('http://localhost:3000/dashboard/cli-tokens', '');
56
+ process.exit(1);
57
+ }
58
+ // Load existing config to get custom apiUrl if set
59
+ const existingConfig = await loadConfig();
60
+ const apiUrl = process.env.DELTA_API_URL || existingConfig.apiUrl || 'http://localhost:3000';
61
+ printSection('Connecting to Platform');
62
+ printKeyValue('API Endpoint', apiUrl);
63
+ console.log();
64
+ startSpinner('Verifying credentials...');
65
+ try {
66
+ const controller = new AbortController();
67
+ const timeout = setTimeout(() => controller.abort(), 10000);
68
+ const response = await fetch(`${apiUrl}/api/me/entitlements`, {
69
+ headers: {
70
+ 'Authorization': `Bearer ${token}`,
71
+ 'Content-Type': 'application/json',
72
+ },
73
+ signal: controller.signal,
74
+ });
75
+ clearTimeout(timeout);
76
+ if (!response.ok) {
77
+ const errorText = await response.text().catch(() => response.statusText);
78
+ throw new Error(`HTTP ${response.status}: ${errorText}`);
79
+ }
80
+ const data = await response.json();
81
+ if (!data.success) {
82
+ throw new Error(data.error?.message || 'Authentication failed');
83
+ }
84
+ // Save config - store PAT securely in keychain, NOT in config file
85
+ await SecureTokenStore.saveAccessToken(token);
86
+ // Save only non-sensitive config
87
+ await saveConfig({
88
+ apiUrl,
89
+ lastUsedAt: new Date().toISOString(),
90
+ });
91
+ stopSpinner(true, 'Authentication successful!');
92
+ console.log();
93
+ const user = data.data.user;
94
+ const quota = data.data.quota;
95
+ printHeader('Account Overview');
96
+ // User info table
97
+ const userTable = createTable(['Property', 'Value']);
98
+ userTable.push([icons.user + ' Email', user.email], [icons.package + ' Plan', user.plan], [icons.chart + ' Quota Used', `${quota.used}/${quota.limit} reports`], [icons.lock + ' Config', CONFIG_FILE]);
99
+ console.log(userTable.toString());
100
+ console.log();
101
+ printSuccess(`Welcome back, ${user.email.split('@')[0]}! 🎉`);
102
+ console.log();
103
+ printCommandHint('delta whoami', 'to see full account details');
104
+ printCommandHint('delta analyze', 'to start analyzing code');
105
+ }
106
+ catch (error) {
107
+ stopSpinner(false, 'Authentication failed');
108
+ console.log();
109
+ if (error instanceof Error && error.name === 'AbortError') {
110
+ printError('Request timeout (10s)', 'Check if the server is running and accessible');
111
+ }
112
+ else {
113
+ const message = error instanceof Error ? error.message : String(error);
114
+ if (message.includes('401')) {
115
+ printError('Invalid or expired token', 'Generate a new token from the web app');
116
+ }
117
+ else if (message.includes('ENOTFOUND') || message.includes('ECONNREFUSED')) {
118
+ printError('Cannot connect to server', 'Check your internet connection and API URL');
119
+ }
120
+ else {
121
+ printError(message);
122
+ }
123
+ }
124
+ console.log();
125
+ printInfo('Need help? Visit: http://localhost:3000/docs/cli/authentication');
126
+ process.exit(1);
127
+ }
128
+ },
129
+ };
130
+ // Export individual commands for direct import
131
+ export const loginCommand = authCommands.login;
132
+ export { loadConfig, saveConfig, CONFIG_FILE };
133
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Config Command - Manage CLI configuration
3
+ */
4
+ import { loadConfig, saveConfig, CONFIG_FILE } from './auth.js';
5
+ import { SecureTokenStore } from '../auth/secure-auth.js';
6
+ export async function configCommand(options) {
7
+ const config = await loadConfig();
8
+ if (options.get) {
9
+ const value = config[options.get];
10
+ if (value !== undefined) {
11
+ console.log(`${options.get}: ${value}`);
12
+ }
13
+ else {
14
+ console.log(`${options.get}: (not set)`);
15
+ }
16
+ return;
17
+ }
18
+ if (options.set) {
19
+ const [key, value] = options.set.split('=');
20
+ if (!key || value === undefined) {
21
+ console.error('❌ Error: Invalid format. Use: key=value');
22
+ process.exit(1);
23
+ }
24
+ const newConfig = {
25
+ ...config,
26
+ apiUrl: config.apiUrl || 'http://localhost:3000',
27
+ [key]: value,
28
+ };
29
+ await saveConfig(newConfig);
30
+ console.log(`✅ Set ${key} = ${value}`);
31
+ return;
32
+ }
33
+ if (options.list || (!options.get && !options.set)) {
34
+ console.log('🔧 Delta CLI Configuration');
35
+ console.log(` Config file: ${CONFIG_FILE}`);
36
+ console.log();
37
+ const hasPat = await SecureTokenStore.hasTokens();
38
+ if (hasPat) {
39
+ console.log(' PAT: ✅ Set (securely stored in keychain)');
40
+ }
41
+ else {
42
+ console.log(' PAT: ❌ Not set');
43
+ }
44
+ console.log(` API URL: ${config.apiUrl || 'http://localhost:3000 (default)'}`);
45
+ if (config.lastUsedAt) {
46
+ console.log(` Last used: ${new Date(config.lastUsedAt).toLocaleString()}`);
47
+ }
48
+ }
49
+ }
50
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,6 @@
1
+ import { printSuccess, printInfo } from '../ui.js';
2
+ export async function deployCommand(_options) {
3
+ printInfo('Deploying documentation site...');
4
+ printSuccess('Deploy completed successfully');
5
+ }
6
+ //# sourceMappingURL=deploy.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Init Command - Initialize a new Delta project
3
+ */
4
+ import * as fs from 'fs/promises';
5
+ import * as path from 'path';
6
+ export async function initCommand(projectPath, options) {
7
+ const targetPath = path.resolve(projectPath);
8
+ const configPath = path.join(targetPath, 'delta.config.json');
9
+ try {
10
+ // Check if directory exists
11
+ await fs.access(targetPath);
12
+ }
13
+ catch {
14
+ console.log(`📁 Creating directory: ${targetPath}`);
15
+ await fs.mkdir(targetPath, { recursive: true });
16
+ }
17
+ // Check if config already exists
18
+ try {
19
+ await fs.access(configPath);
20
+ if (!options.force) {
21
+ console.log('⚠️ Delta config already exists');
22
+ console.log(' Use --force to overwrite');
23
+ return;
24
+ }
25
+ }
26
+ catch {
27
+ // Config doesn't exist, continue
28
+ }
29
+ // Create default config
30
+ const config = {
31
+ name: path.basename(targetPath),
32
+ version: '1.0.0',
33
+ template: options.template || 'default',
34
+ createdAt: new Date().toISOString(),
35
+ settings: {
36
+ include: ['src/**/*'],
37
+ exclude: ['node_modules', 'dist', '.git'],
38
+ maxFileSize: 10485760,
39
+ },
40
+ };
41
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2));
42
+ console.log('✅ Project initialized');
43
+ console.log(` Path: ${targetPath}`);
44
+ console.log(` Config: ${configPath}`);
45
+ console.log(` Template: ${config.template}`);
46
+ }
47
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Logout Command - Remove stored authentication
3
+ */
4
+ import * as fs from 'fs/promises';
5
+ import { CONFIG_FILE } from './auth.js';
6
+ import { SecureTokenStore } from '../auth/secure-auth.js';
7
+ export async function logoutCommand() {
8
+ try {
9
+ const hasToken = await SecureTokenStore.hasTokens();
10
+ if (!hasToken) {
11
+ console.log('ℹ️ Not currently authenticated');
12
+ return;
13
+ }
14
+ // Clear tokens from keychain and remove config file
15
+ await SecureTokenStore.clearTokens();
16
+ try {
17
+ await fs.unlink(CONFIG_FILE);
18
+ }
19
+ catch {
20
+ // File may not exist, that's fine
21
+ }
22
+ console.log('✅ Successfully logged out');
23
+ console.log(' Authentication data removed');
24
+ }
25
+ catch (error) {
26
+ console.error('❌ Error during logout:', error instanceof Error ? error.message : String(error));
27
+ process.exit(1);
28
+ }
29
+ }
30
+ //# sourceMappingURL=logout.js.map