@vee-stack/delta-cli 2.0.8 → 2.0.10

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 (183) hide show
  1. package/dist/adapters/analysis.adapter.d.ts +29 -0
  2. package/dist/analyzer/commands/analyze.d.ts +14 -0
  3. package/dist/analyzer/commands/config.d.ts +12 -0
  4. package/dist/analyzer/commands/report.d.ts +11 -0
  5. package/dist/analyzer/generators/report.generator.d.ts +43 -0
  6. package/dist/analyzer/index.d.ts +8 -0
  7. package/dist/analyzer/scanners/project.scanner.d.ts +29 -0
  8. package/dist/analyzer/validators/contracts.validator.d.ts +27 -0
  9. package/dist/analyzer/validators/maintainability.validator.d.ts +27 -0
  10. package/dist/analyzer/validators/observability.validator.d.ts +27 -0
  11. package/dist/analyzer/validators/performance.validator.d.ts +27 -0
  12. package/dist/analyzer/validators/security.validator.d.ts +27 -0
  13. package/dist/analyzer/validators/soc.validator.d.ts +27 -0
  14. package/dist/auth/device-auth.d.ts +18 -0
  15. package/dist/auth/secure-auth.d.ts +35 -0
  16. package/dist/bundle.mjs +422 -0
  17. package/dist/commands/analyze.d.ts +12 -0
  18. package/dist/commands/auth-new.d.ts +6 -0
  19. package/dist/commands/auth.d.ts +17 -0
  20. package/dist/commands/config.d.ts +8 -0
  21. package/dist/commands/deploy.d.ts +5 -0
  22. package/dist/commands/init.d.ts +7 -0
  23. package/dist/commands/logout.d.ts +2 -0
  24. package/dist/commands/plugins.d.ts +7 -0
  25. package/dist/commands/status.d.ts +5 -0
  26. package/dist/commands/sync.d.ts +5 -0
  27. package/dist/commands/whoami.d.ts +4 -0
  28. package/dist/components/Dashboard.d.ts +8 -0
  29. package/dist/components/DeltaApp.d.ts +13 -0
  30. package/dist/components/UnifiedManager.d.ts +10 -0
  31. package/dist/core/audit.d.ts +60 -0
  32. package/dist/core/completion.d.ts +79 -0
  33. package/dist/core/contracts.d.ts +127 -0
  34. package/dist/core/engine.d.ts +26 -0
  35. package/dist/core/exit-codes.d.ts +19 -0
  36. package/dist/core/hooks.d.ts +50 -0
  37. package/dist/{apps/cli/src/core/index.js → core/index.d.ts} +1 -1
  38. package/dist/core/policy.d.ts +24 -0
  39. package/dist/core/profiles.d.ts +45 -0
  40. package/dist/core/wizard.d.ts +28 -0
  41. package/dist/interactive/index.d.ts +5 -0
  42. package/dist/plugins/GitStatusPlugin.d.ts +25 -0
  43. package/dist/providers/ai-provider.d.ts +21 -0
  44. package/dist/providers/local-provider.d.ts +21 -0
  45. package/dist/providers/remote-provider.d.ts +15 -0
  46. package/dist/telemetry/wrapper.d.ts +18 -0
  47. package/dist/types/api.d.ts +46 -0
  48. package/dist/ui.d.ts +52 -0
  49. package/dist/welcome.d.ts +8 -0
  50. package/package.json +8 -8
  51. package/dist/analyzer/commands/analyze.js +0 -260
  52. package/dist/analyzer/commands/config.js +0 -83
  53. package/dist/analyzer/commands/report.js +0 -38
  54. package/dist/analyzer/generators/report.generator.js +0 -123
  55. package/dist/analyzer/index.js +0 -44
  56. package/dist/analyzer/scanners/project.scanner.js +0 -92
  57. package/dist/analyzer/validators/contracts.validator.js +0 -42
  58. package/dist/analyzer/validators/maintainability.validator.js +0 -40
  59. package/dist/analyzer/validators/observability.validator.js +0 -39
  60. package/dist/analyzer/validators/performance.validator.js +0 -42
  61. package/dist/analyzer/validators/security.validator.js +0 -66
  62. package/dist/analyzer/validators/soc.validator.js +0 -75
  63. package/dist/apps/cli/src/analyzer/commands/analyze.js +0 -256
  64. package/dist/apps/cli/src/analyzer/commands/config.js +0 -83
  65. package/dist/apps/cli/src/analyzer/commands/report.js +0 -38
  66. package/dist/apps/cli/src/analyzer/generators/report.generator.js +0 -123
  67. package/dist/apps/cli/src/analyzer/index.js +0 -44
  68. package/dist/apps/cli/src/analyzer/scanners/project.scanner.js +0 -92
  69. package/dist/apps/cli/src/analyzer/validators/contracts.validator.js +0 -42
  70. package/dist/apps/cli/src/analyzer/validators/maintainability.validator.js +0 -40
  71. package/dist/apps/cli/src/analyzer/validators/observability.validator.js +0 -39
  72. package/dist/apps/cli/src/analyzer/validators/performance.validator.js +0 -42
  73. package/dist/apps/cli/src/analyzer/validators/security.validator.js +0 -66
  74. package/dist/apps/cli/src/analyzer/validators/soc.validator.js +0 -75
  75. package/dist/apps/cli/src/auth/secure-auth.js +0 -312
  76. package/dist/apps/cli/src/commands/analyze.js +0 -286
  77. package/dist/apps/cli/src/commands/auth-new.js +0 -37
  78. package/dist/apps/cli/src/commands/auth.js +0 -122
  79. package/dist/apps/cli/src/commands/config.js +0 -49
  80. package/dist/apps/cli/src/commands/deploy.js +0 -6
  81. package/dist/apps/cli/src/commands/init.js +0 -47
  82. package/dist/apps/cli/src/commands/logout.js +0 -23
  83. package/dist/apps/cli/src/commands/plugins.js +0 -21
  84. package/dist/apps/cli/src/commands/status.js +0 -80
  85. package/dist/apps/cli/src/commands/sync.js +0 -6
  86. package/dist/apps/cli/src/commands/whoami.js +0 -115
  87. package/dist/apps/cli/src/components/Dashboard.js +0 -168
  88. package/dist/apps/cli/src/components/DeltaApp.js +0 -56
  89. package/dist/apps/cli/src/components/UnifiedManager.js +0 -324
  90. package/dist/apps/cli/src/core/audit.js +0 -184
  91. package/dist/apps/cli/src/core/completion.js +0 -294
  92. package/dist/apps/cli/src/core/contracts.js +0 -6
  93. package/dist/apps/cli/src/core/engine.js +0 -124
  94. package/dist/apps/cli/src/core/exit-codes.js +0 -71
  95. package/dist/apps/cli/src/core/hooks.js +0 -181
  96. package/dist/apps/cli/src/core/policy.js +0 -115
  97. package/dist/apps/cli/src/core/profiles.js +0 -161
  98. package/dist/apps/cli/src/core/wizard.js +0 -203
  99. package/dist/apps/cli/src/index.js +0 -636
  100. package/dist/apps/cli/src/interactive/index.js +0 -11
  101. package/dist/apps/cli/src/plugins/GitStatusPlugin.js +0 -99
  102. package/dist/apps/cli/src/providers/ai-provider.js +0 -74
  103. package/dist/apps/cli/src/providers/local-provider.js +0 -302
  104. package/dist/apps/cli/src/providers/remote-provider.js +0 -100
  105. package/dist/apps/cli/src/types/api.js +0 -3
  106. package/dist/apps/cli/src/ui.js +0 -219
  107. package/dist/apps/cli/src/welcome.js +0 -81
  108. package/dist/auth/secure-auth.js +0 -372
  109. package/dist/bundle.js +0 -504
  110. package/dist/commands/analyze.js +0 -390
  111. package/dist/commands/auth-new.js +0 -37
  112. package/dist/commands/auth.js +0 -134
  113. package/dist/commands/config.js +0 -51
  114. package/dist/commands/deploy.js +0 -6
  115. package/dist/commands/init.js +0 -47
  116. package/dist/commands/logout.js +0 -31
  117. package/dist/commands/plugins.js +0 -21
  118. package/dist/commands/status.js +0 -82
  119. package/dist/commands/sync.js +0 -6
  120. package/dist/commands/whoami.js +0 -72
  121. package/dist/components/Dashboard.js +0 -169
  122. package/dist/components/DeltaApp.js +0 -57
  123. package/dist/components/UnifiedManager.js +0 -344
  124. package/dist/core/audit.js +0 -184
  125. package/dist/core/completion.js +0 -294
  126. package/dist/core/contracts.js +0 -6
  127. package/dist/core/engine.js +0 -124
  128. package/dist/core/exit-codes.js +0 -71
  129. package/dist/core/hooks.js +0 -181
  130. package/dist/core/index.js +0 -7
  131. package/dist/core/policy.js +0 -115
  132. package/dist/core/profiles.js +0 -161
  133. package/dist/core/wizard.js +0 -203
  134. package/dist/index.js +0 -387
  135. package/dist/interactive/index.js +0 -11
  136. package/dist/packages/domain/src/constitution/contracts/index.js +0 -43
  137. package/dist/packages/domain/src/constitution/contracts/ts.rules.js +0 -268
  138. package/dist/packages/domain/src/constitution/index.js +0 -139
  139. package/dist/packages/domain/src/constitution/maintainability/index.js +0 -43
  140. package/dist/packages/domain/src/constitution/maintainability/ts.rules.js +0 -344
  141. package/dist/packages/domain/src/constitution/observability/index.js +0 -43
  142. package/dist/packages/domain/src/constitution/observability/ts.rules.js +0 -307
  143. package/dist/packages/domain/src/constitution/performance/index.js +0 -43
  144. package/dist/packages/domain/src/constitution/performance/ts.rules.js +0 -325
  145. package/dist/packages/domain/src/constitution/security/index.js +0 -50
  146. package/dist/packages/domain/src/constitution/security/ts.rules.js +0 -267
  147. package/dist/packages/domain/src/constitution/soc/index.js +0 -43
  148. package/dist/packages/domain/src/constitution/soc/ts.rules.js +0 -360
  149. package/dist/packages/domain/src/contracts/analysis.contract.js +0 -18
  150. package/dist/packages/domain/src/contracts/index.js +0 -7
  151. package/dist/packages/domain/src/contracts/projects.contract.js +0 -18
  152. package/dist/packages/domain/src/control/registry/rules.registry.js +0 -29
  153. package/dist/packages/domain/src/control/schemas/policies.js +0 -6
  154. package/dist/packages/domain/src/core/analysis/discovery.js +0 -163
  155. package/dist/packages/domain/src/core/analysis/engine.contract.js +0 -298
  156. package/dist/packages/domain/src/core/analysis/engine.js +0 -77
  157. package/dist/packages/domain/src/core/analysis/index.js +0 -14
  158. package/dist/packages/domain/src/core/analysis/orchestrator.js +0 -242
  159. package/dist/packages/domain/src/core/comparison/engine.js +0 -29
  160. package/dist/packages/domain/src/core/comparison/index.js +0 -5
  161. package/dist/packages/domain/src/core/documentation/index.js +0 -5
  162. package/dist/packages/domain/src/core/documentation/pipeline.js +0 -41
  163. package/dist/packages/domain/src/core/fs/adapter.js +0 -111
  164. package/dist/packages/domain/src/core/fs/index.js +0 -5
  165. package/dist/packages/domain/src/core/parser/unified-parser.js +0 -166
  166. package/dist/packages/domain/src/index.js +0 -33
  167. package/dist/packages/domain/src/plugin/registry.js +0 -195
  168. package/dist/packages/domain/src/plugin/types.js +0 -6
  169. package/dist/packages/domain/src/ports/analysis.engine.js +0 -7
  170. package/dist/packages/domain/src/ports/audit.logger.js +0 -7
  171. package/dist/packages/domain/src/ports/project.repository.js +0 -7
  172. package/dist/packages/domain/src/rules/index.js +0 -134
  173. package/dist/packages/domain/src/types/analysis.js +0 -6
  174. package/dist/packages/domain/src/types/errors.js +0 -53
  175. package/dist/packages/domain/src/types/fs.js +0 -6
  176. package/dist/packages/domain/src/types/index.js +0 -7
  177. package/dist/plugins/GitStatusPlugin.js +0 -93
  178. package/dist/providers/ai-provider.js +0 -74
  179. package/dist/providers/local-provider.js +0 -304
  180. package/dist/providers/remote-provider.js +0 -100
  181. package/dist/types/api.js +0 -3
  182. package/dist/ui.js +0 -219
  183. package/dist/welcome.js +0 -81
