dir-analysis-tool 3.5.0 → 3.5.2

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.
package/README.md CHANGED
@@ -289,13 +289,19 @@ All scan options are accepted, as are `--si`, `--color`, `--no-color`, `--no-pro
289
289
 
290
290
  ### `dat watch`
291
291
 
292
- `dat watch [directory] [options]` re-analyzes whenever something changes. It uses the operating system's native file watching: recursive on macOS and Windows; on Linux, one watcher per scanned folder, so skipped folders like `node_modules` are never watched. If watching fails, it falls back to polling.
292
+ `dat watch [directory] [options]` re-analyzes whenever something changes. It uses the operating system's native file watching: recursive on macOS and Windows; on Linux, one watcher per scanned folder, so skipped folders like `node_modules` are never watched. If watching fails, it falls back to polling every 5 seconds.
293
293
 
294
294
  ```bash
295
295
  dat watch . -l 1GB # keep an eye on large files
296
296
  dat watch . --json | jq -c .summary # one JSON document per line (NDJSON)
297
+ dat watch . -j -o report.json # keep report.json up to date
297
298
  ```
298
299
 
300
+ - **Output.** Without `-o`, each report goes to stdout: pretty reports replace the previous one on a terminal (`--no-clear` keeps them), and JSON reports are printed one per line (NDJSON). With `-o`, the file is rewritten with the latest report on each change, in either format. The report file counts in the analysis like any other file, but writing it never starts a new scan, even inside the watched folder.
301
+ - **`--poll`.** A new report is printed only when it would differ from the previous one, for any reason: a size, a date, a stale or empty file, a duplicate.
302
+ - **A missing root.** A directory that doesn't exist (or isn't a directory) when `watch` starts is an error: one message, exit code `1`. If the watched directory is deleted later, `watch` says so once and waits; when it comes back, it reports again and resumes watching, on every platform and with `--poll`.
303
+ - **Stopping.** Ctrl+C stops `watch` with exit code `130`, as for every command. It also stops on its own, with exit code `0`, when the reader of its output goes away (`dat watch --json | head -1`).
304
+
299
305
  | Option | Description |
300
306
  | ------------------ | ---------------------------------------------------------- |
301
307
  | `--debounce <ms>` | Wait this long after the last change. Default `300`. |
@@ -319,7 +325,7 @@ All scan, report, and output options are accepted too (`pretty` and `json` forma
319
325
  | `1.5M`, `1.5MiB` | 1.5 × 1,024² bytes |
320
326
  | `10kB`, `500MB`, `1GB` | Decimal: 10,000, 500,000,000, and 1,000,000,000 bytes |
321
327
 
322
- **Ages and dates:** an age counts back from now (`45s`, `30min`, `12h`, `90d`, `2w`, `6mo`, `1y`). A date is `YYYY-MM-DD` in local time, or any ISO 8601 timestamp.
328
+ **Ages and dates:** an age counts back from now (`45s`, `30min`, `12h`, `90d`, `2w`, `6mo`, `1y`) and always needs a unit: `--stale 12` is an error, not 12 months. A date is `YYYY-MM-DD` in local time, or an ISO 8601 timestamp such as `2024-01-31T10:00:00Z` (local time without an offset). Nothing else is read as a date.
323
329
 
324
330
  **Patterns** use [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) relative to the analyzed directory: `*.log` matches at any depth, `build/` matches only directories, `/out` matches only at the top, `docs/**/*.pdf` matches nested files, and `!keep.log` re-includes a file that an earlier pattern in the same list excluded. A negation cannot re-include a file inside an excluded folder, a default exclude such as `node_modules` (use `--all`), or a file that `.gitignore` excludes, because exclude patterns are checked first. `dat explain <path>` shows which rule decided.
325
331
 
@@ -465,6 +471,8 @@ The `$schema` line gives you autocompletion and validation in most editors. Ever
465
471
  | `units` | `"iec"` or `"si"` | `"iec"` | `--si` |
466
472
  | `budgets` | `string[]` | `[]` | `--budget` |
467
473
 
474
+ A size without a unit is bytes in the config, as in the table above: `"largeFiles": 15` is 15 bytes, while `-l 15` on the command line still means 15 MiB, as it did in v2. Write the unit (`"largeFiles": "15MiB"`); dat warns about a `largeFiles` without a unit below 1 MiB, and `dat init` asks for a unit.
475
+
468
476
  Invalid values stop the run with a precise message. Unknown keys produce a warning. Config files from v1 and v2 still work: their keys are translated, with a deprecation warning.
469
477
 
470
478
  ## Library API
@@ -548,7 +556,9 @@ The benchmark script reports scan and duplicate timings plus process peak RSS (n
548
556
  | `0` | Success, including every `dat explain` decision |
549
557
  | `1` | Error: invalid option or config, missing directory, and so on |
550
558
  | `2` | A budget failed |
551
- | `130` | Interrupted (Ctrl+C) |
559
+ | `130` | Interrupted (Ctrl+C), including stopping `dat watch` |
560
+
561
+ A reader that stops early (`dat . --json | head`) doesn't change the exit code: a failed budget still exits `2`.
552
562
 
553
563
  ## Stability
554
564
 
@@ -577,6 +587,7 @@ v3 is a rewrite with a new output format. Most commands keep working unchanged.
577
587
  | `dist/`, `build/`, `.cache/` excluded by default | Only `.git`, `.hg`, `.svn`, and `node_modules` are; use `--gitignore` or `-e` for more |
578
588
  | Sizes in decimal units (`MB`) | Binary units by default (`MiB`); `--si` switches to decimal |
579
589
  | Config keys `excludePatterns`, `topN`, `largeSizeThresholdMB`, … | `exclude`, `top`, `largeFiles`, …, read with a deprecation warning |
590
+ | `"maxDepth": -1` for unlimited depth | Leave `maxDepth` out. `-1` still means unlimited, with a deprecation warning |
580
591
 
581
592
  ## FAQ
582
593
 
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { $ as errorMessage, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, G as parseSize, H as formatBudgetActual, I as Excluder, L as joinRelative, M as analyze, O as compare, P as listDirectories, Q as errorCode, T as explainSkips, U as parseBudget, W as formatBytes, X as AbortError, Y as parsePointInTime, Z as DatError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, f as formatCount, h as supportsColor, i as renderAnalysisCsv, k as compactAnalysis, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, q as VERSION, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-CyXKu5cI.js";
2
+ import { $ as errorCode, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as listDirectories, G as formatBytes, J as VERSION, K as parseSize, L as Excluder, M as analyze, O as compare, P as assertDirectory, Q as DatError, R as joinRelative, T as explainSkips, U as formatBudgetActual, W as parseBudget, X as parsePointInTime, Z as AbortError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, et as errorMessage, f as formatCount, h as supportsColor, i as renderAnalysisCsv, k as compactAnalysis, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-CwIrKaAV.js";
3
3
  import { existsSync, watch } from "node:fs";
4
- import { mkdir, writeFile } from "node:fs/promises";
5
- import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { mkdir, realpath, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  // src/cli/io.ts
8
8
  function processIO(signal) {
@@ -23,10 +23,40 @@ const ExitCode = {
23
23
  BudgetFailed: 2,
24
24
  Interrupted: 130
25
25
  };
26
- /** Writes to a stream and waits until the data is flushed (important for large piped output). */
26
+ const closedStreams = /* @__PURE__ */ new WeakSet();
27
+ /** Errors that mean the reader went away (`dat --json | head`), which is not a failure of dat. */
28
+ function isClosedPipe(error) {
29
+ const code = errorCode(error);
30
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED";
31
+ }
32
+ /**
33
+ * Treats a closed pipe on `stream` as the end of its output instead of an
34
+ * error: later writes are dropped, and the run still ends with its own exit
35
+ * code (a failed budget stays 2). Any other stream error is rethrown.
36
+ */
37
+ function ignoreClosedPipe(stream) {
38
+ stream.on("error", (error) => {
39
+ if (!isClosedPipe(error)) throw error;
40
+ closedStreams.add(stream);
41
+ });
42
+ }
43
+ /** True once a reader closed the stream early. */
44
+ function isClosed(stream) {
45
+ return closedStreams.has(stream);
46
+ }
47
+ /**
48
+ * Writes to a stream and waits until the data is flushed (important for large
49
+ * piped output). Resolves without writing once the reader has closed the pipe.
50
+ */
27
51
  function write(stream, text) {
52
+ if (closedStreams.has(stream)) return Promise.resolve();
28
53
  return new Promise((resolve, reject) => {
29
- stream.write(text, (error) => error ? reject(error) : resolve());
54
+ stream.write(text, (error) => {
55
+ if (!error) return resolve();
56
+ if (!isClosedPipe(error)) return reject(error);
57
+ closedStreams.add(stream);
58
+ resolve();
59
+ });
30
60
  });
31
61
  }
32
62
  function terminalWidth(io) {
@@ -1255,7 +1285,7 @@ async function ask(ctx, confirmOverwrite) {
1255
1285
  const large = bail(await p.text({
1256
1286
  message: "Report files at least this large (leave empty to skip)",
1257
1287
  placeholder: "100MiB",
1258
- validate: (value) => validateWith(value, parseSize)
1288
+ validate: (value) => validateWith(value, parseSizeWithUnit)
1259
1289
  }));
1260
1290
  const duplicates = bail(await p.confirm({
1261
1291
  message: "Look for duplicate files on every run?",
@@ -1296,6 +1326,14 @@ async function ask(ctx, confirmOverwrite) {
1296
1326
  }
1297
1327
  }
1298
1328
  var CancelledError = class extends Error {};
1329
+ /**
1330
+ * A size for the config file, which reads a number without a unit as bytes while `-l 15` reads
1331
+ * it as MiB. The answer must say which, so that "15" can't silently mean 15 bytes.
1332
+ */
1333
+ function parseSizeWithUnit(value) {
1334
+ if (/^(\d+(\.\d+)?|\.\d+)$/.test(value)) throw new RangeError(`Add a unit: ${value}MiB (what -l ${value} means) or ${value}MB. Without one, the config reads ${value} as bytes.`);
1335
+ return parseSize(value);
1336
+ }
1299
1337
  function splitList(value) {
1300
1338
  return value.split(",").map((item) => item.trim()).filter(Boolean);
1301
1339
  }
@@ -1384,6 +1422,7 @@ Examples:
1384
1422
  $ dat watch ./downloads -l 1GB keep an eye on large downloads
1385
1423
  $ dat watch . --json | jq -c .summary
1386
1424
  one JSON document per line (NDJSON)
1425
+ $ dat watch . -j -o report.json keep report.json up to date
1387
1426
  `;
