devclean-cache 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ import { formatBytes, formatCount } from "./util/format.js";
2
+ function escapeHtml(value) {
3
+ return value
4
+ .replace(/&/g, "&")
5
+ .replace(/</g, "&lt;")
6
+ .replace(/>/g, "&gt;")
7
+ .replace(/"/g, "&quot;")
8
+ .replace(/'/g, "&#39;");
9
+ }
10
+ function escapeJsonForScript(value) {
11
+ return JSON.stringify(value)
12
+ .replace(/</g, "\\u003c")
13
+ .replace(/\u2028/g, "\\u2028")
14
+ .replace(/\u2029/g, "\\u2029");
15
+ }
16
+ function platformName() {
17
+ if (process.platform === "win32")
18
+ return "Windows";
19
+ if (process.platform === "darwin")
20
+ return "macOS";
21
+ return "Linux";
22
+ }
23
+ const CSS = String.raw `:root{--bg:#0b0e14;--panel:#11151f;--line:#232a3a;--text:#c9d1d9;--dim:#8b949e;--green:#7ee787;--blue:#58a6ff;--yellow:#d29922;--red:#f85149;}
24
+ *{box-sizing:border-box}
25
+ body{margin:0;background:radial-gradient(1200px 600px at 20% -10%,#16202f 0%,#0b0e14 55%);color:var(--text);font:15px/1.55 ui-sans-serif,-apple-system,'Segoe UI',Roboto,sans-serif;padding:48px 24px 64px}
26
+ .wrap{max-width:1080px;margin:0 auto}
27
+ header{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:28px;flex-wrap:wrap}
28
+ .brand{font:600 15px ui-monospace,'Cascadia Code',Consolas,monospace;color:var(--green);letter-spacing:.2px}
29
+ .brand span{color:var(--dim);font-weight:400}
30
+ h1{font-size:44px;line-height:1.1;margin:0 0 6px;letter-spacing:-.02em;font-weight:650}
31
+ h1 em{font-style:normal;color:var(--green)}
32
+ .meta{color:var(--dim);font-size:13.5px}
33
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:14px;overflow:hidden}
34
+ .map{display:block;width:100%;height:auto}
35
+ .legend{display:flex;gap:18px;flex-wrap:wrap;padding:12px 16px;border-top:1px solid var(--line);color:var(--dim);font-size:12.5px}
36
+ .legend i{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:6px;vertical-align:middle}
37
+ table{width:100%;border-collapse:collapse;margin-top:26px;font-size:13.5px}
38
+ th{text-align:left;color:var(--dim);font-weight:500;font-size:11.5px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}
39
+ td{padding:10px;border-bottom:1px solid #1a202c;vertical-align:top}
40
+ td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
41
+ .path{color:var(--dim);font:12px ui-monospace,'Cascadia Code',Consolas,monospace;word-break:break-all}
42
+ .risk{font-size:11.5px;text-transform:uppercase;letter-spacing:.06em}
43
+ .low{color:var(--green)}.medium{color:var(--yellow)}.high{color:var(--red)}
44
+ footer{margin-top:30px;color:var(--dim);font-size:12.5px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap}
45
+ footer a{color:var(--blue);text-decoration:none}
46
+ .rect{transition:opacity .15s}
47
+ .rect:hover{opacity:.8}
48
+ @media (max-width:640px){h1{font-size:32px}}`;
49
+ const SCRIPT = String.raw `(function () {
50
+ var data = JSON.parse(document.getElementById("devclean-data").textContent);
51
+ var W = 1080, H = 520, PAD = 3;
52
+ var svg = document.getElementById("map");
53
+ svg.setAttribute("viewBox", "0 0 " + W + " " + H);
54
+ var ns = "http://www.w3.org/2000/svg";
55
+ var colors = { low: "#2ea043", medium: "#d29922", high: "#f85149" };
56
+ var items = data.items.filter(function (it) { return it.bytes > 0; }).map(function (it) {
57
+ return { name: it.name, bytes: it.bytes, files: it.files, risk: it.risk, path: it.path, v: it.bytes };
58
+ });
59
+ function bytes(n) {
60
+ if (n >= 1073741824) return (n / 1073741824).toFixed(2) + " GB";
61
+ if (n >= 1048576) return (n / 1048576).toFixed(1) + " MB";
62
+ if (n >= 1024) return (n / 1024).toFixed(1) + " KB";
63
+ return n + " B";
64
+ }
65
+ var total = items.reduce(function (s, it) { return s + it.bytes; }, 0) || 1;
66
+ var floor = total * 0.06;
67
+ items.forEach(function (it) { it.v = Math.max(it.bytes, floor); });
68
+ function worst(row, length) {
69
+ var sum = 0, max = 0, min = Infinity;
70
+ for (var i = 0; i < row.length; i++) {
71
+ var v = row[i].v;
72
+ sum += v;
73
+ if (v > max) max = v;
74
+ if (v < min) min = v;
75
+ }
76
+ if (sum <= 0) return Infinity;
77
+ var s2 = sum * sum, l2 = length * length;
78
+ return Math.max((l2 * max) / s2, s2 / (l2 * min));
79
+ }
80
+ function layout(list, x, y, w, h, out) {
81
+ var rest = list.slice();
82
+ while (rest.length) {
83
+ var length = Math.min(w, h);
84
+ var row = [rest[0]];
85
+ var j = 1;
86
+ while (j < rest.length) {
87
+ var cand = row.concat([rest[j]]);
88
+ if (worst(cand, length) <= worst(row, length)) { row = cand; j++; } else { break; }
89
+ }
90
+ var rowSum = 0, restSum = 0;
91
+ for (var a = 0; a < row.length; a++) rowSum += row[a].v;
92
+ for (var b = 0; b < rest.length; b++) restSum += rest[b].v;
93
+ var area = (rowSum / restSum) * w * h;
94
+ if (w >= h) {
95
+ var th = area / w;
96
+ var cx = x;
97
+ for (var c = 0; c < row.length; c++) {
98
+ var cw = (row[c].v / rowSum) * w;
99
+ out.push({ item: row[c], x: cx, y: y, w: cw, h: th });
100
+ cx += cw;
101
+ }
102
+ y += th; h -= th;
103
+ } else {
104
+ var tw = area / h;
105
+ var cy = y;
106
+ for (var d = 0; d < row.length; d++) {
107
+ var ch = (row[d].v / rowSum) * h;
108
+ out.push({ item: row[d], x: x, y: cy, w: tw, h: ch });
109
+ cy += ch;
110
+ }
111
+ x += tw; w -= tw;
112
+ }
113
+ rest = rest.slice(row.length);
114
+ }
115
+ }
116
+ items.sort(function (a, b) { return b.v - a.v; });
117
+ var rects = [];
118
+ layout(items, 0, 0, W, H, rects);
119
+ function svgText(x, y, size, fill, content) {
120
+ var t = document.createElementNS(ns, "text");
121
+ t.setAttribute("x", x);
122
+ t.setAttribute("y", y);
123
+ t.setAttribute("fill", fill);
124
+ t.setAttribute("font-size", String(size));
125
+ t.setAttribute("font-family", "ui-monospace, 'Cascadia Code', Consolas, monospace");
126
+ t.textContent = content;
127
+ return t;
128
+ }
129
+ function fit(text, size) {
130
+ var max = Math.max(0, Math.floor(size / 7.4));
131
+ if (max <= 1) return "";
132
+ return text.length <= max ? text : text.slice(0, max - 1) + "\u2026";
133
+ }
134
+ rects.forEach(function (r) {
135
+ if (r.w < PAD * 2 || r.h < PAD * 2) return;
136
+ var g = document.createElementNS(ns, "g");
137
+ var rect = document.createElementNS(ns, "rect");
138
+ rect.setAttribute("class", "rect");
139
+ rect.setAttribute("x", r.x + PAD / 2);
140
+ rect.setAttribute("y", r.y + PAD / 2);
141
+ rect.setAttribute("width", Math.max(0, r.w - PAD));
142
+ rect.setAttribute("height", Math.max(0, r.h - PAD));
143
+ rect.setAttribute("rx", "5");
144
+ rect.setAttribute("fill", colors[r.item.risk] || colors.low);
145
+ rect.setAttribute("fill-opacity", "0.22");
146
+ rect.setAttribute("stroke", colors[r.item.risk] || colors.low);
147
+ rect.setAttribute("stroke-opacity", "0.5");
148
+ var title = document.createElementNS(ns, "title");
149
+ title.textContent = r.item.name + " - " + r.item.path + " (" + r.item.files + " files)";
150
+ g.appendChild(rect);
151
+ g.appendChild(title);
152
+ if (r.w > 90 && r.h > 24) {
153
+ var nameLine = fit(r.item.name, Math.min(r.w - 20, 260));
154
+ if (r.h >= 44) {
155
+ g.appendChild(svgText(r.x + 11, r.y + 21, 13, "#e6edf3", nameLine));
156
+ g.appendChild(svgText(r.x + 11, r.y + 40, 12, "#9aa4b2", bytes(r.item.bytes)));
157
+ } else {
158
+ var compact = fit(r.item.name + " " + bytes(r.item.bytes), Math.min(r.w - 20, 320));
159
+ g.appendChild(svgText(r.x + 11, r.y + 17, 11.5, "#d7dee8", compact));
160
+ }
161
+ }
162
+ svg.appendChild(g);
163
+ });
164
+ })();`;
165
+ export function renderHtmlReport(items, options) {
166
+ const totalBytes = items.reduce((sum, item) => sum + item.bytes, 0);
167
+ const totalFiles = items.reduce((sum, item) => sum + item.files, 0);
168
+ const generatedAt = options.generatedAt ?? new Date();
169
+ const cleanableBytes = items.filter((item) => item.risk !== "high").reduce((sum, item) => sum + item.bytes, 0);
170
+ const highBytes = totalBytes - cleanableBytes;
171
+ const title = options.title ?? "devclean report";
172
+ const data = {
173
+ version: options.version,
174
+ generatedAt: generatedAt.toISOString(),
175
+ platform: process.platform,
176
+ totalBytes,
177
+ totalFiles,
178
+ items: items.map((item) => ({
179
+ id: item.id,
180
+ name: item.name,
181
+ path: item.path,
182
+ risk: item.risk,
183
+ bytes: item.bytes,
184
+ files: item.files,
185
+ })),
186
+ };
187
+ const rows = items
188
+ .map((item) => "<tr><td>" +
189
+ escapeHtml(item.name) +
190
+ '</td><td class="num">' +
191
+ formatBytes(item.bytes) +
192
+ '</td><td class="num">' +
193
+ formatCount(item.files) +
194
+ '</td><td class="risk ' +
195
+ item.risk +
196
+ '">' +
197
+ item.risk +
198
+ '</td><td class="path">' +
199
+ escapeHtml(item.path) +
200
+ "</td></tr>")
201
+ .join("\n");
202
+ const subtitle = formatBytes(cleanableBytes) +
203
+ " reclaimable" +
204
+ (highBytes > 0 ? " - " + formatBytes(highBytes) + " high risk" : "") +
205
+ " - " +
206
+ items.length +
207
+ (items.length === 1 ? " cache" : " caches") +
208
+ ", " +
209
+ formatCount(totalFiles) +
210
+ " files - " +
211
+ escapeHtml(platformName()) +
212
+ " - " +
213
+ generatedAt.toISOString().slice(0, 10);
214
+ return [
215
+ "<!doctype html>",
216
+ '<html lang="en"><head><meta charset="utf-8">',
217
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
218
+ "<title>" + escapeHtml(title) + "</title>",
219
+ "<style>",
220
+ CSS,
221
+ "</style>",
222
+ '</head><body><div class="wrap">',
223
+ "<header>",
224
+ '<div class="brand">devclean <span>report</span></div>',
225
+ '<div class="meta">' + subtitle + "</div>",
226
+ "</header>",
227
+ "<h1>You can reclaim <em>" + formatBytes(cleanableBytes) + "</em></h1>",
228
+ '<p class="meta">' +
229
+ items.length +
230
+ " caches found. High-risk items (local model weights) are never included in the total above.</p>",
231
+ '<div class="panel" style="margin-top:22px">',
232
+ '<svg id="map" class="map" role="img" aria-label="Treemap of developer caches"></svg>',
233
+ '<div class="legend">',
234
+ '<span><i style="background:#2ea043"></i>low risk</span>',
235
+ '<span><i style="background:#d29922"></i>medium risk</span>',
236
+ '<span><i style="background:#f85149"></i>high risk</span>',
237
+ '<span style="margin-left:auto">area = size on disk</span>',
238
+ "</div></div>",
239
+ '<table><thead><tr><th>Cache</th><th class="num">Size</th><th class="num">Files</th><th>Risk</th><th>Path</th></tr></thead><tbody>',
240
+ rows,
241
+ "</tbody></table>",
242
+ "<footer>",
243
+ "<span>Generated by devclean " +
244
+ escapeHtml(options.version) +
245
+ " on " +
246
+ generatedAt.toISOString().replace("T", " ").slice(0, 19) +
247
+ " UTC</span>",
248
+ '<span><a href="https://github.com/shisilang684/devclean">github.com/shisilang684/devclean</a></span>',
249
+ "</footer></div>",
250
+ '<script id="devclean-data" type="application/json">' + escapeJsonForScript(data) + "</script>",
251
+ "<script>",
252
+ SCRIPT,
253
+ "</script>",
254
+ "</body></html>",
255
+ ].join("\n");
256
+ }
@@ -0,0 +1,36 @@
1
+ import type { ScanItem } from "./scan.js";
2
+ import type { Risk } from "./adapters.js";
3
+ export interface Palette {
4
+ bold: (s: string) => string;
5
+ dim: (s: string) => string;
6
+ cyan: (s: string) => string;
7
+ green: (s: string) => string;
8
+ yellow: (s: string) => string;
9
+ red: (s: string) => string;
10
+ magenta: (s: string) => string;
11
+ }
12
+ export declare function createPalette(enabled: boolean): Palette;
13
+ export declare function riskColor(p: Palette, risk: Risk): (s: string) => string;
14
+ export interface TableOptions {
15
+ palette?: Palette;
16
+ showPath?: boolean;
17
+ title?: string;
18
+ }
19
+ /** Render cache rows as an aligned table. */
20
+ export declare function renderTable(items: ScanItem[], options?: TableOptions): string;
21
+ export declare function renderSummary(items: Array<{
22
+ bytes: number;
23
+ files: number;
24
+ }>, palette: Palette): string;
25
+ export interface JsonReport {
26
+ version: string;
27
+ generatedAt: string;
28
+ platform: string;
29
+ totalBytes: number;
30
+ totalFiles: number;
31
+ items: Array<Omit<ScanItem, "errors"> & {
32
+ errors: number;
33
+ }>;
34
+ }
35
+ export declare function renderJson(items: ScanItem[], version: string): string;
36
+ export declare function removeFooter(items: ScanItem[]): string;
package/dist/report.js ADDED
@@ -0,0 +1,109 @@
1
+ import { formatBytes, formatCount, percent, truncateMiddle, truncatePath, bar, plural } from "./util/format.js";
2
+ const IDENTITY = (s) => s;
3
+ export function createPalette(enabled) {
4
+ const wrap = (code) => (s) => (enabled ? `\u001b[${code}m${s}\u001b[0m` : s);
5
+ return {
6
+ bold: wrap(1),
7
+ dim: wrap(2),
8
+ cyan: wrap(36),
9
+ green: wrap(32),
10
+ yellow: wrap(33),
11
+ red: wrap(31),
12
+ magenta: wrap(35),
13
+ };
14
+ }
15
+ export function riskColor(p, risk) {
16
+ if (risk === "high")
17
+ return p.red;
18
+ if (risk === "medium")
19
+ return p.yellow;
20
+ return p.green;
21
+ }
22
+ function padRight(text, width) {
23
+ return text.length >= width ? text : text + " ".repeat(width - text.length);
24
+ }
25
+ function padLeft(text, width) {
26
+ return text.length >= width ? text : " ".repeat(width - text.length) + text;
27
+ }
28
+ function termWidth() {
29
+ const width = process.stdout.columns || 0;
30
+ return width > 40 ? width : 100;
31
+ }
32
+ /** Render cache rows as an aligned table. */
33
+ export function renderTable(items, options = {}) {
34
+ const p = options.palette ?? createPalette(false);
35
+ const showPath = options.showPath !== false;
36
+ const total = items.reduce((sum, item) => sum + item.bytes, 0);
37
+ const nameWidth = Math.min(24, Math.max(10, ...items.map((item) => item.name.length)));
38
+ const sizeWidth = 9;
39
+ const shareWidth = 20;
40
+ const filesWidth = 6;
41
+ const riskWidth = 6;
42
+ const fixedWidth = nameWidth + sizeWidth + shareWidth + filesWidth + riskWidth + 10;
43
+ const pathWidth = showPath ? Math.max(18, termWidth() - fixedWidth) : 0;
44
+ const lines = [];
45
+ const header = [
46
+ padRight("CACHE", nameWidth),
47
+ padLeft("SIZE", sizeWidth),
48
+ padRight("SHARE", shareWidth),
49
+ padLeft("FILES", filesWidth),
50
+ padRight("RISK", riskWidth),
51
+ showPath ? "PATH" : "",
52
+ ]
53
+ .filter(Boolean)
54
+ .join(" ");
55
+ lines.push(p.dim(header));
56
+ for (const item of items) {
57
+ const share = percent(item.bytes, total);
58
+ const shareText = `${bar(share, 14)} ${share.toFixed(0).padStart(3)}%`;
59
+ const cells = [
60
+ padRight(truncateMiddle(item.name, nameWidth), nameWidth),
61
+ p.bold(padLeft(formatBytes(item.bytes), sizeWidth)),
62
+ p.cyan(shareText),
63
+ padLeft(formatCount(item.files), filesWidth),
64
+ padRight(item.risk, riskWidth),
65
+ showPath ? p.dim(truncatePath(item.path, pathWidth)) : "",
66
+ ].filter(Boolean);
67
+ // Color the risk cell only.
68
+ cells[4] = riskColor(p, item.risk)(padRight(item.risk, riskWidth));
69
+ lines.push(cells.join(" "));
70
+ }
71
+ return lines.join("\n");
72
+ }
73
+ export function renderSummary(items, palette) {
74
+ const total = items.reduce((acc, item) => ({ bytes: acc.bytes + item.bytes, files: acc.files + item.files }), {
75
+ bytes: 0,
76
+ files: 0,
77
+ });
78
+ return (palette.bold(`Total: ${formatBytes(total.bytes)}`) +
79
+ palette.dim(` across ${plural(items.length, "location")}, ${formatCount(total.files)} files`));
80
+ }
81
+ export function renderJson(items, version) {
82
+ const totalBytes = items.reduce((sum, item) => sum + item.bytes, 0);
83
+ const totalFiles = items.reduce((sum, item) => sum + item.files, 0);
84
+ const report = {
85
+ version,
86
+ generatedAt: new Date().toISOString(),
87
+ platform: process.platform,
88
+ totalBytes,
89
+ totalFiles,
90
+ items: items.map((item) => ({
91
+ id: item.id,
92
+ name: item.name,
93
+ path: item.path,
94
+ risk: item.risk,
95
+ note: item.note,
96
+ bytes: item.bytes,
97
+ files: item.files,
98
+ errors: item.errors,
99
+ })),
100
+ };
101
+ return JSON.stringify(report, null, 2);
102
+ }
103
+ export function removeFooter(items) {
104
+ const cleanable = items.filter((item) => item.risk !== "high");
105
+ const lowBytes = cleanable.reduce((sum, item) => sum + item.bytes, 0);
106
+ if (lowBytes === 0)
107
+ return "";
108
+ return "Reclaim " + formatBytes(lowBytes) + " with devclean clean";
109
+ }
package/dist/scan.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type CacheCandidate, type Env, type Risk } from "./adapters.js";
2
+ import { type DevcleanConfig } from "./config.js";
3
+ export interface ScanItem {
4
+ id: string;
5
+ name: string;
6
+ path: string;
7
+ risk: Risk;
8
+ note: string;
9
+ bytes: number;
10
+ files: number;
11
+ errors: number;
12
+ }
13
+ export interface ScanOptions {
14
+ env?: Env;
15
+ only?: string[];
16
+ config?: DevcleanConfig;
17
+ onScanStart?: (candidate: CacheCandidate) => void;
18
+ onScanDone?: (item: ScanItem) => void;
19
+ }
20
+ /** Resolve adapters to cache paths that actually exist on this machine. */
21
+ export declare function discover(options?: {
22
+ env?: Env;
23
+ only?: string[];
24
+ config?: DevcleanConfig;
25
+ }): Promise<CacheCandidate[]>;
26
+ export declare function scanCandidates(candidates: CacheCandidate[], options?: ScanOptions): Promise<ScanItem[]>;
27
+ export declare function scanAll(options?: ScanOptions): Promise<{
28
+ items: ScanItem[];
29
+ candidates: CacheCandidate[];
30
+ }>;
31
+ export declare function totalOf(items: Array<{
32
+ bytes: number;
33
+ files: number;
34
+ }>): {
35
+ bytes: number;
36
+ files: number;
37
+ };
package/dist/scan.js ADDED
@@ -0,0 +1,66 @@
1
+ import path from "node:path";
2
+ import { ADAPTERS, detectEnv } from "./adapters.js";
3
+ import { dirSize, isDirectory } from "./util/fs.js";
4
+ import { loadConfig } from "./config.js";
5
+ /** Resolve adapters to cache paths that actually exist on this machine. */
6
+ export async function discover(options = {}) {
7
+ const env = options.env ?? detectEnv();
8
+ const config = options.config ?? (await loadConfig(env));
9
+ const only = options.only && options.only.length > 0 ? new Set(options.only) : null;
10
+ const ignoreIds = new Set(config.ignore.filter((entry) => !path.isAbsolute(entry)));
11
+ const ignorePaths = new Set(config.ignore
12
+ .filter((entry) => path.isAbsolute(entry))
13
+ .map((entry) => (env.platform === "win32" ? path.resolve(entry).toLowerCase() : path.resolve(entry))));
14
+ const seen = new Set();
15
+ const candidates = [];
16
+ const adapters = ADAPTERS.filter((adapter) => (!only || only.has(adapter.id)) && !ignoreIds.has(adapter.id));
17
+ for (const adapter of adapters) {
18
+ for (const raw of adapter.paths(env)) {
19
+ const resolved = path.resolve(raw);
20
+ const key = env.platform === "win32" ? resolved.toLowerCase() : resolved;
21
+ if (seen.has(key) || ignorePaths.has(key))
22
+ continue;
23
+ seen.add(key);
24
+ if (!(await isDirectory(resolved)))
25
+ continue;
26
+ candidates.push({
27
+ id: adapter.id,
28
+ name: adapter.name,
29
+ path: resolved,
30
+ risk: adapter.risk,
31
+ note: adapter.note,
32
+ });
33
+ }
34
+ }
35
+ const extra = config.extra.filter((item) => !only || only.has(item.id));
36
+ for (const item of extra) {
37
+ const key = env.platform === "win32" ? item.path.toLowerCase() : item.path;
38
+ if (seen.has(key) || ignorePaths.has(key))
39
+ continue;
40
+ seen.add(key);
41
+ if (!(await isDirectory(item.path)))
42
+ continue;
43
+ candidates.push(item);
44
+ }
45
+ return candidates;
46
+ }
47
+ export async function scanCandidates(candidates, options = {}) {
48
+ const items = [];
49
+ for (const candidate of candidates) {
50
+ options.onScanStart?.(candidate);
51
+ const size = await dirSize(candidate.path);
52
+ const item = { ...candidate, ...size };
53
+ items.push(item);
54
+ options.onScanDone?.(item);
55
+ }
56
+ items.sort((a, b) => b.bytes - a.bytes);
57
+ return items;
58
+ }
59
+ export async function scanAll(options = {}) {
60
+ const candidates = await discover({ env: options.env, only: options.only, config: options.config });
61
+ const items = await scanCandidates(candidates, options);
62
+ return { items, candidates };
63
+ }
64
+ export function totalOf(items) {
65
+ return items.reduce((acc, item) => ({ bytes: acc.bytes + item.bytes, files: acc.files + item.files }), { bytes: 0, files: 0 });
66
+ }
package/dist/tui.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { ScanItem } from "./scan.js";
2
+ import type { Palette } from "./report.js";
3
+ export interface TuiState {
4
+ items: ScanItem[];
5
+ selected: boolean[];
6
+ cursor: number;
7
+ }
8
+ /** Low and medium risk caches start selected; model weights are opt-in. */
9
+ export declare function createTuiState(items: ScanItem[]): TuiState;
10
+ export declare function toggleAt(state: TuiState, index?: number): TuiState;
11
+ export declare function setAll(state: TuiState, value: boolean): TuiState;
12
+ export declare function moveCursor(state: TuiState, delta: number): TuiState;
13
+ export declare function selectedItems(state: TuiState): ScanItem[];
14
+ export declare function selectionTotals(state: TuiState): {
15
+ bytes: number;
16
+ files: number;
17
+ };
18
+ export declare function renderTui(state: TuiState, palette: Palette, width?: number): string[];
19
+ export interface SelectOptions {
20
+ palette: Palette;
21
+ input?: NodeJS.ReadStream;
22
+ output?: NodeJS.WriteStream;
23
+ }
24
+ /** Interactive checkbox list. Returns null when the user quits. */
25
+ export declare function selectItems(items: ScanItem[], options: SelectOptions): Promise<ScanItem[] | null>;
package/dist/tui.js ADDED
@@ -0,0 +1,113 @@
1
+ import readline from "node:readline";
2
+ import process from "node:process";
3
+ import { formatBytes, formatCount, truncatePath } from "./util/format.js";
4
+ /** Low and medium risk caches start selected; model weights are opt-in. */
5
+ export function createTuiState(items) {
6
+ return {
7
+ items,
8
+ selected: items.map((item) => item.risk !== "high"),
9
+ cursor: 0,
10
+ };
11
+ }
12
+ export function toggleAt(state, index = state.cursor) {
13
+ if (index < 0 || index >= state.items.length)
14
+ return state;
15
+ const selected = state.selected.slice();
16
+ selected[index] = !selected[index];
17
+ return { ...state, selected };
18
+ }
19
+ export function setAll(state, value) {
20
+ return { ...state, selected: state.items.map(() => value) };
21
+ }
22
+ export function moveCursor(state, delta) {
23
+ const next = Math.min(state.items.length - 1, Math.max(0, state.cursor + delta));
24
+ return { ...state, cursor: next };
25
+ }
26
+ export function selectedItems(state) {
27
+ return state.items.filter((_, index) => state.selected[index]);
28
+ }
29
+ export function selectionTotals(state) {
30
+ return selectedItems(state).reduce((acc, item) => ({ bytes: acc.bytes + item.bytes, files: acc.files + item.files }), { bytes: 0, files: 0 });
31
+ }
32
+ export function renderTui(state, palette, width = 100) {
33
+ const p = palette;
34
+ const lines = [];
35
+ lines.push(p.bold("devclean") + p.dim(" - select what to delete"));
36
+ lines.push("");
37
+ const { bytes, files } = selectionTotals(state);
38
+ lines.push(p.dim(" space toggle a all n none arrows move enter delete q quit"));
39
+ lines.push("");
40
+ const nameWidth = Math.min(22, Math.max(10, ...state.items.map((item) => item.name.length)));
41
+ const riskWidth = 6;
42
+ const sizeWidth = 9;
43
+ const pathWidth = Math.max(16, width - nameWidth - sizeWidth - riskWidth - 14);
44
+ state.items.forEach((item, index) => {
45
+ const cursor = index === state.cursor;
46
+ const box = state.selected[index] ? p.green("[x]") : p.dim("[ ]");
47
+ const name = (cursor ? p.bold(">") : " ") + " " + box + " " + item.name.padEnd(nameWidth);
48
+ const size = formatBytes(item.bytes).padStart(sizeWidth);
49
+ const risk = item.risk.padEnd(riskWidth);
50
+ const meta = p.dim(truncatePath(item.path, pathWidth));
51
+ lines.push(name + " " + size + " " + risk + " " + meta);
52
+ });
53
+ lines.push("");
54
+ lines.push(p.bold("Selected: " + formatBytes(bytes)) +
55
+ p.dim(" (" + formatCount(files) + " files, " + selectedItems(state).length + " of " + state.items.length + ")"));
56
+ return lines;
57
+ }
58
+ /** Interactive checkbox list. Returns null when the user quits. */
59
+ export function selectItems(items, options) {
60
+ const input = options.input ?? process.stdin;
61
+ const output = options.output ?? process.stdout;
62
+ const palette = options.palette;
63
+ return new Promise((resolve) => {
64
+ let state = createTuiState(items);
65
+ let lines = renderTui(state, palette, output.columns ?? 100);
66
+ const paint = (full) => {
67
+ if (full)
68
+ output.write("\u001b[?25l");
69
+ else
70
+ output.write("\u001b[" + lines.length + "A");
71
+ for (const line of lines)
72
+ output.write(line + "\u001b[K\n");
73
+ lines = renderTui(state, palette, output.columns ?? 100);
74
+ };
75
+ const done = (result) => {
76
+ input.setRawMode?.(false);
77
+ input.pause();
78
+ input.removeListener("keypress", onKey);
79
+ output.write("\u001b[?25h\n");
80
+ resolve(result);
81
+ };
82
+ const onKey = (str, key) => {
83
+ if (key?.ctrl && key.name === "c")
84
+ return done(null);
85
+ if (key?.name === "q" || key?.name === "escape")
86
+ return done(null);
87
+ if (key?.name === "return" || key?.name === "enter")
88
+ return done(selectedItems(state));
89
+ if (key?.name === "space")
90
+ state = toggleAt(state);
91
+ else if (key?.name === "up" || (key?.name === "k"))
92
+ state = moveCursor(state, -1);
93
+ else if (key?.name === "down" || (key?.name === "j"))
94
+ state = moveCursor(state, 1);
95
+ else if (key?.name === "a")
96
+ state = setAll(state, true);
97
+ else if (key?.name === "n")
98
+ state = setAll(state, false);
99
+ else if (str === " ")
100
+ state = toggleAt(state);
101
+ else
102
+ return;
103
+ paint(false);
104
+ };
105
+ readline.emitKeypressEvents(input);
106
+ input.setRawMode?.(true);
107
+ input.resume();
108
+ input.on("keypress", onKey);
109
+ output.write("\u001b[?25l");
110
+ for (const line of lines)
111
+ output.write(line + "\u001b[K\n");
112
+ });
113
+ }
@@ -0,0 +1,14 @@
1
+ /** Human-readable byte size, e.g. 1536 -> "1.5 KB". */
2
+ export declare function formatBytes(bytes: number, digits?: number): string;
3
+ export declare function formatCount(count: number): string;
4
+ /** Shorten a long path from the middle: C:\\Users\\me\\AppData\\...\\_cacache */
5
+ export declare function truncateMiddle(text: string, max: number): string;
6
+ /**
7
+ * Shorten a long path, preferring the tail: C:\Users\me\AppData\...\pnpm\store
8
+ * becomes ...\AppData\Local\pnpm\store so the distinguishing end stays visible.
9
+ */
10
+ export declare function truncatePath(text: string, max: number): string;
11
+ export declare function percent(part: number, whole: number): number;
12
+ /** A 20-cell unicode bar. */
13
+ export declare function bar(share: number, width?: number): string;
14
+ export declare function plural(n: number, word: string): string;