@@ -1,390 +0,0 @@
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
- // Check authentication FIRST if upload is requested
26
- if (options.upload) {
27
- printInfo('🔐 Checking authentication...');
28
- await loadConfig();
29
- const pat = await SecureTokenStore.getAccessToken();
30
- if (!pat) {
31
- console.error();
32
- console.error(chalk.red('❌ Error: You must be logged in to upload reports.'));
33
- console.error();
34
- console.error(chalk.yellow('Please authenticate first:'));
35
- console.error(chalk.cyan(' delta login'));
36
- console.error();
37
- console.error(chalk.dim('Or use --upload with a valid PAT:'));
38
- console.error(chalk.cyan(' delta analyze . --upload --token <your-pat>'));
39
- console.error();
40
- process.exit(1);
41
- }
42
- printSuccess('✓ Authenticated');
43
- console.log();
44
- }
45
- printInfo('🔍 Starting Delta Analysis Engine...');
46
- printDivider();
47
- console.log(`${icons.folder} Project: ${chalk.cyan(targetPath)}`);
48
- console.log();
49
- // Phase 1: File Discovery
50
- startSpinner('Scanning project files...');
51
- const files = await discoverFiles(targetPath, {
52
- include: options.include ? [options.include] : ['**/*.{ts,tsx,js,jsx}'],
53
- exclude: options.exclude ? [options.exclude].concat(['node_modules', 'dist', '.git']) : ['node_modules', 'dist', '.git'],
54
- maxSize: parseInt(options.maxSize, 10),
55
- });
56
- stopSpinner(true, `Found ${files.length} files to analyze`);
57
- console.log();
58
- if (files.length === 0) {
59
- printWarning('No files found matching the criteria');
60
- printInfo('Try adjusting --include or --exclude patterns');
61
- process.exit(0);
62
- }
63
- // Phase 2: Analysis with Progress
64
- console.log(`${icons.loading} Analyzing ${files.length} files...`);
65
- console.log();
66
- const startTime = Date.now();
67
- const summary = {
68
- totalFiles: files.length,
69
- successfulParses: 0,
70
- failedParses: 0,
71
- totalLines: 0,
72
- totalFunctions: 0,
73
- totalClasses: 0,
74
- totalDuration: 0,
75
- errors: [],
76
- };
77
- const findings = [];
78
- // Process files with progress indication
79
- for (let i = 0; i < files.length; i++) {
80
- const file = files[i];
81
- const progress = Math.round(((i + 1) / files.length) * 100);
82
- const bar = renderProgressBar(progress);
83
- // Clear line and print progress
84
- process.stdout.write(`\r${bar} ${chalk.cyan(`${i + 1}/${files.length}`)} ${chalk.dim(file.split(/[/\\]/).pop() || '')}`);
85
- try {
86
- const content = await fs.readFile(file, 'utf-8');
87
- const lines = content.split('\n');
88
- summary.totalLines += lines.length;
89
- summary.successfulParses++;
90
- // Simple heuristics for demo
91
- if (content.includes('function '))
92
- summary.totalFunctions++;
93
- if (content.includes('class '))
94
- summary.totalClasses++;
95
- // Find potential issues
96
- if (content.includes('eval(')) {
97
- findings.push({
98
- file: path.relative(targetPath, file),
99
- type: 'security',
100
- severity: 'high',
101
- message: 'Use of eval() detected',
102
- });
103
- }
104
- if (content.includes('console.log')) {
105
- findings.push({
106
- file: path.relative(targetPath, file),
107
- type: 'maintainability',
108
- severity: 'low',
109
- message: 'Console.log statement found',
110
- });
111
- }
112
- }
113
- catch (error) {
114
- summary.failedParses++;
115
- summary.errors.push({
116
- file: path.relative(targetPath, file),
117
- error: error instanceof Error ? error.message : String(error),
118
- });
119
- }
120
- }
121
- // Clear progress line
122
- process.stdout.write('\r' + ' '.repeat(80) + '\r');
123
- console.log(`${icons.check} Analysis complete: ${chalk.green(`${summary.successfulParses} successful`)}, ${summary.failedParses > 0 ? chalk.red(`${summary.failedParses} failed`) : ''}`);
124
- console.log();
125
- summary.totalDuration = Date.now() - startTime;
126
- // Build report
127
- const report = {
128
- schema_version: '1.0',
129
- engine_version: '0.5.0',
130
- created_at: new Date().toISOString(),
131
- project: {
132
- name: options.projectName || path.basename(targetPath),
133
- root_fingerprint: '',
134
- path: targetPath,
135
- },
136
- tools_used: [
137
- { id: 'delta-core', version: '0.5.0', adapter_version: '0.5.0' },
138
- ],
139
- summary: {
140
- total: findings.length,
141
- high: findings.filter(f => f.severity === 'high').length,
142
- medium: findings.filter(f => f.severity === 'medium').length,
143
- low: findings.filter(f => f.severity === 'low').length,
144
- },
145
- findings,
146
- metadata: summary,
147
- };
148
- // Phase 3: Results Display
149
- printDivider();
150
- printSuccess('Analysis Complete');
151
- console.log();
152
- // Summary table
153
- const summaryTable = createTable(['Metric', 'Value']);
154
- 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)]);
155
- console.log(summaryTable.toString());
156
- console.log();
157
- // Findings summary
158
- if (findings.length > 0) {
159
- printWarning(`Found ${findings.length} issues:`);
160
- const issuesTable = createTable(['Severity', 'Count']);
161
- const highCount = findings.filter(f => f.severity === 'high').length;
162
- const mediumCount = findings.filter(f => f.severity === 'medium').length;
163
- const lowCount = findings.filter(f => f.severity === 'low').length;
164
- if (highCount > 0)
165
- issuesTable.push([chalk.red('🔴 High'), highCount.toString()]);
166
- if (mediumCount > 0)
167
- issuesTable.push([chalk.yellow('🟡 Medium'), mediumCount.toString()]);
168
- if (lowCount > 0)
169
- issuesTable.push([chalk.blue('🔵 Low'), lowCount.toString()]);
170
- console.log(issuesTable.toString());
171
- }
172
- else {
173
- printSuccess('✨ No issues found! Great job!');
174
- }
175
- console.log();
176
- // Save report to file ONLY if not uploading
177
- if (!options.upload) {
178
- const outputDir = path.resolve(options.output);
179
- await fs.mkdir(outputDir, { recursive: true });
180
- const reportFile = path.join(outputDir, `report-${Date.now()}.json`);
181
- await fs.writeFile(reportFile, JSON.stringify(report, null, 2));
182
- printInfo(`${icons.chart} Report saved: ${chalk.cyan(reportFile)}`);
183
- console.log();
184
- }
185
- else {
186
- printInfo(`${icons.chart} Report will be available on Delta Cloud Dashboard`);
187
- console.log();
188
- }
189
- // Upload to cloud if requested
190
- if (options.upload) {
191
- console.log(`${icons.rocket} Uploading to Delta Cloud...`);
192
- await uploadReport(report);
193
- }
194
- process.exit(0);
195
- }
196
- async function uploadReport(report) {
197
- const config = await loadConfig();
198
- // Get PAT from secure keychain storage, NOT from config file
199
- const pat = await SecureTokenStore.getAccessToken();
200
- if (!pat) {
201
- console.error('❌ Error: Not authenticated. Run: delta login --token <pat>');
202
- process.exit(1);
203
- }
204
- const apiUrl = process.env.DELTA_API_URL || config.apiUrl || 'http://localhost:3000';
205
- const reportJson = JSON.stringify(report);
206
- const reportHash = crypto.createHash('sha256').update(reportJson).digest('hex');
207
- try {
208
- // Step 1: Init upload session
209
- const initResponse = await fetch(`${apiUrl}/api/upload/init`, {
210
- method: 'POST',
211
- headers: {
212
- 'Authorization': `Bearer ${pat}`,
213
- 'Content-Type': 'application/json',
214
- 'Idempotency-Key': crypto.randomUUID(),
215
- },
216
- body: JSON.stringify({
217
- schemaVersion: '1.0',
218
- engineVersion: '0.5.0',
219
- reportHash: reportHash,
220
- reportSizeBytes: Buffer.byteLength(reportJson),
221
- toolsUsed: [{ id: 'delta-core', version: '0.5.0', adapterVersion: '0.5.0' }],
222
- }),
223
- });
224
- if (!initResponse.ok) {
225
- let payload = undefined;
226
- try {
227
- payload = await initResponse.json();
228
- }
229
- catch {
230
- payload = await initResponse.text().catch(() => undefined);
231
- }
232
- const apiError = extractApiErrorPayload(payload);
233
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
234
- const message = apiError.message || `Init failed: ${initResponse.status}`;
235
- throw new Error(message + details);
236
- }
237
- const initData = await initResponse.json();
238
- if (!initData.success) {
239
- throw new Error(initData.error?.message || 'Upload init failed');
240
- }
241
- const uploadId = initData.data.uploadId;
242
- const secret = initData.data.signing.secret;
243
- console.log(` Upload session: ${uploadId}`);
244
- // Step 2: Sign and upload report
245
- const signature = crypto.createHmac('sha256', secret).update(reportJson).digest('hex');
246
- const uploadResponse = await fetch(`${apiUrl}/api/upload/${uploadId}`, {
247
- method: 'PUT',
248
- headers: {
249
- 'Authorization': `Bearer ${pat}`,
250
- 'Content-Type': 'application/json',
251
- },
252
- body: JSON.stringify({
253
- report: Object.assign({}, report, {
254
- integrity: {
255
- report_hash: reportHash,
256
- signature: signature,
257
- algorithm: 'HMAC-SHA256',
258
- },
259
- }),
260
- }),
261
- });
262
- if (!uploadResponse.ok) {
263
- let payload = undefined;
264
- try {
265
- payload = await uploadResponse.json();
266
- }
267
- catch {
268
- payload = await uploadResponse.text().catch(() => undefined);
269
- }
270
- const apiError = extractApiErrorPayload(payload);
271
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
272
- const message = apiError.message || `Upload failed: ${uploadResponse.status}`;
273
- throw new Error(message + details);
274
- }
275
- console.log(' Report uploaded');
276
- // Step 3: Finalize
277
- const finalizeResponse = await fetch(`${apiUrl}/api/upload/${uploadId}/finalize`, {
278
- method: 'POST',
279
- headers: {
280
- 'Authorization': `Bearer ${pat}`,
281
- 'Content-Type': 'application/json',
282
- 'Idempotency-Key': crypto.randomUUID(),
283
- },
284
- body: '{}',
285
- });
286
- if (!finalizeResponse.ok) {
287
- let payload = undefined;
288
- try {
289
- payload = await finalizeResponse.json();
290
- }
291
- catch {
292
- payload = await finalizeResponse.text().catch(() => undefined);
293
- }
294
- const apiError = extractApiErrorPayload(payload);
295
- const details = apiError.details ? `\nDetails: ${JSON.stringify(apiError.details)}` : '';
296
- const message = apiError.message || `Finalize failed: ${finalizeResponse.status}`;
297
- throw new Error(message + details);
298
- }
299
- const finalizeData = await finalizeResponse.json();
300
- if (!finalizeData.success) {
301
- throw new Error(finalizeData.error?.message || 'Upload finalize failed');
302
- }
303
- console.log(`✅ Report finalized: ${finalizeData.data.reportId}`);
304
- console.log(` Quota updated`);
305
- }
306
- catch (error) {
307
- console.error('❌ Upload failed:', error instanceof Error ? error.message : String(error));
308
- process.exit(1);
309
- }
310
- }
311
- async function discoverFiles(rootPath, options) {
312
- const files = [];
313
- async function walk(dir) {
314
- const entries = await fs.readdir(dir, { withFileTypes: true });
315
- for (const entry of entries) {
316
- const fullPath = path.join(dir, entry.name);
317
- if (entry.isDirectory()) {
318
- // Skip excluded directories
319
- if (options.exclude.some(e => entry.name.includes(e)))
320
- continue;
321
- await walk(fullPath);
322
- }
323
- else if (entry.isFile()) {
324
- // Check include patterns - support glob patterns like **/*.{ts,tsx}
325
- const shouldInclude = options.include.some(pattern => {
326
- // Handle brace expansion: **/*.{ts,tsx} → match **/*.ts or **/*.tsx
327
- if (pattern.includes('{') && pattern.includes('}')) {
328
- const braceMatch = pattern.match(/\{([^}]+)\}/);
329
- if (braceMatch) {
330
- const extensions = braceMatch[1].split(',');
331
- const basePattern = pattern.replace(/\{[^}]+\}/, '');
332
- return extensions.some(ext => {
333
- const fullPattern = basePattern + ext;
334
- return matchGlob(fullPath, fullPattern);
335
- });
336
- }
337
- }
338
- return matchGlob(fullPath, pattern);
339
- });
340
- if (shouldInclude) {
341
- // Check file size
342
- try {
343
- const stats = await fs.stat(fullPath);
344
- if (stats.size <= options.maxSize) {
345
- files.push(fullPath);
346
- }
347
- }
348
- catch {
349
- // Skip files we can't stat
350
- }
351
- }
352
- }
353
- }
354
- }
355
- await walk(rootPath);
356
- return files;
357
- }
358
- function matchGlob(filePath, pattern) {
359
- // Convert glob pattern to regex
360
- // **/*.ts → matches any .ts file in any directory
361
- // *.ts → matches .ts files in current directory
362
- const fileName = filePath.split(/[/\\]/).pop() || '';
363
- if (pattern.includes('**')) {
364
- // Match any directory depth
365
- const ext = pattern.replace('**/*', '');
366
- return fileName.endsWith(ext);
367
- }
368
- else if (pattern.includes('*')) {
369
- // Simple wildcard
370
- const ext = pattern.replace('*', '');
371
- return fileName.endsWith(ext);
372
- }
373
- // Exact match
374
- return filePath.includes(pattern);
375
- }
376
- function renderProgressBar(percentage) {
377
- const width = 20;
378
- const filled = Math.round((percentage / 100) * width);
379
- const empty = width - filled;
380
- const filledBar = chalk.cyan('█'.repeat(filled));
381
- const emptyBar = chalk.gray('░'.repeat(empty));
382
- return `${filledBar}${emptyBar} ${chalk.bold(`${percentage}%`)}`;
383
- }
384
- // Helper to format duration
385
- function formatDuration(ms) {
386
- if (ms < 1000)
387
- return `${ms}ms`;
388
- return `${(ms / 1000).toFixed(2)}s`;
389
- }
390
- //# sourceMappingURL=analyze.js.map
@@ -1,37 +0,0 @@
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
@@ -1,134 +0,0 @@
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
- process.exit(0);
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
- process.exit(0);
106
- }
107
- catch (error) {
108
- stopSpinner(false, 'Authentication failed');
109
- console.log();
110
- if (error instanceof Error && error.name === 'AbortError') {
111
- printError('Request timeout (10s)', 'Check if the server is running and accessible');
112
- }
113
- else {
114
- const message = error instanceof Error ? error.message : String(error);
115
- if (message.includes('401')) {
116
- printError('Invalid or expired token', 'Generate a new token from the web app');
117
- }
118
- else if (message.includes('ENOTFOUND') || message.includes('ECONNREFUSED')) {
119
- printError('Cannot connect to server', 'Check your internet connection and API URL');
120
- }
121
- else {
122
- printError(message);
123
- }
124
- }
125
- console.log();
126
- printInfo('Need help? Visit: http://localhost:3000/docs/cli/authentication');
127
- process.exit(1);
128
- }
129
- },
130
- };
131
- // Export individual commands for direct import
132
- export const loginCommand = authCommands.login;
133
- export { loadConfig, saveConfig, CONFIG_FILE };
134
- //# sourceMappingURL=auth.js.map
@@ -1,51 +0,0 @@
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
- process.exit(0);
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
- process.exit(0);
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
- process.exit(0);
49
- }
50
- }
51
- //# sourceMappingURL=config.js.map
@@ -1,6 +0,0 @@
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
@@ -1,47 +0,0 @@
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