@dataparade/cli 0.0.29 → 0.0.31

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 (24) hide show
  1. package/dist/package.json +3 -3
  2. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +6 -1
  3. package/dist/src/cli/scan-interrupt-handlers.d.ts +34 -0
  4. package/dist/src/cli/scan-interrupt-handlers.js +105 -0
  5. package/dist/src/cli.js +99 -28
  6. package/dist/src/config/scan-env.d.ts +5 -2
  7. package/dist/src/config/scan-env.js +8 -2
  8. package/dist/src/platform-api/scan-quota-client.d.ts +3 -1
  9. package/dist/src/platform-api/scan-quota-client.js +41 -28
  10. package/dist/src/ui/scan-progress-renderer.d.ts +24 -0
  11. package/dist/src/ui/scan-progress-renderer.js +91 -0
  12. package/dist/src/ui/types.d.ts +5 -0
  13. package/dist/tests/unit/ai-enrichment/platform-proxy-provider.spec.js +26 -0
  14. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.d.ts +1 -0
  15. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.js +154 -0
  16. package/dist/tests/unit/cli/scan-quota-flow.spec.js +2 -2
  17. package/dist/tests/unit/platform-api/read-cli-api-error-message.spec.js +2 -2
  18. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +134 -0
  19. package/dist/vendor/scanner/dist/src/core/pipeline/diagram-layout/constants.d.ts +2 -0
  20. package/dist/vendor/scanner/dist/src/core/pipeline/diagram-layout/constants.js +3 -1
  21. package/dist/vendor/scanner/dist/src/core/pipeline/diagram-layout/section-packing.d.ts +9 -0
  22. package/dist/vendor/scanner/dist/src/core/pipeline/diagram-layout/section-packing.js +40 -0
  23. package/dist/vendor/scanner/dist/src/core/pipeline/graph-mapping.js +2 -0
  24. package/package.json +3 -3
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.29",
3
+ "version": "0.0.31",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "@clack/prompts": "^1.8.1",
58
- "@sentry/node": "^10.38.0",
58
+ "@sentry/node": "^10.75.2",
59
59
  "commander": "^14.0.3",
60
60
  "dotenv": "^16.4.7",
61
61
  "langsmith": "^0.10.13",
@@ -66,7 +66,7 @@
66
66
  "zod": "^4.3.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@dataparade/scanner": "github:DataParade-io/scanner#6a5a95897fe9ccd60230b0636f3a91b2e21a1ab1",
69
+ "@dataparade/scanner": "github:DataParade-io/scanner#dc6104f9108cbb3647eb595861e73090f3cc257a",
70
70
  "@eslint/js": "^9.18.0",
71
71
  "@types/jest": "^30.0.0",
72
72
  "@types/node": "^22.0.0",
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PlatformProxyProvider = void 0;
4
4
  const lambda_init_error_1 = require("../lambda-init-error");
5
5
  const fetch_failure_1 = require("../../platform-api/fetch-failure");
6
+ const scan_env_1 = require("../../config/scan-env");
6
7
  const DEFAULT_NETWORK_RETRY_DELAYS_MS = [1000, 2000];