1388
1427
  function registerWatch(program, ctx) {
1389
1428
  const command = program.command("watch").description("re-analyze a directory whenever it changes").argument("[directory]", "directory to watch", ".");
@@ -1403,18 +1442,23 @@ function registerWatch(program, ctx) {
1403
1442
  const pollSeconds = read.number(cli["poll"]);
1404
1443
  const clear = cli["clear"] !== false && display.format === "pretty" && ctx.io.stdout.isTTY === true;
1405
1444
  const signal = ctx.io.signal;
1445
+ await assertDirectory(target);
1406
1446
  let previous = null;
1447
+ let previousKey = "";
1407
1448
  let running = false;
1408
1449
  let pending = false;
1409
1450
  let timer = null;
1410
1451
  let changes = 0;
1411
- let polling = false;
1452
+ let polling = pollSeconds !== void 0;
1453
+ let rootGone = false;
1454
+ let rootCheck = null;
1412
1455
  const excluder = new Excluder({
1413
1456
  patterns: options.exclude ?? [],
1414
1457
  defaultExcludes: options.defaultExcludes ?? true
1415
1458
  });
1459
+ let ownFiles = /* @__PURE__ */ new Set();
1416
1460
  const render = async (result) => {
1417
- if (display.format === "json") {
1461
+ if (display.format === "json" && !display.output) {
1418
1462
  await ctx.stdout(`${stringifyJson(result)}\n`);
1419
1463
  return;
1420
1464
  }
@@ -1424,11 +1468,91 @@ function registerWatch(program, ctx) {
1424
1468
  html: void 0,
1425
1469
  csv: void 0
1426
1470
  }, listLimit(options.top));
1471
+ if (display.format === "json") return;
1427
1472
  const status = previous ? describeChange(previous, result, display.units) : "initial scan";
1428
1473
  ctx.info(ctx.err.dim(`watching ${escapeControl(target)} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1429
1474
  };
1475
+ let stopWatching = () => {};
1476
+ const stopped = new Promise((resolve) => stopWatching = resolve);
1477
+ const readerGone = () => ctx.stdoutClosed;
1430
1478
  let watcher = null;
1431
- const run = async () => {
1479
+ let poller = null;
1480
+ const closeWatcher = () => {
1481
+ watcher?.close();
1482
+ watcher = null;
1483
+ };
1484
+ const schedule = () => {
1485
+ changes++;
1486
+ if (timer) clearTimeout(timer);
1487
+ timer = setTimeout(() => void run(), debounce);
1488
+ };
1489
+ const startPolling = (seconds) => {
1490
+ polling = true;
1491
+ if (rootCheck) clearInterval(rootCheck);
1492
+ rootCheck = null;
1493
+ poller = setInterval(() => void run(), seconds * 1e3);
1494
+ };
1495
+ const markRootGone = () => {
1496
+ if (rootGone) return;
1497
+ rootGone = true;
1498
+ ctx.warn(`${escapeControl(target)} was removed; waiting for it to come back (Ctrl+C to stop)`);
1499
+ closeWatcher();
1500
+ };
1501
+ const checkRoot = async () => {
1502
+ if (running) return;
1503
+ if (rootGone || !await isDirectory(target)) await run();
1504
+ };
1505
+ const watchFailed = async (failed, error) => {
1506
+ failed.close();
1507
+ if (watcher === failed) watcher = null;
1508
+ if (!await isDirectory(target)) {
1509
+ schedule();
1510
+ return;
1511
+ }
1512
+ ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1513
+ if (!poller) startPolling(5);
1514
+ };
1515
+ const syncWatcher = async () => {
1516
+ if (polling || signal?.aborted) return;
1517
+ if (!watcher) {
1518
+ if (display.output) ownFiles = await ownFileEvents(target, ctx.resolvePath(display.output));
1519
+ const created = new TreeWatcher({
1520
+ root: target,
1521
+ isIgnored: (rel) => ownFiles.has(rel) || excluder.isPathExcluded(rel),
1522
+ onChange: schedule,
1523
+ onError: (error) => void watchFailed(created, error)
1524
+ });
1525
+ watcher = created;
1526
+ if (created.recursive) {
1527
+ created.sync([]);
1528
+ return;
1529
+ }
1530
+ }
1531
+ if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1532
+ };
1533
+ const scan = async () => {
1534
+ if (!await isDirectory(target)) {
1535
+ markRootGone();
1536
+ return null;
1537
+ }
1538
+ if (rootGone) {
1539
+ rootGone = false;
1540
+ changes++;
1541
+ }
1542
+ try {
1543
+ return await runAnalysis(ctx, target, options, {
1544
+ ...display,
1545
+ progress: display.progress && previous === null
1546
+ });
1547
+ } catch (error) {
1548
+ if (!(error instanceof AbortError) && !await isDirectory(target)) {
1549
+ markRootGone();
1550
+ return null;
1551
+ }
1552
+ throw error;
1553
+ }
1554
+ };
1555
+ const run = async (initial = false) => {
1432
1556
  if (running) {
1433
1557
  pending = true;
1434
1558
  return;
@@ -1437,63 +1561,87 @@ function registerWatch(program, ctx) {
1437
1561
  try {
1438
1562
  for (;;) {
1439
1563
  pending = false;
1440
- const result = await runAnalysis(ctx, target, options, {
1441
- ...display,
1442
- progress: display.progress && previous === null
1443
- });
1444
- if (!polling || !previous || changes > 0 || fingerprint(previous) !== fingerprint(result)) await render(result);
1564
+ const result = await scan();
1565
+ if (!result) break;
1566
+ const key = reportKey(result);
1567
+ if (!polling || !previous || changes > 0 || key !== previousKey) {
1568
+ await render(result);
1569
+ if (readerGone()) {
1570
+ stopWatching();
1571
+ break;
1572
+ }
1573
+ }
1445
1574
  previous = result;
1575
+ previousKey = key;
1446
1576
  changes = 0;
1447
- if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1577
+ try {
1578
+ await syncWatcher();
1579
+ } catch (error) {
1580
+ if (await isDirectory(target)) throw error;
1581
+ markRootGone();
1582
+ break;
1583
+ }
1448
1584
  if (!pending || signal?.aborted) break;
1449
1585
  }
1450
1586
  } catch (error) {
1451
1587
  if (error instanceof AbortError) return;
1588
+ if (initial) throw error;
1452
1589
  ctx.io.stderr.write(`${ctx.err.red("error")} ${escapeControlInLines(errorMessage(error))}\n`);
1453
1590
  } finally {
1454
1591
  running = false;
1455
1592
  }
1456
1593
  };
1457
- const schedule = () => {
1458
- changes++;
1459
- if (timer) clearTimeout(timer);
1460
- timer = setTimeout(() => void run(), debounce);
1461
- };
1462
- await run();
1463
- if (signal?.aborted) return;
1464
- let poller = null;
1465
- const startPolling = (seconds) => {
1466
- polling = true;
1467
- poller = setInterval(() => void run(), seconds * 1e3);
1468
- };
1469
- if (pollSeconds) startPolling(pollSeconds);
1470
- else {
1471
- watcher = new TreeWatcher({
1472
- root: target,
1473
- isIgnored: (rel) => excluder.isPathExcluded(rel),
1474
- onChange: schedule,
1475
- onError: (error) => {
1476
- ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1477
- watcher?.close();
1478
- watcher = null;
1479
- if (!poller) startPolling(5);
1480
- }
1481
- });
1482
- watcher.sync(watcher.recursive ? [] : await listDirectories(target, options));
1594
+ await run(true);
1595
+ if (!signal?.aborted && !readerGone()) {
1596
+ if (pollSeconds) startPolling(pollSeconds);
1597
+ else rootCheck = setInterval(() => void checkRoot(), 1e3);
1598
+ await Promise.race([stopped, new Promise((resolve) => {
1599
+ if (!signal) return;
1600
+ if (signal.aborted) resolve();
1601
+ signal.addEventListener("abort", () => resolve(), { once: true });
1602
+ })]);
1483
1603
  }
1484
- await new Promise((resolve) => {
1485
- if (!signal) return;
1486
- if (signal.aborted) resolve();
1487
- signal.addEventListener("abort", () => resolve(), { once: true });
1488
- });
1489
1604
  if (timer) clearTimeout(timer);
1490
1605
  if (poller) clearInterval(poller);
1491
- watcher?.close();
1606
+ if (rootCheck) clearInterval(rootCheck);
1607
+ closeWatcher();
1608
+ if (signal?.aborted) throw new AbortError();
1609
+ });
1610
+ }
1611
+ /** The result without the fields that change on every scan even when nothing on disk did. */
1612
+ function reportKey(result) {
1613
+ const { startedAt: _startedAt, durationMs: _durationMs, settings, staleFiles, ...rest } = result;
1614
+ return stringifyJson({
1615
+ ...rest,
1616
+ settings: {
1617
+ ...settings,
1618
+ modifiedAfter: null,
1619
+ modifiedBefore: null
1620
+ },
1621
+ staleFiles: staleFiles && {
1622
+ ...staleFiles,
1623
+ modifiedBefore: ""
1624
+ }
1492
1625
  });
1493
1626
  }
1494
- function fingerprint(result) {
1495
- const s = result.summary;
1496
- return `${s.bytes}:${s.files}:${s.directories}:${result.largestFiles.map((f) => `${f.path}@${f.modified}`).join("|")}`;
1627
+ async function isDirectory(path) {
1628
+ return stat(path).then((stats) => stats.isDirectory(), () => false);
1629
+ }
1630
+ /**
1631
+ * The root-relative `/` paths under which the watcher may report `file`: as given, and through
1632
+ * real paths, since FSEvents can report `/private/var` for a root under `/var`.
1633
+ */
1634
+ async function ownFileEvents(root, file) {
1635
+ const paths = /* @__PURE__ */ new Set();
1636
+ const add = (base, path) => {
1637
+ const rel = relative(base, path);
1638
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) paths.add(rel.split(sep).join("/"));
1639
+ };
1640
+ add(root, file);
1641
+ const realRoot = await realpath(root).catch(() => root);
1642
+ const realDir = await realpath(dirname(file)).catch(() => dirname(file));
1643
+ add(realRoot, join(realDir, basename(file)));
1644
+ return paths;
1497
1645
  }
1498
1646
  function describeChange(previous, current, units) {
1499
1647
  const bytes = current.summary.bytes - previous.summary.bytes;
@@ -1552,6 +1700,10 @@ var Context = class {
1552
1700
  stdout(text) {
1553
1701
  return write(this.io.stdout, text);
1554
1702
  }
1703
+ /** True once the reader of stdout went away (`dat watch --json | head -1`). */
1704
+ get stdoutClosed() {
1705
+ return isClosed(this.io.stdout);
1706
+ }
1555
1707
  };
1556
1708
  // src/cli/program.ts
1557
1709
  function createProgram(ctx) {
@@ -1605,10 +1757,8 @@ function handleError(error, ctx) {
1605
1757
  return ExitCode.Error;
1606
1758
  }
1607
1759
  // src/cli/main.ts
1608
- for (const stream of [process.stdout, process.stderr]) stream.on("error", (error) => {
1609
- if (errorCode(error) === "EPIPE") process.exit(0);
1610
- throw error;
1611
- });
1760
+ ignoreClosedPipe(process.stdout);
1761
+ ignoreClosedPipe(process.stderr);
1612
1762
  const controller = new AbortController();
1613
1763
  process.on("SIGINT", () => {
1614
1764
  if (controller.signal.aborted) process.exit(130);
package/dist/index.d.ts CHANGED
@@ -260,7 +260,10 @@ interface ScanSettings {
260
260
  minSize?: number | string | undefined;
261
261
  /** Only include files at most this large. */
262
262
  maxSize?: number | string | undefined;
263
- /** Only include files modified at or after this time: a date, epoch ms, `YYYY-MM-DD`, or an age such as `"30d"`. */
263
+ /**
264
+ * Only include files modified at or after this time: a `Date`, epoch ms, `YYYY-MM-DD`, an ISO 8601
265
+ * timestamp, or an age with a unit such as `"30d"`. A string without a unit (`"12"`) is rejected.
266
+ */
264
267
  modifiedAfter?: Date | number | string | undefined;
265
268
  /** Only include files modified at or before this time. Date-only values include the whole day. */
266
269
  modifiedBefore?: Date | number | string | undefined;
@@ -609,8 +612,10 @@ interface PointInTimeOptions {
609
612
  }
610
613
  /**
611
614
  * Resolves a point in time from either an age relative to now (`30d` means
612
- * "30 days ago") or an absolute date (`2024-01-31`, or any ISO 8601 timestamp).
613
- * Date-only values are interpreted in local time. Returns epoch milliseconds.
615
+ * "30 days ago") or an absolute date: `YYYY-MM-DD` in local time, or an ISO
616
+ * 8601 timestamp such as `2024-01-31T10:00:00Z` (local time without an
617
+ * offset). Anything else throws a `RangeError`, including bare numbers, which
618
+ * have no unit. Returns epoch milliseconds.
614
619
  */
615
620
  export declare function parsePointInTime(input: string, options?: PointInTimeOptions): number;
616
621
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { X as AbortError, B as BUDGET_METRICS, K as CATEGORIES, g as CONFIG_FILE_NAMES, N as DEFAULT_CONCURRENCY, F as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, A as DEFAULT_LARGE_FILE_THRESHOLD, j as DEFAULT_STALE_AGE, Z as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, q as VERSION, M as analyze, y as buildJsonSchema, R as classify, k as compactAnalysis, O as compare, m as createStyle, V as evaluateBudgets, w as explainPath, T as explainSkips, z as extensionOf, _ as findConfigFile, W as formatBytes, P as listDirectories, v as loadConfig, U as parseBudget, J as parseDuration, Y as parsePointInTime, G as parseSize, c as renderAnalysis, i as renderAnalysisCsv, r as renderAnalysisHtml, o as renderAnalysisMarkdown, l as renderComparison, a as renderComparisonCsv, s as renderComparisonMarkdown, t as renderPathExplanation, n as renderSkipsExplanation, b as validateConfig } from "./shared-CyXKu5cI.js";
1
+ export { Z as AbortError, V as BUDGET_METRICS, q as CATEGORIES, g as CONFIG_FILE_NAMES, N as DEFAULT_CONCURRENCY, I as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, A as DEFAULT_LARGE_FILE_THRESHOLD, j as DEFAULT_STALE_AGE, Q as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, J as VERSION, M as analyze, y as buildJsonSchema, z as classify, k as compactAnalysis, O as compare, m as createStyle, H as evaluateBudgets, w as explainPath, T as explainSkips, B as extensionOf, _ as findConfigFile, G as formatBytes, F as listDirectories, v as loadConfig, W as parseBudget, Y as parseDuration, X as parsePointInTime, K as parseSize, c as renderAnalysis, i as renderAnalysisCsv, r as renderAnalysisHtml, o as renderAnalysisMarkdown, l as renderComparison, a as renderComparisonCsv, s as renderComparisonMarkdown, t as renderPathExplanation, n as renderSkipsExplanation, b as validateConfig } from "./shared-CwIrKaAV.js";
@@ -49,6 +49,10 @@ const MS_PER_UNIT = {
49
49
  };
50
50
  const DURATION_PATTERN = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|min|mo|m|h|d|w|y)\s*$/i;
51
51
  const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
52
+ /** `YYYY-MM-DDTHH:mm`, with optional seconds and fraction, and an optional `Z` or `±HH:mm` offset. */
53
+ const TIMESTAMP_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-](\d{2}):(\d{2}))?$/i;
54
+ const BARE_NUMBER_PATTERN = /^\d+(?:\.\d+)?$/;
55
+ const LOOSE_DATE_PATTERN = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
52
56
  /** Parses a duration such as `90d`, `2w`, `6mo`, `1y`, `12h`, or `30min` into milliseconds. */
53
57
  function parseDuration(input) {
54
58
  const match = DURATION_PATTERN.exec(input);
@@ -57,23 +61,46 @@ function parseDuration(input) {
57
61
  }
58
62
  /**
59
63
  * Resolves a point in time from either an age relative to now (`30d` means
60
- * "30 days ago") or an absolute date (`2024-01-31`, or any ISO 8601 timestamp).
61
- * Date-only values are interpreted in local time. Returns epoch milliseconds.
64
+ * "30 days ago") or an absolute date: `YYYY-MM-DD` in local time, or an ISO
65
+ * 8601 timestamp such as `2024-01-31T10:00:00Z` (local time without an
66
+ * offset). Anything else throws a `RangeError`, including bare numbers, which
67
+ * have no unit. Returns epoch milliseconds.
62
68
  */
63
69
  function parsePointInTime(input, options = {}) {
64
70
  const now = options.now ?? Date.now();
65
71
  if (DURATION_PATTERN.test(input)) return now - parseDuration(input);
66
- const dateOnly = DATE_ONLY_PATTERN.exec(input.trim());
72
+ const text = input.trim();
73
+ const dateOnly = DATE_ONLY_PATTERN.exec(text);
67
74
  if (dateOnly) {
68
75
  const [, y, m, d] = dateOnly;
69
- const date = new Date(Number(y), Number(m) - 1, Number(d));
70
- if (date.getMonth() !== Number(m) - 1 || date.getDate() !== Number(d)) throw new RangeError(`Invalid date "${input}".`);
76
+ if (!isCalendarDate(Number(y), Number(m), Number(d))) throw new RangeError(`Invalid date "${input}".`);
77
+ const date = new Date(2e3, Number(m) - 1, Number(d));
78
+ date.setFullYear(Number(y));
71
79
  if (options.endOfDay) date.setHours(23, 59, 59, 999);
72
80
  return date.getTime();
73
81
  }
74
- const parsed = Date.parse(input);
75
- if (Number.isNaN(parsed)) throw new RangeError(`Invalid date or age "${input}". Use YYYY-MM-DD, an ISO timestamp, or an age such as 30d.`);
76
- return parsed;
82
+ const timestamp = TIMESTAMP_PATTERN.exec(text);
83
+ if (timestamp) {
84
+ const [, y, m, d, hour, minute, second = "0", offsetHours = "0", offsetMinutes = "0"] = timestamp;
85
+ const parsed = Date.parse(text.toUpperCase());
86
+ if (!isCalendarDate(Number(y), Number(m), Number(d)) || Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59 || Number(offsetHours) > 23 || Number(offsetMinutes) > 59 || Number.isNaN(parsed)) throw new RangeError(`Invalid timestamp "${input}".`);
87
+ return parsed;
88
+ }
89
+ if (/^\d{4}$/.test(text) && Number(text) >= 1900) throw new RangeError(`Invalid date or age "${input}". For a date, write YYYY-MM-DD, for example ${text}-01-01; for an age, add a unit, for example 30d.`);
90
+ if (BARE_NUMBER_PATTERN.test(text)) throw new RangeError(`Invalid date or age "${input}": an age needs a unit. Add one, for example ${text}mo (months) or ${text}d (days).`);
91
+ if (TIMESTAMP_PATTERN.test(text.replace(" ", "T"))) throw new RangeError(`Invalid timestamp "${input}". Separate the date and the time with T, for example ${text.replace(" ", "T")}.`);
92
+ const loose = LOOSE_DATE_PATTERN.exec(text);
93
+ if (loose) {
94
+ const [, y, m, d] = loose;
95
+ throw new RangeError(`Invalid date "${input}". Write dates as YYYY-MM-DD, for example ${y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}.`);
96
+ }
97
+ throw new RangeError(`Invalid date or age "${input}". Use an age such as 30d, a date as YYYY-MM-DD, or an ISO 8601 timestamp such as 2024-01-31T10:00:00Z.`);
98
+ }
99
+ /** True for a real day of the Gregorian calendar (no February 30). */
100
+ function isCalendarDate(year, month, day) {
101
+ const date = new Date(Date.UTC(2e3, month - 1, day));
102
+ date.setUTCFullYear(year);
103
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
77
104
  }
78
105
  /** Formats an elapsed duration compactly: `840ms`, `3.2s`, `2m 05s`. */
79
106
  function formatElapsed(ms) {
@@ -3495,7 +3522,7 @@ async function explainSkips(root, options = {}) {
3495
3522
  }
3496
3523
  // src/config/schema.ts
3497
3524
  const SIZE_HINT = "Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\".";
3498
- const TIME_HINT = "An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD).";
3525
+ const TIME_HINT = "An age with a unit such as \"30d\", \"6mo\", or \"1y\", a date (YYYY-MM-DD), or an ISO 8601 timestamp such as \"2024-01-31T10:00:00Z\".";
3499
3526
  /** Single source of truth for config validation, docs, and `schema.json`. */
3500
3527
  const CONFIG_FIELDS = {
3501
3528
  exclude: {
@@ -3520,7 +3547,7 @@ const CONFIG_FIELDS = {
3520
3547
  kind: "integer",
3521
3548
  min: 0
3522
3549
  },
3523
- description: "Directory levels to descend; 0 scans only the top-level files. Default: unlimited."
3550
+ description: "Directory levels to descend; 0 scans only the top-level files. Default: unlimited (leave it out; the v2 value -1 still works, with a deprecation warning)."
3524
3551
  },
3525
3552
  followSymlinks: {
3526
3553
  type: { kind: "boolean" },
@@ -3558,7 +3585,7 @@ const CONFIG_FIELDS = {
3558
3585
  kind: "size",
3559
3586
  allowBoolean: true
3560
3587
  },
3561
- description: `Report files at least this large; true uses 100 MiB. ${SIZE_HINT}`,
3588
+ description: `Report files at least this large; true uses 100 MiB. ${SIZE_HINT} A number without a unit is bytes here, while the -l flag reads it as MiB.`,
3562
3589
  examples: ["50MB"]
3563
3590
  },
3564
3591
  duplicates: {
@@ -3665,7 +3692,11 @@ function validateConfig(raw) {
3665
3692
  };
3666
3693
  const input = Object.fromEntries(Object.entries(raw));
3667
3694
  delete input["$schema"];
3668
- if (input["maxDepth"] === -1) delete input["maxDepth"];
3695
+ const largeFilesWritten = "largeFiles" in input;
3696
+ if (input["maxDepth"] === -1) {
3697
+ delete input["maxDepth"];
3698
+ warnings.push("\"maxDepth\": -1 is deprecated; leave maxDepth out for unlimited depth");
3699
+ }
3669
3700
  for (const [key, translate] of Object.entries(LEGACY_KEYS)) {
3670
3701
  if (!(key in input)) continue;
3671
3702
  const value = input[key];
@@ -3689,12 +3720,22 @@ function validateConfig(raw) {
3689
3720
  if (problem) errors.push(`"${key}" ${problem}`);
3690
3721
  else config[key] = value;
3691
3722
  }
3723
+ const small = largeFilesWritten ? smallUnitlessSize(config["largeFiles"]) : null;
3724
+ if (small !== null) warnings.push(`"largeFiles": ${JSON.stringify(config["largeFiles"])} is ${small} ${small === 1 ? "byte" : "bytes"}: a size without a unit is bytes in the config, unlike -l ${small}, which means ${small} MiB. Write "${small}MiB" if you meant MiB, or add a unit to silence this warning.`);
3692
3725
  return {
3693
3726
  config,
3694
3727
  warnings,
3695
3728
  errors
3696
3729
  };
3697
3730
  }
3731
+ /**
3732
+ * The byte count of a unitless size below 1 MiB, which is more likely a v2-style MiB count
3733
+ * (`-l 15`) than a deliberate byte threshold for "large" files; null otherwise.
3734
+ */
3735
+ function smallUnitlessSize(value) {
3736
+ const bytes = typeof value === "number" ? value : typeof value === "string" && /^\s*(\d+(\.\d+)?|\.\d+)\s*$/.test(value) ? Number(value) : null;
3737
+ return bytes !== null && bytes > 0 && bytes < 1024 ** 2 ? bytes : null;
3738
+ }
3698
3739
  function checkValue(type, value) {
3699
3740
  const got = `(got ${JSON.stringify(value)})`;
3700
3741
  switch (type.kind) {
@@ -4928,4 +4969,4 @@ function renderSkipsExplanation(result, options = {}) {
4928
4969
  }
4929
4970
  return `${lines.join("\n")}\n`;
4930
4971
  }
4931
- export { errorMessage as $, DEFAULT_LARGE_FILE_THRESHOLD as A, BUDGET_METRICS as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, DEFAULT_EXCLUDES as F, parseSize as G, formatBudgetActual as H, Excluder as I, parseDuration as J, CATEGORIES as K, joinRelative as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, listDirectories as P, errorCode as Q, classify as R, EXPLAIN_VERSION as S, explainSkips as T, parseBudget as U, evaluateBudgets as V, formatBytes as W, AbortError as X, parsePointInTime as Y, DatError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, VERSION as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, extensionOf as z };
4972
+ export { errorCode as $, DEFAULT_LARGE_FILE_THRESHOLD as A, extensionOf as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, listDirectories as F, formatBytes as G, evaluateBudgets as H, DEFAULT_EXCLUDES as I, VERSION as J, parseSize as K, Excluder as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, assertDirectory as P, DatError as Q, joinRelative as R, EXPLAIN_VERSION as S, explainSkips as T, formatBudgetActual as U, BUDGET_METRICS as V, parseBudget as W, parsePointInTime as X, parseDuration as Y, AbortError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, errorMessage as et, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, CATEGORIES as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, classify as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.0",
3
+ "version": "3.5.2",
4
4
  "description": "Fast, zero-dependency directory analysis for your terminal and CI: largest folders and files, type and extension breakdowns, staged duplicate detection, size budgets, directory diffs, and self-contained HTML, Markdown, JSON, and CSV reports.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -99,7 +99,7 @@
99
99
  "oxlint-tsgolint": "^7.0.2004",
100
100
  "prettier": "^3.9.10",
101
101
  "publint": "^0.3.25",
102
- "semantic-release": "^25.0.9",
102
+ "semantic-release": "^26.0.1",
103
103
  "tsdown": "^0.23.1",
104
104
  "typescript": "^7.0.2",
105
105
  "vitest": "^5.0.5"
package/schema.json CHANGED
@@ -35,7 +35,7 @@
35
35
  "maxDepth": {
36
36
  "type": "integer",
37
37
  "minimum": 0,
38
- "description": "Directory levels to descend; 0 scans only the top-level files. Default: unlimited."
38
+ "description": "Directory levels to descend; 0 scans only the top-level files. Default: unlimited (leave it out; the v2 value -1 still works, with a deprecation warning)."
39
39
  },
40
40
  "followSymlinks": {
41
41
  "type": "boolean",
@@ -73,11 +73,11 @@
73
73
  },
74
74
  "newerThan": {
75
75
  "type": "string",
76
- "description": "Only include files modified after this point. An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD)."
76
+ "description": "Only include files modified after this point. An age with a unit such as \"30d\", \"6mo\", or \"1y\", a date (YYYY-MM-DD), or an ISO 8601 timestamp such as \"2024-01-31T10:00:00Z\"."
77
77
  },
78
78
  "olderThan": {
79
79
  "type": "string",
80
- "description": "Only include files modified before this point. An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD)."
80
+ "description": "Only include files modified before this point. An age with a unit such as \"30d\", \"6mo\", or \"1y\", a date (YYYY-MM-DD), or an ISO 8601 timestamp such as \"2024-01-31T10:00:00Z\"."
81
81
  },
82
82
  "top": {
83
83
  "type": "integer",
@@ -98,7 +98,7 @@
98
98
  "pattern": "^\\s*(\\d+(\\.\\d+)?|\\.\\d+)\\s*([kKmMgGtTpP]([iI]?[bB])?|[bB])?\\s*$"
99
99
  }
100
100
  ],
101
- "description": "Report files at least this large; true uses 100 MiB. Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\".",
101
+ "description": "Report files at least this large; true uses 100 MiB. Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\". A number without a unit is bytes here, while the -l flag reads it as MiB.",
102
102
  "examples": [
103
103
  "50MB"
104
104
  ]
@@ -133,7 +133,7 @@
133
133
  "type": "string"
134
134
  }
135
135
  ],
136
- "description": "Report files not modified since this point; true uses one year. An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD).",
136
+ "description": "Report files not modified since this point; true uses one year. An age with a unit such as \"30d\", \"6mo\", or \"1y\", a date (YYYY-MM-DD), or an ISO 8601 timestamp such as \"2024-01-31T10:00:00Z\".",
137
137
  "examples": [
138
138
  "2y"
139
139
  ]