@dataparade/cli 0.0.19 → 0.0.21

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 (36) hide show
  1. package/README.md +12 -10
  2. package/dist/package.json +2 -1
  3. package/dist/src/ai-enrichment/providers/platform-proxy-provider.d.ts +4 -1
  4. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +44 -18
  5. package/dist/src/cli.js +100 -52
  6. package/dist/src/config/scan-env.d.ts +5 -0
  7. package/dist/src/config/scan-env.js +12 -1
  8. package/dist/src/core/pipeline/scan-pipeline.d.ts +2 -1
  9. package/dist/src/core/pipeline/scan-pipeline.js +7 -4
  10. package/dist/src/platform-api/fetch-failure.d.ts +11 -0
  11. package/dist/src/platform-api/fetch-failure.js +85 -0
  12. package/dist/src/ui/brand.d.ts +28 -0
  13. package/dist/src/ui/brand.js +72 -0
  14. package/dist/src/ui/scan-progress-renderer.d.ts +69 -0
  15. package/dist/src/ui/scan-progress-renderer.js +386 -0
  16. package/dist/src/ui/teaching-lines.d.ts +9 -0
  17. package/dist/src/ui/teaching-lines.js +144 -0
  18. package/dist/src/ui/types.d.ts +33 -0
  19. package/dist/src/ui/types.js +2 -0
  20. package/dist/src/upload/run-upload.d.ts +1 -1
  21. package/dist/src/upload/run-upload.js +21 -16
  22. package/dist/src/upload/types.d.ts +4 -0
  23. package/dist/tests/cli/cli.spec.js +77 -40
  24. package/dist/tests/unit/ai-enrichment/platform-proxy-provider.spec.js +118 -47
  25. package/dist/tests/unit/cli/scan-quota-flow.spec.js +9 -0
  26. package/dist/tests/unit/config/scan-env-debug.spec.js +17 -8
  27. package/dist/tests/unit/platform-api/fetch-failure.spec.d.ts +1 -0
  28. package/dist/tests/unit/platform-api/fetch-failure.spec.js +16 -0
  29. package/dist/tests/unit/ui/brand.spec.d.ts +1 -0
  30. package/dist/tests/unit/ui/brand.spec.js +52 -0
  31. package/dist/tests/unit/ui/scan-progress-renderer.spec.d.ts +1 -0
  32. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +275 -0
  33. package/dist/tests/unit/ui/teaching-lines.spec.d.ts +1 -0
  34. package/dist/tests/unit/ui/teaching-lines.spec.js +62 -0
  35. package/dist/tests/unit/upload/run-upload.spec.js +29 -27
  36. package/package.json +2 -1
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTransientFetchError = isTransientFetchError;
4
+ exports.fetchFailureDetail = fetchFailureDetail;
5
+ exports.describeRequestTarget = describeRequestTarget;
6
+ exports.toApiReachabilityError = toApiReachabilityError;
7
+ exports.describeThrownError = describeThrownError;
8
+ const TRANSIENT_CAUSE_CODES = new Set([
9
+ 'ECONNRESET',
10
+ 'ECONNREFUSED',
11
+ 'EPIPE',
12
+ 'ETIMEDOUT',
13
+ 'EAI_AGAIN',
14
+ 'ENOTFOUND',
15
+ 'EHOSTUNREACH',
16
+ 'ENETUNREACH',
17
+ 'UND_ERR_SOCKET',
18
+ 'UND_ERR_CONNECT_TIMEOUT',
19
+ 'UND_ERR_HEADERS_TIMEOUT',
20
+ 'UND_ERR_BODY_TIMEOUT',
21
+ ]);
22
+ function readCause(err) {
23
+ if (!(err instanceof Error))
24
+ return undefined;
25
+ const cause = err.cause;
26
+ if (!cause || typeof cause !== 'object') {
27
+ return undefined;
28
+ }
29
+ const record = cause;
30
+ return {
31
+ code: typeof record.code === 'string' ? record.code : undefined,
32
+ message: typeof record.message === 'string' ? record.message : undefined,
33
+ };
34
+ }
35
+ /** Socket-level fetch failures (no HTTP response), including Node's "fetch failed". */
36
+ function isTransientFetchError(err) {
37
+ if (!(err instanceof Error))
38
+ return false;
39
+ const message = err.message.toLowerCase();
40
+ if (message === 'fetch failed' || message.includes('network'))
41
+ return true;
42
+ const code = readCause(err)?.code;
43
+ return Boolean(code && TRANSIENT_CAUSE_CODES.has(code));
44
+ }
45
+ /** Code plus cause text, without repeating the generic "fetch failed" wrapper. */
46
+ function fetchFailureDetail(err) {
47
+ if (!(err instanceof Error))
48
+ return String(err);
49
+ const cause = readCause(err);
50
+ const parts = [cause?.code, cause?.message].filter((part) => Boolean(part && part !== err.message));
51
+ if (parts.length === 0)
52
+ return err.message;
53
+ return parts.join(': ');
54
+ }
55
+ function describeRequestTarget(url, method) {
56
+ const verb = method.toUpperCase();
57
+ try {
58
+ const parsed = new URL(url);
59
+ return `${verb} ${parsed.origin}${parsed.pathname}`;
60
+ }
61
+ catch {
62
+ return `${verb} ${url}`;
63
+ }
64
+ }
65
+ function toApiReachabilityError(err, url, method, attempts) {
66
+ const where = describeRequestTarget(url, method);
67
+ const detail = fetchFailureDetail(err);
68
+ const tries = attempts > 1 ? ` Tried ${attempts} times.` : '';
69
+ return new Error(`Could not reach the DataParade API (${where}): ${detail}.${tries} Run the scan again.`);
70
+ }
71
+ /**
72
+ * Scan-command message. Unwraps a bare "fetch failed" when a caller did not
73
+ * already attach the request target.
74
+ */
75
+ function describeThrownError(err) {
76
+ if (!(err instanceof Error))
77
+ return 'Unknown error during scan.';
78
+ if (err.message !== 'fetch failed')
79
+ return err.message;
80
+ const detail = fetchFailureDetail(err);
81
+ if (detail === err.message) {
82
+ return 'Could not reach the DataParade API: fetch failed. Run the scan again.';
83
+ }
84
+ return `Could not reach the DataParade API: ${detail}. Run the scan again.`;
85
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Compact terminal brand mark. PNG logos don't render reliably in most
3
+ * terminals, so we ship a small ASCII wordmark for TTY sessions.
4
+ *
5
+ * Upright mixed-case "DataParade". Letter gaps tuned so the second "a"
6
+ * (after "t" in Data) is not more open than the rest.
7
+ */
8
+ export declare const DATAPARADE_ASCII_LOGO: string;
9
+ export declare const DATAPARADE_TAGLINE = "Map privacy data flows from your code";
10
+ /** Below this width the figlet wraps, so we fall back to a one-line header. */
11
+ export declare const BRAND_LOGO_MIN_COLUMNS = 64;
12
+ export interface BrandHeaderOptions {
13
+ /** CLI version shown under the logo. */
14
+ version?: string;
15
+ /** When false, never emit ANSI escape codes. */
16
+ color: boolean;
17
+ /** Terminal color depth in bits (1, 4, 8, 24). */
18
+ colorDepth?: number;
19
+ /** Terminal width; undefined means "assume wide enough". */
20
+ columns?: number;
21
+ /** When false (CI / non-TTY), print only the one-line header. */
22
+ showLogo: boolean;
23
+ }
24
+ /**
25
+ * Brand header lines: teal-gradient figlet + version/tagline on wide TTYs,
26
+ * a single `DataParade vX · tagline` line otherwise.
27
+ */
28
+ export declare function renderBrandHeader(options: BrandHeaderOptions): string[];
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BRAND_LOGO_MIN_COLUMNS = exports.DATAPARADE_TAGLINE = exports.DATAPARADE_ASCII_LOGO = void 0;
4
+ exports.renderBrandHeader = renderBrandHeader;
5
+ /**
6
+ * Compact terminal brand mark. PNG logos don't render reliably in most
7
+ * terminals, so we ship a small ASCII wordmark for TTY sessions.
8
+ *
9
+ * Upright mixed-case "DataParade". Letter gaps tuned so the second "a"
10
+ * (after "t" in Data) is not more open than the rest.
11
+ */
12
+ exports.DATAPARADE_ASCII_LOGO = [
13
+ ' ____ _ ____ _',
14
+ '| _ \\ __ _ | |_ __ _ | _ \\ __ _ _ __ __ _ __| | ___',
15
+ "| | | |/ _` || __|/ _` || |_) |/ _` || '__|/ _` |/ _` | / _ \\",
16
+ '| |_| ||(_| || |_ |(_| || __/ |(_| || | |(_| ||(_| || __/',
17
+ '|____/ \\__,_| \\__|\\__,_||_| \\__,_||_| \\__,_|\\__,_| \\___|',
18
+ ].join('\n');
19
+ exports.DATAPARADE_TAGLINE = 'Map privacy data flows from your code';
20
+ /** Below this width the figlet wraps, so we fall back to a one-line header. */
21
+ exports.BRAND_LOGO_MIN_COLUMNS = 64;
22
+ // Top → bottom gradient, ending on --color-brand (#0c7377). The light end keeps
23
+ // the logo readable on dark terminals; the brand end on light ones.
24
+ const GRADIENT_FROM = [0x3f, 0xb1, 0xb5];
25
+ const GRADIENT_TO = [0x0c, 0x73, 0x77];
26
+ // xterm-256 approximations of the same ramp.
27
+ const GRADIENT_256 = [73, 73, 37, 30, 30];
28
+ const BRAND_256 = 30;
29
+ const ESC = String.fromCharCode(27);
30
+ const RESET = `${ESC}[0m`;
31
+ const BOLD = `${ESC}[1m`;
32
+ const DIM = `${ESC}[2m`;
33
+ function lerp(from, to, t) {
34
+ return [0, 1, 2].map((i) => Math.round(from[i] + (to[i] - from[i]) * t));
35
+ }
36
+ function foreground(colorDepth, rgb, ansi256) {
37
+ if (colorDepth >= 24)
38
+ return `${ESC}[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
39
+ if (colorDepth >= 8)
40
+ return `${ESC}[38;5;${ansi256}m`;
41
+ return `${ESC}[36m`;
42
+ }
43
+ /**
44
+ * Brand header lines: teal-gradient figlet + version/tagline on wide TTYs,
45
+ * a single `DataParade vX · tagline` line otherwise.
46
+ */
47
+ function renderBrandHeader(options) {
48
+ const { color, version } = options;
49
+ const depth = options.colorDepth ?? 4;
50
+ const brand = color ? foreground(depth, GRADIENT_TO, BRAND_256) : '';
51
+ const bold = color ? BOLD : '';
52
+ const dim = color ? DIM : '';
53
+ const reset = color ? RESET : '';
54
+ const versionLabel = version ? `v${version}` : '';
55
+ const wide = options.columns === undefined || options.columns >= exports.BRAND_LOGO_MIN_COLUMNS;
56
+ if (!options.showLogo || !wide) {
57
+ const name = `${bold}${brand}DataParade${reset}`;
58
+ const ver = versionLabel ? ` ${dim}${versionLabel}${reset}` : '';
59
+ return [`${name}${ver} ${dim}· ${exports.DATAPARADE_TAGLINE}${reset}`];
60
+ }
61
+ const logoLines = exports.DATAPARADE_ASCII_LOGO.split('\n');
62
+ const last = logoLines.length - 1;
63
+ const lines = logoLines.map((line, i) => {
64
+ if (!color)
65
+ return line;
66
+ const rgb = lerp(GRADIENT_FROM, GRADIENT_TO, last > 0 ? i / last : 1);
67
+ return `${bold}${foreground(depth, rgb, GRADIENT_256[i] ?? BRAND_256)}${line}${reset}`;
68
+ });
69
+ const ver = versionLabel ? `${bold}${brand}${versionLabel}${reset} ` : '';
70
+ lines.push('', ` ${ver}${dim}${exports.DATAPARADE_TAGLINE}${reset}`);
71
+ return lines;
72
+ }
@@ -0,0 +1,69 @@
1
+ import type { ScanProgress } from '../core/types';
2
+ import type { ScanAiStepResult, ScanProgressRendererOptions, ScanRecognitionPayload } from './types';
3
+ type ClackPrompts = typeof import('@clack/prompts');
4
+ /**
5
+ * Make the preview URL stand out in the next-step block.
6
+ * Uses explicit CSI sequences so our colorEnabled flag wins even when
7
+ * process.env.NO_COLOR would make util.styleText a no-op.
8
+ */
9
+ export declare function formatPreviewLink(url: string, colorEnabled: boolean): string;
10
+ export declare function formatAiStepResult(result: ScanAiStepResult): string;
11
+ /** Output path relative to cwd when it lives below it, otherwise the ~ form. */
12
+ export declare function formatOutputPath(outputPath: string): string;
13
+ /** Prefer a short, human path in the header (home → ~). */
14
+ export declare function formatProjectLabel(projectPath: string): string;
15
+ /**
16
+ * Staged scan progress for TTY (Clack) and plain logs for non-TTY / NO_COLOR.
17
+ */
18
+ export declare class ScanProgressRenderer {
19
+ private readonly isTTY;
20
+ private readonly noColor;
21
+ private readonly writeLine;
22
+ private readonly useClack;
23
+ private readonly colorEnabled;
24
+ private readonly projectLabel?;
25
+ private readonly version?;
26
+ private readonly columns?;
27
+ private readonly colorDepth?;
28
+ private readonly clack;
29
+ private started;
30
+ private recognitionHandled;
31
+ private activeStep;
32
+ private spinner;
33
+ private readonly completedSteps;
34
+ private teachingSummaryLines;
35
+ private previewUrl;
36
+ private previewNotice;
37
+ constructor(options: ScanProgressRendererOptions, clack: ClackPrompts | null);
38
+ /** Test helper: true when Clack chrome is active. */
39
+ get usesClackChrome(): boolean;
40
+ start(): void;
41
+ onProgress(progress: ScanProgress): void;
42
+ onRecognition(payload: ScanRecognitionPayload): void;
43
+ /** Close the AI step with one plain-language result line. */
44
+ onAiResult(result: ScanAiStepResult): void;
45
+ onWroteDataflow(outputPath?: string): void;
46
+ /** Store preview URL for the "What to do next" note. Machine line stays in upload. */
47
+ onPreviewUrl(previewUrl: string, notice?: string): void;
48
+ /**
49
+ * Non-fatal scan warning. Clack renders it inside the guide rail; plain mode
50
+ * keeps the `[scan] …` stderr line scripts may grep for.
51
+ */
52
+ warn(message: string): void;
53
+ /**
54
+ * Technical meters (`--ai-verbose`, quota). Plain mode prints the raw lines;
55
+ * Clack folds them into one dimmed note so they don't break the guide rail.
56
+ */
57
+ showTechnicalDetails(title: string, lines: string[]): void;
58
+ finish(): void;
59
+ private transitionTo;
60
+ private completeActiveStep;
61
+ private runTeachingStep;
62
+ private prompts;
63
+ private writePlain;
64
+ }
65
+ export declare function createScanProgressRenderer(options?: Partial<ScanProgressRendererOptions>): Promise<ScanProgressRenderer>;
66
+ /** Exported for tests. */
67
+ export declare function stripAnsi(text: string): string;
68
+ export declare function hasAnsi(text: string): boolean;
69
+ export {};
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ScanProgressRenderer = void 0;
7
+ exports.formatPreviewLink = formatPreviewLink;
8
+ exports.formatAiStepResult = formatAiStepResult;
9
+ exports.formatOutputPath = formatOutputPath;
10
+ exports.formatProjectLabel = formatProjectLabel;
11
+ exports.createScanProgressRenderer = createScanProgressRenderer;
12
+ exports.stripAnsi = stripAnsi;
13
+ exports.hasAnsi = hasAnsi;
14
+ const node_path_1 = __importDefault(require("node:path"));
15
+ const node_util_1 = require("node:util");
16
+ const brand_1 = require("./brand");
17
+ const teaching_lines_1 = require("./teaching-lines");
18
+ async function loadClack() {
19
+ const importEsm = new Function('specifier', 'return import(specifier)');
20
+ const mod = await importEsm('@clack/prompts');
21
+ if (typeof mod.intro === 'function')
22
+ return mod;
23
+ if (mod.default && typeof mod.default.intro === 'function')
24
+ return mod.default;
25
+ return mod;
26
+ }
27
+ // ESC [ … m — built without a literal control char so eslint no-control-regex is happy.
28
+ const ANSI_PATTERN = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
29
+ const STEP_LABELS = {
30
+ scanning_files: 'Reading your project files',
31
+ analyzing: 'Getting a feel for the codebase',
32
+ detecting_frameworks: 'Looking for APIs and routes',
33
+ mapping_data_stores: 'Looking for databases',
34
+ finding_outbound: 'Checking who you call outside',
35
+ ai_enrichment: 'Filling in details with AI',
36
+ };
37
+ function envNoColor(env = process.env) {
38
+ const value = env.NO_COLOR;
39
+ return typeof value === 'string' && value.length > 0;
40
+ }
41
+ function paint(enabled, style, text) {
42
+ if (!enabled)
43
+ return text;
44
+ return (0, node_util_1.styleText)(style, text);
45
+ }
46
+ /**
47
+ * Make the preview URL stand out in the next-step block.
48
+ * Uses explicit CSI sequences so our colorEnabled flag wins even when
49
+ * process.env.NO_COLOR would make util.styleText a no-op.
50
+ */
51
+ function formatPreviewLink(url, colorEnabled) {
52
+ if (!colorEnabled) {
53
+ return url;
54
+ }
55
+ const esc = String.fromCharCode(27);
56
+ // Color only: terminals already underline links on hover.
57
+ return `${esc}[36m${url}${esc}[39m`;
58
+ }
59
+ function formatAiStepResult(result) {
60
+ const applied = result.proposalsApplied;
61
+ if (applied <= 0)
62
+ return 'Nothing new to add from AI';
63
+ return applied === 1
64
+ ? 'Filled in 1 detail from your code'
65
+ : `Filled in ${applied} details from your code`;
66
+ }
67
+ /** Output path relative to cwd when it lives below it, otherwise the ~ form. */
68
+ function formatOutputPath(outputPath) {
69
+ const relative = node_path_1.default.relative(process.cwd(), outputPath);
70
+ if (relative && !relative.startsWith('..') && !node_path_1.default.isAbsolute(relative)) {
71
+ return `./${relative}`;
72
+ }
73
+ return formatProjectLabel(outputPath);
74
+ }
75
+ /** Prefer a short, human path in the header (home → ~). */
76
+ function formatProjectLabel(projectPath) {
77
+ const home = process.env.HOME?.trim();
78
+ if (home && projectPath.startsWith(`${home}/`)) {
79
+ return `~${projectPath.slice(home.length)}`;
80
+ }
81
+ return projectPath;
82
+ }
83
+ /**
84
+ * Staged scan progress for TTY (Clack) and plain logs for non-TTY / NO_COLOR.
85
+ */
86
+ class ScanProgressRenderer {
87
+ constructor(options, clack) {
88
+ this.started = false;
89
+ this.recognitionHandled = false;
90
+ this.activeStep = null;
91
+ this.spinner = null;
92
+ this.completedSteps = new Set();
93
+ this.teachingSummaryLines = [];
94
+ this.clack = clack;
95
+ this.isTTY = options.isTTY;
96
+ // Prefer explicit option over env (so tests can force color on/off).
97
+ this.noColor =
98
+ options.noColor !== undefined ? options.noColor : envNoColor();
99
+ this.projectLabel = options.projectLabel
100
+ ? formatProjectLabel(options.projectLabel)
101
+ : undefined;
102
+ this.version = options.version;
103
+ this.columns = options.columns;
104
+ this.colorDepth = options.colorDepth;
105
+ this.writeLine =
106
+ options.writeLine ??
107
+ ((line) => {
108
+ console.log(line);
109
+ });
110
+ // Clack for interactive TTY without NO_COLOR. Plain logs otherwise.
111
+ this.useClack = this.isTTY && !this.noColor;
112
+ this.colorEnabled = this.useClack;
113
+ }
114
+ /** Test helper: true when Clack chrome is active. */
115
+ get usesClackChrome() {
116
+ return this.useClack;
117
+ }
118
+ start() {
119
+ if (this.started)
120
+ return;
121
+ this.started = true;
122
+ const where = this.projectLabel
123
+ ? `Let's scan ${this.projectLabel}`
124
+ : "Let's scan your project";
125
+ // Figlet only on a real terminal; CI logs get a single header line.
126
+ const header = (0, brand_1.renderBrandHeader)({
127
+ version: this.version,
128
+ color: this.colorEnabled,
129
+ colorDepth: this.colorDepth,
130
+ columns: this.columns,
131
+ showLogo: this.isTTY,
132
+ });
133
+ if (this.useClack) {
134
+ this.writeLine('');
135
+ for (const line of header)
136
+ this.writeLine(line);
137
+ this.writeLine('');
138
+ this.prompts().intro(where);
139
+ }
140
+ else {
141
+ for (const line of header)
142
+ this.writePlain(line);
143
+ this.writePlain('────────────────');
144
+ this.writePlain(where);
145
+ }
146
+ }
147
+ onProgress(progress) {
148
+ this.start();
149
+ switch (progress.phase) {
150
+ case 'ingest':
151
+ this.transitionTo('scanning_files');
152
+ break;
153
+ case 'analyze':
154
+ this.transitionTo('analyzing');
155
+ break;
156
+ case 'classify':
157
+ if (!this.recognitionHandled) {
158
+ this.transitionTo('analyzing');
159
+ }
160
+ break;
161
+ case 'ai_enrichment':
162
+ this.transitionTo('ai_enrichment');
163
+ break;
164
+ case 'data_flow':
165
+ case 'output':
166
+ case 'idle':
167
+ default:
168
+ break;
169
+ }
170
+ }
171
+ onRecognition(payload) {
172
+ if (this.recognitionHandled)
173
+ return;
174
+ this.recognitionHandled = true;
175
+ this.start();
176
+ const groups = (0, teaching_lines_1.buildTeachingLineGroups)(payload.findings, payload.components);
177
+ this.teachingSummaryLines = (0, teaching_lines_1.flattenTeachingLines)(groups);
178
+ this.completeActiveStep();
179
+ this.runTeachingStep('detecting_frameworks', groups.routes.map((line) => line));
180
+ this.runTeachingStep('mapping_data_stores', groups.stores.map((line) => line));
181
+ this.runTeachingStep('finding_outbound', groups.outbound.map((line) => line));
182
+ if (this.teachingSummaryLines.length > 0) {
183
+ const body = this.teachingSummaryLines
184
+ .map((line) => `• ${line}`)
185
+ .join('\n');
186
+ if (this.useClack) {
187
+ this.prompts().note(body, "Here's what stood out");
188
+ }
189
+ else {
190
+ this.writePlain("Here's what stood out");
191
+ for (const line of this.teachingSummaryLines) {
192
+ this.writePlain(` • ${line}`);
193
+ }
194
+ }
195
+ }
196
+ }
197
+ /** Close the AI step with one plain-language result line. */
198
+ onAiResult(result) {
199
+ if (this.activeStep !== 'ai_enrichment')
200
+ return;
201
+ this.completeActiveStep();
202
+ const line = formatAiStepResult(result);
203
+ if (this.useClack) {
204
+ this.prompts().log.message(line);
205
+ }
206
+ else {
207
+ this.writePlain(` · ${line}`);
208
+ }
209
+ }
210
+ onWroteDataflow(outputPath) {
211
+ this.start();
212
+ this.completeActiveStep();
213
+ const label = 'Saved your data-flow map';
214
+ if (this.useClack) {
215
+ // The `[scan] dataflow.json written to` machine line is skipped in TTY,
216
+ // so the path lives here.
217
+ const where = outputPath
218
+ ? `\n${paint(this.colorEnabled, 'dim', formatOutputPath(outputPath))}`
219
+ : '';
220
+ this.prompts().log.success(`${label}${where}`);
221
+ }
222
+ else {
223
+ this.writePlain(`✓ ${label}`);
224
+ }
225
+ }
226
+ /** Store preview URL for the "What to do next" note. Machine line stays in upload. */
227
+ onPreviewUrl(previewUrl, notice) {
228
+ this.previewUrl = previewUrl;
229
+ this.previewNotice = notice;
230
+ }
231
+ /**
232
+ * Non-fatal scan warning. Clack renders it inside the guide rail; plain mode
233
+ * keeps the `[scan] …` stderr line scripts may grep for.
234
+ */
235
+ warn(message) {
236
+ if (this.useClack) {
237
+ this.prompts().log.warn(message);
238
+ }
239
+ else {
240
+ console.warn(`[scan] ${message}`);
241
+ }
242
+ }
243
+ /**
244
+ * Technical meters (`--ai-verbose`, quota). Plain mode prints the raw lines;
245
+ * Clack folds them into one dimmed note so they don't break the guide rail.
246
+ */
247
+ showTechnicalDetails(title, lines) {
248
+ if (lines.length === 0)
249
+ return;
250
+ if (this.useClack) {
251
+ const body = lines
252
+ .map((line) => line.replace(/^\[scan\] ?/, ''))
253
+ .map((line) => paint(this.colorEnabled, 'dim', line))
254
+ .join('\n');
255
+ this.prompts().note(body, title);
256
+ }
257
+ else {
258
+ for (const line of lines) {
259
+ this.writeLine(line);
260
+ }
261
+ }
262
+ }
263
+ finish() {
264
+ this.completeActiveStep();
265
+ const nextSteps = [];
266
+ if (this.previewUrl) {
267
+ nextSteps.push(`Open your diagram:\n${formatPreviewLink(this.previewUrl, this.colorEnabled)}`);
268
+ // Plain mode already got the notice from the upload's own log line.
269
+ if (this.useClack && this.previewNotice) {
270
+ nextSteps.push(this.previewNotice);
271
+ }
272
+ }
273
+ else {
274
+ nextSteps.push('Jump into DataParade to keep editing the diagram.');
275
+ }
276
+ if (this.useClack) {
277
+ // Not a note(): it hard-wraps to the terminal width, which splits long
278
+ // preview URLs and breaks click-to-open.
279
+ this.prompts().log.step('What to do next');
280
+ this.prompts().log.message(nextSteps.join('\n\n'));
281
+ this.prompts().outro('All done — nice work.');
282
+ }
283
+ else {
284
+ this.writePlain('What to do next');
285
+ for (const line of nextSteps) {
286
+ // Preserve ANSI on the link line when color is on; strip elsewhere.
287
+ if (this.colorEnabled && line.includes('http')) {
288
+ this.writeLine(` ${line}`);
289
+ }
290
+ else {
291
+ this.writePlain(` ${line}`);
292
+ }
293
+ }
294
+ this.writePlain('All done — nice work.');
295
+ }
296
+ }
297
+ transitionTo(step) {
298
+ if (this.activeStep === step || this.completedSteps.has(step)) {
299
+ return;
300
+ }
301
+ this.completeActiveStep();
302
+ this.activeStep = step;
303
+ const label = STEP_LABELS[step];
304
+ if (this.useClack) {
305
+ this.spinner = this.prompts().spinner({ withGuide: true });
306
+ this.spinner.start(label);
307
+ }
308
+ else {
309
+ this.writePlain(`… ${label}`);
310
+ }
311
+ }
312
+ completeActiveStep() {
313
+ if (!this.activeStep)
314
+ return;
315
+ const label = STEP_LABELS[this.activeStep];
316
+ if (this.useClack && this.spinner) {
317
+ this.spinner.stop(label);
318
+ this.spinner = null;
319
+ }
320
+ else if (!this.useClack) {
321
+ this.writePlain(`✓ ${label}`);
322
+ }
323
+ this.completedSteps.add(this.activeStep);
324
+ this.activeStep = null;
325
+ }
326
+ runTeachingStep(step, teachingLines) {
327
+ if (this.completedSteps.has(step))
328
+ return;
329
+ // Only show the step when there is something to teach, per AL-160.
330
+ if (teachingLines.length === 0)
331
+ return;
332
+ const label = STEP_LABELS[step];
333
+ if (this.useClack) {
334
+ const spin = this.prompts().spinner({ withGuide: true });
335
+ spin.start(label);
336
+ spin.stop(label);
337
+ for (const line of teachingLines) {
338
+ this.prompts().log.message(line);
339
+ }
340
+ }
341
+ else {
342
+ this.writePlain(`✓ ${label}`);
343
+ for (const line of teachingLines) {
344
+ this.writePlain(` · ${line}`);
345
+ }
346
+ }
347
+ this.completedSteps.add(step);
348
+ }
349
+ prompts() {
350
+ if (!this.clack) {
351
+ throw new Error('@clack/prompts is not loaded');
352
+ }
353
+ return this.clack;
354
+ }
355
+ writePlain(line) {
356
+ const text = this.noColor ? line.replace(ANSI_PATTERN, '') : line;
357
+ this.writeLine(text);
358
+ }
359
+ }
360
+ exports.ScanProgressRenderer = ScanProgressRenderer;
361
+ async function createScanProgressRenderer(options) {
362
+ const isTTY = options?.isTTY ?? Boolean(process.stdout.isTTY);
363
+ const noColor = options?.noColor !== undefined ? options.noColor : envNoColor();
364
+ const useClack = isTTY && !noColor;
365
+ const clack = useClack ? (options?.prompts ?? (await loadClack())) : null;
366
+ return new ScanProgressRenderer({
367
+ isTTY,
368
+ noColor,
369
+ writeLine: options?.writeLine,
370
+ projectLabel: options?.projectLabel,
371
+ version: options?.version,
372
+ columns: options?.columns ?? process.stdout.columns,
373
+ colorDepth: options?.colorDepth ??
374
+ (typeof process.stdout.getColorDepth === 'function'
375
+ ? process.stdout.getColorDepth()
376
+ : undefined),
377
+ }, clack);
378
+ }
379
+ /** Exported for tests. */
380
+ function stripAnsi(text) {
381
+ return text.replace(ANSI_PATTERN, '');
382
+ }
383
+ function hasAnsi(text) {
384
+ // Avoid RegExp.lastIndex surprises with the global flag.
385
+ return new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`).test(text);
386
+ }
@@ -0,0 +1,9 @@
1
+ import type { DetectedComponent, RawFinding } from '../core/types';
2
+ import type { TeachingLineGroups } from './types';
3
+ /**
4
+ * Build teaching lines from deterministic findings/components.
5
+ * Empty groups are omitted by the renderer.
6
+ */
7
+ export declare function buildTeachingLineGroups(findings: RawFinding[], components: DetectedComponent[]): TeachingLineGroups;
8
+ /** Flatten groups into display strings (without the leading bullet). */
9
+ export declare function flattenTeachingLines(groups: TeachingLineGroups): string[];