7
8
  function resolvePollTimeoutMs(configured) {
8
9
  if (typeof configured === 'number' &&
@@ -95,7 +96,11 @@ class PlatformProxyProvider {
95
96
  if (attempt >= delays.length || !(0, fetch_failure_1.isTransientFetchError)(err)) {
96
97
  throw (0, fetch_failure_1.toApiReachabilityError)(err, url, method, attempt + 1);
97
98
  }
98
- console.warn(`[dataparade-ai] ${(0, fetch_failure_1.describeRequestTarget)(url, method)} failed (${(0, fetch_failure_1.fetchFailureDetail)(err)}). Retrying (${attempt + 1}/${delays.length}).`);
99
+ // The Clack UI owns the terminal; a final failure still surfaces
100
+ // through the scan error ("Tried N times").
101
+ if (!(0, scan_env_1.isScanAiDebugSuppressed)()) {
102
+ console.warn(`[dataparade-ai] ${(0, fetch_failure_1.describeRequestTarget)(url, method)} failed (${(0, fetch_failure_1.fetchFailureDetail)(err)}). Retrying (${attempt + 1}/${delays.length}).`);
103
+ }
99
104
  await this.wait(delays[attempt] ?? 0);
100
105
  }
101
106
  }
@@ -0,0 +1,34 @@
1
+ export type CliScanQuotaCompletionStatus = 'none' | 'in_flight' | 'done';
2
+ export type CliScanInterruptSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP';
3
+ export declare const CLI_SCAN_INTERRUPT_EXIT_CODES: Record<CliScanInterruptSignal, number>;
4
+ /** Cap how long Ctrl+C waits on a hung complete API before exiting. */
5
+ export declare const CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = 2500;
6
+ export type CliScanInterruptProcess = {
7
+ on(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
8
+ off?(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
9
+ removeListener?(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
10
+ };
11
+ export type InstallCliScanInterruptHandlersInput = {
12
+ proc: CliScanInterruptProcess;
13
+ exit: (code: number) => void;
14
+ getState: () => {
15
+ apiKey?: string;
16
+ jobId?: string;
17
+ completionStatus: CliScanQuotaCompletionStatus;
18
+ /** Pending normal-path complete, awaited (bounded) instead of duplicated. */
19
+ inFlight?: Promise<unknown>;
20
+ };
21
+ /** Claim the completion so the scan's own paths don't report it again. */
22
+ setCompletionStatus: (status: CliScanQuotaCompletionStatus) => void;
23
+ onAbortUi: () => void;
24
+ reportFailed: (input: {
25
+ apiKey: string;
26
+ jobId: string;
27
+ timeoutMs: number;
28
+ }) => Promise<void>;
29
+ };
30
+ /**
31
+ * Release the CLI scan lock on Ctrl+C / kill / hangup, then exit.
32
+ * Returns uninstall(); safe to call more than once.
33
+ */
34
+ export declare function installCliScanInterruptHandlers(input: InstallCliScanInterruptHandlersInput): () => void;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = exports.CLI_SCAN_INTERRUPT_EXIT_CODES = void 0;
4
+ exports.installCliScanInterruptHandlers = installCliScanInterruptHandlers;
5
+ exports.CLI_SCAN_INTERRUPT_EXIT_CODES = {
6
+ SIGINT: 130,
7
+ SIGTERM: 143,
8
+ SIGHUP: 129,
9
+ };
10
+ /** Cap how long Ctrl+C waits on a hung complete API before exiting. */
11
+ exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = 2_500;
12
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
13
+ /** Below this, a follow-up report can't realistically land before exit. */
14
+ const MIN_REPORT_WINDOW_MS = 250;
15
+ /** Resolve when `promise` settles or `ms` elapses, whichever comes first. */
16
+ async function settleWithin(promise, ms) {
17
+ let timer;
18
+ try {
19
+ await Promise.race([
20
+ promise.then(() => undefined, () => undefined),
21
+ new Promise((resolve) => {
22
+ timer = setTimeout(resolve, ms);
23
+ }),
24
+ ]);
25
+ }
26
+ finally {
27
+ if (timer)
28
+ clearTimeout(timer);
29
+ }
30
+ }
31
+ /**
32
+ * Release the CLI scan lock on Ctrl+C / kill / hangup, then exit.
33
+ * Returns uninstall(); safe to call more than once.
34
+ */
35
+ function installCliScanInterruptHandlers(input) {
36
+ let handling = false;
37
+ let uninstalled = false;
38
+ const remove = (event, listener) => {
39
+ if (typeof input.proc.off === 'function') {
40
+ input.proc.off(event, listener);
41
+ return;
42
+ }
43
+ if (typeof input.proc.removeListener === 'function') {
44
+ input.proc.removeListener(event, listener);
45
+ }
46
+ };
47
+ const onSignal = (signal) => {
48
+ const code = exports.CLI_SCAN_INTERRUPT_EXIT_CODES[signal];
49
+ if (handling) {
50
+ input.exit(code);
51
+ return;
52
+ }
53
+ handling = true;
54
+ void (async () => {
55
+ const deadline = Date.now() + exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS;
56
+ try {
57
+ input.onAbortUi();
58
+ const pending = input.getState();
59
+ if (pending.completionStatus === 'in_flight' && pending.inFlight) {
60
+ // Let the scan's own complete land; exiting now could cut it off.
61
+ await settleWithin(pending.inFlight, deadline - Date.now());
62
+ }
63
+ // Re-read: a failed in-flight complete resets the status to 'none'.
64
+ const state = input.getState();
65
+ const remainingMs = deadline - Date.now();
66
+ if (state.apiKey &&
67
+ state.jobId &&
68
+ state.completionStatus === 'none' &&
69
+ remainingMs >= MIN_REPORT_WINDOW_MS) {
70
+ input.setCompletionStatus('in_flight');
71
+ try {
72
+ await input.reportFailed({
73
+ apiKey: state.apiKey,
74
+ jobId: state.jobId,
75
+ timeoutMs: remainingMs,
76
+ });
77
+ }
78
+ catch {
79
+ // Lock release must not block exit.
80
+ }
81
+ // Exiting either way; keep the scan's finally from reporting again.
82
+ input.setCompletionStatus('done');
83
+ }
84
+ }
85
+ finally {
86
+ input.exit(code);
87
+ }
88
+ })();
89
+ };
90
+ const listeners = SIGNALS.map((signal) => {
91
+ const listener = () => {
92
+ onSignal(signal);
93
+ };
94
+ input.proc.on(signal, listener);
95
+ return { signal, listener };
96
+ });
97
+ return () => {
98
+ if (uninstalled)
99
+ return;
100
+ uninstalled = true;
101
+ for (const { signal, listener } of listeners) {
102
+ remove(signal, listener);
103
+ }
104
+ };
105
+ }
package/dist/src/cli.js CHANGED
@@ -64,6 +64,7 @@ const telemetry_client_1 = require("./platform-api/telemetry-client");
64
64
  const cli_scan_failure_report_1 = require("./platform-api/cli-scan-failure-report");
65
65
  const scan_config_schema_1 = require("./core/schema/scan-config.schema");
66
66
  const scanner_1 = require("../vendor/scanner/dist/src/index.js");
67
+ const scan_interrupt_handlers_1 = require("./cli/scan-interrupt-handlers");
67
68
  const scan_progress_renderer_1 = require("./ui/scan-progress-renderer");
68
69
  /** The scanner is vendored into the CLI; its version is the commit the CLI depends on. */
69
70
  function scannerVersionFromPackage() {
@@ -191,7 +192,9 @@ function createProgram() {
191
192
  .action(async (path, options) => {
192
193
  let cliQuotaJobId;
193
194
  let platformQuotaApiKey;
194
- let quotaCompletionReported = false;
195
+ let progressUi;
196
+ let quotaCompletionStatus = 'none';
197
+ let quotaCompletionInFlight;
195
198
  let fallbackFailureMessage = 'CLI scan did not complete successfully';
196
199
  let reportedFailure;
197
200
  let sentryScanRoot;
@@ -201,6 +204,15 @@ function createProgram() {
201
204
  // True once Clack owns the terminal: raw `[scan]` lines would break its
202
205
  // guide rail, so they go through the renderer or are skipped.
203
206
  let friendlyTty = false;
207
+ // Errors close the Clack UI as a plain sentence; logs (CI, non-TTY)
208
+ // keep the `[scan] …:` prefix so they stay greppable.
209
+ const reportScanError = (logLine, friendlyText) => {
210
+ if (friendlyTty && progressUi) {
211
+ progressUi.fail(friendlyText);
212
+ return;
213
+ }
214
+ console.error(logLine);
215
+ };
204
216
  // Parse and validate --git-context if provided
205
217
  let parsedGitContext;
206
218
  if (options.gitContext) {
@@ -236,6 +248,35 @@ function createProgram() {
236
248
  apiKey: workspaceApiKey,
237
249
  cliVersion: package_json_1.default.version,
238
250
  });
251
+ const uninstallInterruptHandlers = (0, scan_interrupt_handlers_1.installCliScanInterruptHandlers)({
252
+ proc: process,
253
+ exit: (code) => {
254
+ process.exit(code);
255
+ },
256
+ getState: () => ({
257
+ apiKey: platformQuotaApiKey,
258
+ jobId: cliQuotaJobId,
259
+ completionStatus: quotaCompletionStatus,
260
+ inFlight: quotaCompletionInFlight,
261
+ }),
262
+ setCompletionStatus: (status) => {
263
+ quotaCompletionStatus = status;
264
+ },
265
+ onAbortUi: () => {
266
+ progressUi?.abort('Scan cancelled');
267
+ },
268
+ reportFailed: async ({ apiKey, jobId, timeoutMs }) => {
269
+ const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
270
+ await cliScanComplete({
271
+ apiKey,
272
+ jobId,
273
+ status: 'failed',
274
+ failureCode: 'scan_interrupted',
275
+ failureMessage: 'You stopped this scan',
276
+ timeoutMs,
277
+ });
278
+ },
279
+ });
239
280
  try {
240
281
  const rootPathArg = path || '.';
241
282
  // Load dataparade.config.json from the directory being scanned, not
@@ -268,15 +309,16 @@ function createProgram() {
268
309
  Promise.resolve().then(() => __importStar(require('./core/pipeline/scan-pipeline'))),
269
310
  Promise.resolve().then(() => __importStar(require('./core/pipeline/graph-mapping'))),
270
311
  ]);
271
- const progressUi = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
312
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
272
313
  isTTY: Boolean(isInteractive),
273
314
  noColor: Boolean(typeof process.env.NO_COLOR === 'string' &&
274
315
  process.env.NO_COLOR.length > 0),
275
316
  projectLabel: resolvedScanRoot,
276
317
  version: package_json_1.default.version,
277
318
  });
278
- progressUi.start();
279
- friendlyTty = progressUi.usesClackChrome;
319
+ progressUi = ui;
320
+ ui.start();
321
+ friendlyTty = ui.usesClackChrome;
280
322
  (0, scan_env_1.setScanAiDebugSuppressed)(friendlyTty && !options.aiVerbose);
281
323
  // Technical meters, shown as one block after the scan (TTY) or
282
324
  // printed as before (non-TTY).
@@ -348,7 +390,7 @@ function createProgram() {
348
390
  config.cliQuotaJobId = undefined;
349
391
  config.anonSessionToken = undefined;
350
392
  sentryAiMode = 'none';
351
- progressUi.warn(`AI enrichment unavailable (${(0, fetch_failure_1.describeUnavailableReason)(setupError)}); continuing with a structural scan. Use --no-ai-inference to skip this step.`);
393
+ ui.warn(`AI enrichment unavailable (${(0, fetch_failure_1.describeUnavailableReason)(setupError)}); continuing with a structural scan. Use --no-ai-inference to skip this step.`);
352
394
  };
353
395
  // Quota preflight for platform billing. Structural-only scans (AI off) do not use quota API.
354
396
  if (workspaceApiKey && !usesByok && config.enableAiInference) {
@@ -449,14 +491,17 @@ function createProgram() {
449
491
  failurePhase: 'config_validation',
450
492
  failureCode: 'invalid_configuration',
451
493
  });
452
- console.error(`[scan] invalid configuration:\n${configValidation.errors.map((e) => ` - ${e}`).join('\n')}`);
494
+ const configErrors = configValidation.errors
495
+ .map((e) => ` - ${e}`)
496
+ .join('\n');
497
+ reportScanError(`[scan] invalid configuration:\n${configErrors}`, `Invalid configuration:\n${configErrors}`);
453
498
  process.exitCode = 2;
454
499
  return;
455
500
  }
456
501
  if (isInteractive && warnings.length > 0) {
457
502
  if (friendlyTty) {
458
503
  for (const w of warnings)
459
- progressUi.warn(w);
504
+ ui.warn(w);
460
505
  }
461
506
  else {
462
507
  console.warn(`[scan] warnings:\n${warnings.map((w) => ` - ${w}`).join('\n')}`);
@@ -470,13 +515,13 @@ function createProgram() {
470
515
  progressUi.warn(tree.warning);
471
516
  }
472
517
  const orchestratorResult = await runScanPipeline(resolvedScanRoot, config, (progress) => {
473
- progressUi.onProgress(progress);
518
+ ui.onProgress(progress);
474
519
  }, (recognition) => {
475
- progressUi.onRecognition(recognition);
520
+ ui.onRecognition(recognition);
476
521
  });
477
522
  const { scanResult, redFlags } = orchestratorResult;
478
523
  if (scanResult.aiInferenceSummary) {
479
- progressUi.onAiResult({
524
+ ui.onAiResult({
480
525
  proposalsApplied: scanResult.aiInferenceSummary.proposalsApplied,
481
526
  });
482
527
  }
@@ -504,7 +549,7 @@ function createProgram() {
504
549
  }
505
550
  // Friendly TTY only shows the block on request (--ai-verbose).
506
551
  if (!friendlyTty || options.aiVerbose) {
507
- progressUi.showTechnicalDetails('Scan details', technicalLines);
552
+ ui.showTechnicalDetails('Scan details', technicalLines);
508
553
  }
509
554
  for (const w of scanResult.warnings ?? []) {
510
555
  if (w.startsWith('ai-provider:')) {
@@ -517,10 +562,10 @@ function createProgram() {
517
562
  failurePhase: 'ai_provider',
518
563
  failureCode: 'ai_provider_warning',
519
564
  });
520
- progressUi.warn(w);
565
+ ui.warn(w);
521
566
  }
522
567
  else if (w.startsWith('red-flag:')) {
523
- progressUi.warn(w);
568
+ ui.warn(w);
524
569
  }
525
570
  }
526
571
  if (scanResult.errors?.length) {
@@ -564,7 +609,7 @@ function createProgram() {
564
609
  const message = graphError instanceof Error
565
610
  ? graphError.message
566
611
  : 'Unknown error while building diagram graph.';
567
- console.error(`[scan] warning: unable to build diagram graph: ${message}`);
612
+ reportScanError(`[scan] warning: unable to build diagram graph: ${message}`, `Could not build the diagram: ${message}`);
568
613
  }
569
614
  process.exitCode = 1;
570
615
  }
@@ -593,7 +638,7 @@ function createProgram() {
593
638
  scannerVersion: scannerVersionFromPackage(),
594
639
  });
595
640
  // Friendly TTY/plain progress line (additive).
596
- progressUi.onWroteDataflow(dataflowOutputPath);
641
+ ui.onWroteDataflow(dataflowOutputPath);
597
642
  // Machine line for scripts / CI (non-TTY). The friendly TTY UI
598
643
  // shows the path in its own success line instead.
599
644
  if (!friendlyTty) {
@@ -624,7 +669,7 @@ function createProgram() {
624
669
  quiet: friendlyTty,
625
670
  });
626
671
  if (uploadResult.previewUrl) {
627
- progressUi.onPreviewUrl(uploadResult.previewUrl, uploadResult.notice);
672
+ ui.onPreviewUrl(uploadResult.previewUrl, uploadResult.notice);
628
673
  }
629
674
  }
630
675
  catch (uploadError) {
@@ -632,7 +677,7 @@ function createProgram() {
632
677
  ? uploadError.message
633
678
  : 'Unknown upload error.';
634
679
  if (friendlyTty) {
635
- progressUi.warn(`Auto-upload failed: ${uploadMessage}`);
680
+ ui.warn(`Auto-upload failed: ${uploadMessage}`);
636
681
  }
637
682
  else {
638
683
  console.error(`[scan] Auto-upload failed: ${uploadMessage}`);
@@ -642,7 +687,7 @@ function createProgram() {
642
687
  progressUi.onUploadFailed(describeAutoUploadFailure(uploadError, dataflowOutputPath, Boolean(workspaceApiKey)));
643
688
  }
644
689
  }
645
- progressUi.finish();
690
+ ui.finish();
646
691
  }
647
692
  catch (dataflowError) {
648
693
  reportedFailure = {
@@ -663,15 +708,18 @@ function createProgram() {
663
708
  const message = dataflowError instanceof Error
664
709
  ? dataflowError.message
665
710
  : 'Unknown error while writing dataflow.json.';
666
- console.error(`[scan] error: failed to write dataflow.json: ${message}`);
711
+ reportScanError(`[scan] error: failed to write dataflow.json: ${message}`, `Could not save dataflow.json: ${message}`);
667
712
  process.exitCode = 1;
668
713
  }
669
714
  }
670
- if (platformQuotaApiKey && cliQuotaJobId) {
715
+ if (platformQuotaApiKey &&
716
+ cliQuotaJobId &&
717
+ quotaCompletionStatus === 'none') {
671
718
  const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
672
719
  const exitFailed = (process.exitCode ?? 0) !== 0;
673
720
  const platformAiMode = (0, validate_scan_ai_1.resolveAiMode)(config) === 'platform';
674
- await cliScanComplete({
721
+ quotaCompletionStatus = 'in_flight';
722
+ quotaCompletionInFlight = cliScanComplete({
675
723
  apiKey: platformQuotaApiKey,
676
724
  jobId: cliQuotaJobId,
677
725
  status: exitFailed ? 'failed' : 'completed',
@@ -685,7 +733,18 @@ function createProgram() {
685
733
  ? (reportedFailure?.message ?? fallbackFailureMessage)
686
734
  : undefined,
687
735
  });
688
- quotaCompletionReported = true;
736
+ try {
737
+ await quotaCompletionInFlight;
738
+ quotaCompletionStatus = 'done';
739
+ }
740
+ catch (completeError) {
741
+ // Not reported: let the finally (or an interrupt) retry as failed.
742
+ quotaCompletionStatus = 'none';
743
+ throw completeError;
744
+ }
745
+ finally {
746
+ quotaCompletionInFlight = undefined;
747
+ }
689
748
  // The Clack outro already closes the run in friendly TTY.
690
749
  if (isInteractive && !friendlyTty) {
691
750
  console.log('[scan] Scan finished — you can start a new scan now.');
@@ -719,11 +778,13 @@ function createProgram() {
719
778
  ? 'scan_already_running'
720
779
  : 'scan_exception',
721
780
  });
722
- console.error(quotaBlocked
781
+ // Clack: the error closes the live spinner. A raw line would land
782
+ // mid-spinner and Clack would add its own "Canceled" on exit.
783
+ reportScanError(quotaBlocked
723
784
  ? `[scan] workspace quota: ${message}`
724
785
  : scanInProgress
725
786
  ? `[scan] scan in progress: ${message}`
726
- : `Scan failed: ${message}`);
787
+ : `Scan failed: ${message}`, quotaBlocked || scanInProgress ? message : `Scan failed: ${message}`);
727
788
  process.exitCode = 1;
728
789
  }
729
790
  finally {
@@ -744,25 +805,35 @@ function createProgram() {
744
805
  });
745
806
  if (platformQuotaApiKey &&
746
807
  cliQuotaJobId &&
747
- !quotaCompletionReported) {
808
+ quotaCompletionStatus === 'none') {
748
809
  try {
749
810
  const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
750
- await cliScanComplete({
811
+ quotaCompletionStatus = 'in_flight';
812
+ quotaCompletionInFlight = cliScanComplete({
751
813
  apiKey: platformQuotaApiKey,
752
814
  jobId: cliQuotaJobId,
753
815
  status: 'failed',
754
816
  failureCode: reportedFailure?.code ?? 'scan_failed',
755
817
  failureMessage: reportedFailure?.message ?? fallbackFailureMessage,
756
818
  });
757
- quotaCompletionReported = true;
758
- if (isInteractive) {
819
+ await quotaCompletionInFlight;
820
+ quotaCompletionStatus = 'done';
821
+ // Clack already closed the run with the error line.
822
+ if (isInteractive && !friendlyTty) {
759
823
  console.log('[scan] Scan finished — you can start a new scan now.');
760
824
  }
761
825
  }
762
826
  catch {
763
827
  // Quota report failure must not mask the original scan error.
828
+ quotaCompletionStatus = 'none';
829
+ }
830
+ finally {
831
+ quotaCompletionInFlight = undefined;
764
832
  }
765
833
  }
834
+ // Last: Ctrl+C during the usage event or complete above must still
835
+ // release the lock.
836
+ uninstallInterruptHandlers();
766
837
  }
767
838
  });
768
839
  program
@@ -5,9 +5,12 @@ export declare function resolveByokModel(env: NodeJS.ProcessEnv): string | undef
5
5
  export declare function resolveScanAiInference(env: NodeJS.ProcessEnv): string | undefined;
6
6
  export declare function resolveHostedInferProxyUrl(env: NodeJS.ProcessEnv): string | undefined;
7
7
  /**
8
- * Mute SCAN_AI_DEBUG logs for this run. The interactive progress UI sets this:
9
- * raw `[dataparade-ai]` lines written mid-spinner break its layout.
8
+ * Mute SCAN_AI_DEBUG logs and transient AI notices (e.g. network retries) for
9
+ * this run. The interactive progress UI sets this: raw `[dataparade-ai]` lines
10
+ * written mid-spinner break its layout.
10
11
  */
11
12
  export declare function setScanAiDebugSuppressed(suppressed: boolean): void;
13
+ /** True while the interactive UI owns the terminal (see setScanAiDebugSuppressed). */
14
+ export declare function isScanAiDebugSuppressed(): boolean;
12
15
  /** Extra provider HTTP / normalization logging (all providers, not OpenAI-only). */
13
16
  export declare function isScanAiDebugEnabled(env?: NodeJS.ProcessEnv): boolean;
@@ -7,6 +7,7 @@ exports.resolveByokModel = resolveByokModel;
7
7
  exports.resolveScanAiInference = resolveScanAiInference;
8
8
  exports.resolveHostedInferProxyUrl = resolveHostedInferProxyUrl;
9
9
  exports.setScanAiDebugSuppressed = setScanAiDebugSuppressed;
10
+ exports.isScanAiDebugSuppressed = isScanAiDebugSuppressed;
10
11
  exports.isScanAiDebugEnabled = isScanAiDebugEnabled;
11
12
  function resolveWorkspaceApiKey(env) {
12
13
  const value = env.DATAPARADE_WORKSPACE_API_KEY?.trim();
@@ -40,12 +41,17 @@ function parseTruthyEnvFlag(value) {
40
41
  }
41
42
  let scanAiDebugSuppressed = false;
42
43
  /**
43
- * Mute SCAN_AI_DEBUG logs for this run. The interactive progress UI sets this:
44
- * raw `[dataparade-ai]` lines written mid-spinner break its layout.
44
+ * Mute SCAN_AI_DEBUG logs and transient AI notices (e.g. network retries) for
45
+ * this run. The interactive progress UI sets this: raw `[dataparade-ai]` lines
46
+ * written mid-spinner break its layout.
45
47
  */
46
48
  function setScanAiDebugSuppressed(suppressed) {
47
49
  scanAiDebugSuppressed = suppressed;
48
50
  }
51
+ /** True while the interactive UI owns the terminal (see setScanAiDebugSuppressed). */
52
+ function isScanAiDebugSuppressed() {
53
+ return scanAiDebugSuppressed;
54
+ }
49
55
  /** Extra provider HTTP / normalization logging (all providers, not OpenAI-only). */
50
56
  function isScanAiDebugEnabled(env = process.env) {
51
57
  if (scanAiDebugSuppressed)
@@ -26,8 +26,10 @@ export declare function cliScanPreflight(input: {
26
26
  export declare function cliScanComplete(input: {
27
27
  apiKey: string;
28
28
  jobId: string;
29
- status: "completed" | "failed";
29
+ status: 'completed' | 'failed';
30
30
  aiTokensUsed?: number;
31
31
  failureCode?: string;
32
32
  failureMessage?: string;
33
+ /** Optional fetch abort timeout (e.g. interrupt path). */
34
+ timeoutMs?: number;
33
35
  }): Promise<void>;
@@ -9,8 +9,8 @@ const read_cli_api_error_message_1 = require("./read-cli-api-error-message");
9
9
  class CliScanQuotaExceededError extends Error {
10
10
  constructor(message) {
11
11
  super(message);
12
- this.code = "scan_quota_exceeded";
13
- this.name = "CliScanQuotaExceededError";
12
+ this.code = 'scan_quota_exceeded';
13
+ this.name = 'CliScanQuotaExceededError';
14
14
  }
15
15
  }
16
16
  exports.CliScanQuotaExceededError = CliScanQuotaExceededError;
@@ -18,20 +18,20 @@ exports.CliScanQuotaExceededError = CliScanQuotaExceededError;
18
18
  class CliScanAlreadyRunningError extends Error {
19
19
  constructor(message) {
20
20
  super(message);
21
- this.code = "scan_already_running";
22
- this.name = "CliScanAlreadyRunningError";
21
+ this.code = 'scan_already_running';
22
+ this.name = 'CliScanAlreadyRunningError';
23
23
  }
24
24
  }
25
25
  exports.CliScanAlreadyRunningError = CliScanAlreadyRunningError;
26
26
  function buildHeaders(apiKey) {
27
27
  return {
28
28
  Authorization: `Bearer ${apiKey}`,
29
- "Content-Type": "application/json",
29
+ 'Content-Type': 'application/json',
30
30
  };
31
31
  }
32
32
  async function cliScanPreflight(input) {
33
33
  const res = await fetch(`${(0, dataparade_api_base_url_1.getDataparadeApiBaseUrl)()}/api/scans/cli/preflight`, {
34
- method: "POST",
34
+ method: 'POST',
35
35
  headers: buildHeaders(input.apiKey),
36
36
  body: JSON.stringify({
37
37
  enableAi: input.enableAi,
@@ -53,10 +53,10 @@ async function cliScanPreflight(input) {
53
53
  catch {
54
54
  // ignore
55
55
  }
56
- if (res.status === 403 && code === "scan_quota_exceeded") {
56
+ if (res.status === 403 && code === 'scan_quota_exceeded') {
57
57
  throw new CliScanQuotaExceededError(message);
58
58
  }
59
- if (res.status === 409 && code === "scan_already_running") {
59
+ if (res.status === 409 && code === 'scan_already_running') {
60
60
  throw new CliScanAlreadyRunningError(message);
61
61
  }
62
62
  throw new Error(message);
@@ -64,26 +64,39 @@ async function cliScanPreflight(input) {
64
64
  return (await res.json());
65
65
  }
66
66
  async function cliScanComplete(input) {
67
- const res = await fetch(`${(0, dataparade_api_base_url_1.getDataparadeApiBaseUrl)()}/api/scans/cli/${encodeURIComponent(input.jobId)}/complete`, {
68
- method: "POST",
69
- headers: buildHeaders(input.apiKey),
70
- body: JSON.stringify({
71
- status: input.status,
72
- aiTokensUsed: input.aiTokensUsed,
73
- failureCode: input.failureCode,
74
- failureMessage: input.failureMessage,
75
- }),
76
- });
77
- if (!res.ok) {
78
- const fallback = `Scan complete report failed (${res.status})`;
79
- let message = fallback;
80
- try {
81
- const body = await res.json();
82
- message = (0, read_cli_api_error_message_1.readCliApiErrorMessage)(body, fallback).message;
83
- }
84
- catch {
85
- // ignore
67
+ const controller = typeof input.timeoutMs === 'number' && input.timeoutMs > 0
68
+ ? new AbortController()
69
+ : undefined;
70
+ const timer = controller
71
+ ? setTimeout(() => controller.abort(), input.timeoutMs)
72
+ : undefined;
73
+ try {
74
+ const res = await fetch(`${(0, dataparade_api_base_url_1.getDataparadeApiBaseUrl)()}/api/scans/cli/${encodeURIComponent(input.jobId)}/complete`, {
75
+ method: 'POST',
76
+ headers: buildHeaders(input.apiKey),
77
+ signal: controller?.signal,
78
+ body: JSON.stringify({
79
+ status: input.status,
80
+ aiTokensUsed: input.aiTokensUsed,
81
+ failureCode: input.failureCode,
82
+ failureMessage: input.failureMessage,
83
+ }),
84
+ });
85
+ if (!res.ok) {
86
+ const fallback = `Scan complete report failed (${res.status})`;
87
+ let message = fallback;
88
+ try {
89
+ const body = await res.json();
90
+ message = (0, read_cli_api_error_message_1.readCliApiErrorMessage)(body, fallback).message;
91
+ }
92
+ catch {
93
+ // ignore
94
+ }
95
+ throw new Error(message);
86
96
  }
87
- throw new Error(message);
97
+ }
98
+ finally {
99
+ if (timer)
100
+ clearTimeout(timer);
88
101
  }
89
102
  }