@acanthis-dec/cli 0.2.3 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -5,11 +5,13 @@ import fs from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import z from "zod";
8
- import { S_BAR, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, cancel, confirm, intro, isCI, isCancel, log, multiselect, note, outro, password, select, spinner, text, unicode, unicodeOr } from "@clack/prompts";
8
+ import { S_BAR, S_BAR_END, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, cancel, confirm, intro, isCI, isCancel, log, multiselect, note, outro, password, select, spinner, symbol, symbolBar, text, unicode, unicodeOr } from "@clack/prompts";
9
9
  import { createRequire } from "module";
10
10
  import { stripVTControlCharacters } from "node:util";
11
+ import fs$1 from "node:fs";
12
+ import readline from "node:readline";
11
13
  // package.json
12
- var version = "0.2.3";
14
+ var version = "0.3.0";
13
15
  // src/client.ts
14
16
  var ApiClientError = class extends Error {
15
17
  status;
@@ -576,6 +578,25 @@ async function withConcurrencyLimit(items, concurrency, worker) {
576
578
  await Promise.all(Array.from({ length: workerCount }, () => runWorker()));
577
579
  return results;
578
580
  }
581
+ /**
582
+ * Resolves a base output directory path, expanding `~` / `~/` / `~\` to the user's home directory
583
+ * and resolving relative paths against the current working directory.
584
+ */
585
+ function resolveOutputBaseDir(rawDir) {
586
+ const trimmed = rawDir.trim();
587
+ if (!trimmed) return path.resolve(".");
588
+ if (trimmed === "~") return os.homedir();
589
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return path.resolve(os.homedir(), trimmed.slice(2));
590
+ return path.resolve(trimmed);
591
+ }
592
+ /**
593
+ * Resolves the final export directory, appending a sanitized novel title subdirectory by default.
594
+ */
595
+ function resolveExportTargetDir(baseDir, novelTitle, subdir = true) {
596
+ const resolvedBase = resolveOutputBaseDir(baseDir);
597
+ if (!subdir) return resolvedBase;
598
+ return path.join(resolvedBase, sanitizeFilename(novelTitle));
599
+ }
579
600
  // src/commands/shared.ts
580
601
  const serverTokenArgs = {
581
602
  server: {
@@ -5299,7 +5320,8 @@ async function runExport(client, options, callbacks) {
5299
5320
  const novelCover = novel.coverUrl?.trim() ? assetByRawUrl.get(novel.coverUrl.trim()) : void 0;
5300
5321
  const summaryText = novel.summary.trim() ? novel.summary : void 0;
5301
5322
  const genresList = novel.genres.length > 0 ? novel.genres : void 0;
5302
- await fs.mkdir(options.outputDir, { recursive: true });
5323
+ const targetDir = resolveExportTargetDir(options.outputDir, novel.title, options.subdir !== false);
5324
+ await fs.mkdir(targetDir, { recursive: true });
5303
5325
  const files = [];
5304
5326
  if (options.mode === "split") {
5305
5327
  const totalSteps = selectedVolumes.length;
@@ -5309,7 +5331,7 @@ async function runExport(client, options, callbacks) {
5309
5331
  const volumeIllustUrls = illustrationUrlsPerVolume[vIdx];
5310
5332
  if (!volume || !chapters || !volumeIllustUrls) continue;
5311
5333
  const baseName = sanitizeFilename(`[${novel.author}] ${novel.title} - ${volume.title}`);
5312
- const targetPath = path.join(options.outputDir, `${baseName}.epub`);
5334
+ const targetPath = path.join(targetDir, `${baseName}.epub`);
5313
5335
  const displayTitle = `${novel.title} - ${volume.title}`;
5314
5336
  if (!options.overwrite && await fileExists(targetPath)) {
5315
5337
  emitWarning(`Skipped existing file: ${targetPath}`);
@@ -5385,7 +5407,7 @@ async function runExport(client, options, callbacks) {
5385
5407
  } else {
5386
5408
  const baseName = sanitizeFilename(`[${novel.author}] ${novel.title}`);
5387
5409
  const suffix = selectedAllVolumes ? "" : " (选集)";
5388
- const targetPath = path.join(options.outputDir, `${baseName}${suffix}.epub`);
5410
+ const targetPath = path.join(targetDir, `${baseName}${suffix}.epub`);
5389
5411
  const totalChapterCount = fetchedChaptersPerVolume.reduce((sum, list) => sum + list.length, 0);
5390
5412
  if (!options.overwrite && await fileExists(targetPath)) {
5391
5413
  emitWarning(`Skipped existing file: ${targetPath}`);
@@ -5445,7 +5467,7 @@ async function runExport(client, options, callbacks) {
5445
5467
  phase: "write",
5446
5468
  current: 1,
5447
5469
  total: 1,
5448
- message: `Writing ${targetPath}`
5470
+ message: `Writing ${path.basename(targetPath)}`
5449
5471
  });
5450
5472
  await fs.writeFile(targetPath, epubBytes);
5451
5473
  files.push({
@@ -5461,14 +5483,15 @@ async function runExport(client, options, callbacks) {
5461
5483
  novelTitle: novel.title,
5462
5484
  source: options.source,
5463
5485
  mode: options.mode,
5486
+ outputDir: targetDir,
5464
5487
  files,
5465
5488
  warnings
5466
5489
  };
5467
5490
  }
5468
5491
  // src/progress.ts
5469
5492
  const ESC_CODE = 27;
5470
- const CURSOR_HIDE = "\x1B[?25l";
5471
- const CURSOR_SHOW = "\x1B[?25h";
5493
+ const CURSOR_HIDE$1 = "\x1B[?25l";
5494
+ const CURSOR_SHOW$1 = "\x1B[?25h";
5472
5495
  const RESET_STYLE = "\x1B[0m";
5473
5496
  const SPINNER_FRAMES = unicode ? [
5474
5497
  "◒",
@@ -5485,9 +5508,9 @@ const SPINNER_DELAY_MS = unicode ? 80 : 120;
5485
5508
  const RENDER_THROTTLE_MS = 50;
5486
5509
  const BAR_FILLED = unicodeOr("█", "#");
5487
5510
  const BAR_EMPTY = unicodeOr("░", "-");
5488
- const ELLIPSIS = unicodeOr("…", "...");
5511
+ const ELLIPSIS$1 = unicodeOr("…", "...");
5489
5512
  const TRUNCATE_ELLIPSIS = unicodeOr("…", ".");
5490
- const CHEVRON = unicodeOr("›", ">");
5513
+ const CHEVRON$1 = unicodeOr("›", ">");
5491
5514
  const ICON_PENDING = unicodeOr("○", "o");
5492
5515
  const ICON_DONE = unicodeOr("✓", "+");
5493
5516
  const ICON_SKIPPED = unicodeOr("–", "-");
@@ -5717,7 +5740,7 @@ function createExportProgressRenderer(options) {
5717
5740
  };
5718
5741
  const formatActiveLine = (budget) => {
5719
5742
  if (activeVolumeTitle && activeDetail) {
5720
- const sepWidth = getDisplayWidth(` ${CHEVRON} `);
5743
+ const sepWidth = getDisplayWidth(` ${CHEVRON$1} `);
5721
5744
  const innerBudget = Math.max(4, budget - sepWidth);
5722
5745
  const volRaw = getDisplayWidth(activeVolumeTitle);
5723
5746
  const detailRaw = getDisplayWidth(activeDetail);
@@ -5742,7 +5765,7 @@ function createExportProgressRenderer(options) {
5742
5765
  }
5743
5766
  const volPart = truncatePlain(activeVolumeTitle, volLimit);
5744
5767
  const detailPart = truncatePlain(activeDetail, detailLimit);
5745
- return `${pc.cyan(volPart)} ${pc.dim(CHEVRON)} ${detailPart}`;
5768
+ return `${pc.cyan(volPart)} ${pc.dim(CHEVRON$1)} ${detailPart}`;
5746
5769
  }
5747
5770
  if (activeVolumeTitle) return pc.cyan(truncatePlain(activeVolumeTitle, budget));
5748
5771
  if (activeDetail) return truncatePlain(activeDetail, budget);
@@ -5870,14 +5893,14 @@ function createExportProgressRenderer(options) {
5870
5893
  const vol = volumes[i];
5871
5894
  if (vol && isVolumeCompleteInPhase(vol)) doneBefore += 1;
5872
5895
  }
5873
- lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS} ${start} earlier volume(s) (${doneBefore}/${start} done)`)}`);
5896
+ lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS$1} ${start} earlier volume(s) (${doneBefore}/${start} done)`)}`);
5874
5897
  }
5875
5898
  for (let i = start; i < end; i += 1) {
5876
5899
  const vol = volumes[i];
5877
5900
  if (!vol) continue;
5878
5901
  lines.push(buildVolumeRow(vol, spinnerFrame, columns, contentBudget));
5879
5902
  }
5880
- if (end < totalVolumes) lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS} ${totalVolumes - end} more volume(s)`)}`);
5903
+ if (end < totalVolumes) lines.push(`${guidePrefix}${pc.dim(`${ELLIPSIS$1} ${totalVolumes - end} more volume(s)`)}`);
5881
5904
  return lines.map((line) => truncateAnsi(line, maxLineWidth));
5882
5905
  };
5883
5906
  const renderFrame = () => {
@@ -5899,7 +5922,7 @@ function createExportProgressRenderer(options) {
5899
5922
  };
5900
5923
  const restoreCursorIfHidden = () => {
5901
5924
  if (cursorHidden) {
5902
- output.write(CURSOR_SHOW);
5925
+ output.write(CURSOR_SHOW$1);
5903
5926
  cursorHidden = false;
5904
5927
  }
5905
5928
  };
@@ -5962,7 +5985,7 @@ function createExportProgressRenderer(options) {
5962
5985
  return;
5963
5986
  }
5964
5987
  if (withGuide) output.write(`${pc.gray(S_BAR)}\n`);
5965
- output.write(CURSOR_HIDE);
5988
+ output.write(CURSOR_HIDE$1);
5966
5989
  cursorHidden = true;
5967
5990
  onResize = () => {
5968
5991
  renderFrame();
@@ -6110,9 +6133,15 @@ const exportCommand = defineCommand({
6110
6133
  output: {
6111
6134
  type: "string",
6112
6135
  alias: "o",
6113
- description: "Output directory for EPUB files",
6136
+ description: "Base output directory (supports relative paths and ~; defaults to current directory)",
6114
6137
  valueHint: "dir"
6115
6138
  },
6139
+ subdir: {
6140
+ type: "boolean",
6141
+ default: true,
6142
+ description: "Create a subdirectory named after the novel title inside the base output directory",
6143
+ negativeDescription: "Write EPUB file(s) directly into the base output directory without a novel subdirectory"
6144
+ },
6116
6145
  mode: {
6117
6146
  type: "string",
6118
6147
  alias: "m",
@@ -6185,6 +6214,7 @@ const exportCommand = defineCommand({
6185
6214
  source: config.defaultSource,
6186
6215
  token: config.token,
6187
6216
  outputDir: config.outputDir,
6217
+ subdir: args.subdir !== false,
6188
6218
  mode: effectiveMode,
6189
6219
  volumes: volumesSpec,
6190
6220
  illustrations: args.illustrations !== false,
@@ -6381,6 +6411,550 @@ const sourcesCommand = defineCommand({
6381
6411
  }
6382
6412
  }
6383
6413
  });
6414
+ // src/dir-prompt.ts
6415
+ const CURSOR_HIDE = "\x1B[?25l";
6416
+ const CURSOR_SHOW = "\x1B[?25h";
6417
+ const CHEVRON = unicodeOr("▸", ">");
6418
+ const ARROW_RIGHT = unicodeOr("→", "->");
6419
+ const ELLIPSIS = unicodeOr("…", "...");
6420
+ const DIR_PROMPT_CANCEL = Symbol("acanthis:dir-prompt-cancel");
6421
+ /**
6422
+ * Checks whether a value returned from `promptDirectory` indicates cancellation.
6423
+ */
6424
+ function isDirectoryPromptCancel(value) {
6425
+ return value === DIR_PROMPT_CANCEL;
6426
+ }
6427
+ function resolveBaseWithContext(rawDir, cwd, homeDir) {
6428
+ const trimmed = rawDir.trim();
6429
+ if (!trimmed) return path.resolve(cwd);
6430
+ if (trimmed === "~") return homeDir;
6431
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return path.resolve(homeDir, trimmed.slice(2));
6432
+ return path.resolve(cwd, trimmed);
6433
+ }
6434
+ function detectSeparator(rawInput, platform) {
6435
+ if (rawInput.includes("/")) return "/";
6436
+ if (rawInput.includes("\\")) return "\\";
6437
+ return platform === "win32" ? "\\" : "/";
6438
+ }
6439
+ function listSubdirectories(dirPath, cache) {
6440
+ const cached = cache?.get(dirPath);
6441
+ if (cached !== void 0) return cached;
6442
+ let entries;
6443
+ try {
6444
+ entries = fs$1.readdirSync(dirPath, { withFileTypes: true });
6445
+ } catch {
6446
+ return [];
6447
+ }
6448
+ const dirs = [];
6449
+ for (const entry of entries) {
6450
+ if (entry.isDirectory()) {
6451
+ dirs.push(entry.name);
6452
+ continue;
6453
+ }
6454
+ if (entry.isSymbolicLink()) try {
6455
+ if (fs$1.statSync(path.join(dirPath, entry.name)).isDirectory()) dirs.push(entry.name);
6456
+ } catch {}
6457
+ }
6458
+ dirs.sort((a, b) => a.localeCompare(b, "en", {
6459
+ sensitivity: "base",
6460
+ numeric: true
6461
+ }));
6462
+ cache?.set(dirPath, dirs);
6463
+ return dirs;
6464
+ }
6465
+ function computeLongestCommonPrefix(values) {
6466
+ if (values.length === 0) return "";
6467
+ const firstValue = values[0];
6468
+ if (firstValue === void 0) return "";
6469
+ if (values.length === 1) return firstValue;
6470
+ const splitValues = values.map((v) => [...v]);
6471
+ const firstChars = splitValues[0] ?? [];
6472
+ let prefix = "";
6473
+ for (let i = 0; i < firstChars.length; i += 1) {
6474
+ const targetChar = firstChars[i];
6475
+ if (targetChar === void 0) break;
6476
+ const targetLower = targetChar.toLowerCase();
6477
+ let allMatch = true;
6478
+ for (let j = 1; j < splitValues.length; j += 1) {
6479
+ const candidateChar = splitValues[j]?.[i];
6480
+ if (candidateChar === void 0 || candidateChar.toLowerCase() !== targetLower) {
6481
+ allMatch = false;
6482
+ break;
6483
+ }
6484
+ }
6485
+ if (!allMatch) break;
6486
+ prefix += targetChar;
6487
+ }
6488
+ return prefix;
6489
+ }
6490
+ /**
6491
+ * Computes the remaining suffix to render as inline ghost text for a candidate path.
6492
+ */
6493
+ function computeGhostSuffix(rawInput, candidate) {
6494
+ if (!candidate) return "";
6495
+ if (candidate.length > rawInput.length && candidate.toLowerCase().startsWith(rawInput.toLowerCase())) return candidate.slice(rawInput.length);
6496
+ return "";
6497
+ }
6498
+ /**
6499
+ * Computes matching subdirectory completions for a partially typed path.
6500
+ */
6501
+ function getDirectoryCompletions(rawInput, options) {
6502
+ const cwd = options?.cwd ?? process.cwd();
6503
+ const homeDir = options?.homeDir ?? os.homedir();
6504
+ const platform = options?.platform ?? process.platform;
6505
+ const sep = detectSeparator(rawInput, platform);
6506
+ let dirPrefixDisplay = "";
6507
+ let searchDirFs = cwd;
6508
+ let namePrefix = "";
6509
+ if (rawInput === "") {
6510
+ dirPrefixDisplay = "";
6511
+ searchDirFs = cwd;
6512
+ namePrefix = "";
6513
+ } else if (rawInput === ".") {
6514
+ dirPrefixDisplay = `.${sep}`;
6515
+ searchDirFs = cwd;
6516
+ namePrefix = "";
6517
+ } else if (rawInput === "..") {
6518
+ dirPrefixDisplay = `..${sep}`;
6519
+ searchDirFs = path.resolve(cwd, "..");
6520
+ namePrefix = "";
6521
+ } else if (rawInput === "~") {
6522
+ dirPrefixDisplay = `~${sep}`;
6523
+ searchDirFs = homeDir;
6524
+ namePrefix = "";
6525
+ } else if (rawInput.endsWith("/") || rawInput.endsWith("\\")) {
6526
+ dirPrefixDisplay = rawInput;
6527
+ searchDirFs = resolveBaseWithContext(rawInput, cwd, homeDir);
6528
+ namePrefix = "";
6529
+ } else {
6530
+ const lastSepIdx = Math.max(rawInput.lastIndexOf("/"), rawInput.lastIndexOf("\\"));
6531
+ if (lastSepIdx >= 0) {
6532
+ dirPrefixDisplay = rawInput.slice(0, lastSepIdx + 1);
6533
+ namePrefix = rawInput.slice(lastSepIdx + 1);
6534
+ searchDirFs = resolveBaseWithContext(dirPrefixDisplay, cwd, homeDir);
6535
+ } else {
6536
+ dirPrefixDisplay = "";
6537
+ namePrefix = rawInput;
6538
+ searchDirFs = cwd;
6539
+ }
6540
+ }
6541
+ const allDirs = listSubdirectories(searchDirFs, options?.cache);
6542
+ const includeHidden = namePrefix.startsWith(".");
6543
+ const namePrefixLower = namePrefix.toLowerCase();
6544
+ const filtered = allDirs.filter((name) => {
6545
+ if (!includeHidden && name.startsWith(".")) return false;
6546
+ if (namePrefix.length === 0) return true;
6547
+ return name.toLowerCase().startsWith(namePrefixLower);
6548
+ });
6549
+ if (namePrefix.length > 0 && platform !== "win32") filtered.sort((a, b) => {
6550
+ const aExact = a.startsWith(namePrefix) ? 0 : 1;
6551
+ const bExact = b.startsWith(namePrefix) ? 0 : 1;
6552
+ if (aExact !== bExact) return aExact - bExact;
6553
+ return a.localeCompare(b, "en", {
6554
+ sensitivity: "base",
6555
+ numeric: true
6556
+ });
6557
+ });
6558
+ const matches = filtered.map((name) => `${dirPrefixDisplay}${name}${sep}`);
6559
+ return {
6560
+ matches,
6561
+ labels: filtered.map((name) => `${name}${sep}`),
6562
+ commonPrefix: computeLongestCommonPrefix(matches),
6563
+ ghostSuffix: computeGhostSuffix(rawInput, matches[0]),
6564
+ resolvedParentDir: searchDirFs
6565
+ };
6566
+ }
6567
+ function stripNonPrintable(str) {
6568
+ let cleaned = "";
6569
+ for (const ch of str) {
6570
+ const cp = ch.codePointAt(0);
6571
+ if (cp !== void 0 && cp >= 32 && cp !== 127) cleaned += ch;
6572
+ }
6573
+ return cleaned;
6574
+ }
6575
+ function deleteLastPathSegment(beforeCursor) {
6576
+ if (!beforeCursor) return "";
6577
+ const chars = [...beforeCursor];
6578
+ while (chars.length > 0) {
6579
+ const last = chars[chars.length - 1];
6580
+ if (last === "/" || last === "\\") chars.pop();
6581
+ else break;
6582
+ }
6583
+ while (chars.length > 0) {
6584
+ const last = chars[chars.length - 1];
6585
+ if (last === "/" || last === "\\") break;
6586
+ chars.pop();
6587
+ }
6588
+ return chars.join("");
6589
+ }
6590
+ /**
6591
+ * Prompts the user for a directory path with zsh-autosuggestions / PSReadLine-style
6592
+ * inline ghost suggestions, Tab/Shift+Tab cycling, arrow selection, and path preview.
6593
+ */
6594
+ async function promptDirectory(options) {
6595
+ const input = options.input ?? process.stdin;
6596
+ const output = options.output ?? process.stdout;
6597
+ if (!input.isTTY || !output.isTTY) {
6598
+ const validateFn = options.validate;
6599
+ const fallbackOpts = {
6600
+ message: options.message,
6601
+ ...options.initialValue !== void 0 ? {
6602
+ initialValue: options.initialValue,
6603
+ defaultValue: options.initialValue
6604
+ } : {},
6605
+ ...options.placeholder !== void 0 ? { placeholder: options.placeholder } : {},
6606
+ ...validateFn !== void 0 ? { validate: (val) => validateFn(val ?? "") } : {}
6607
+ };
6608
+ const result = await text(fallbackOpts);
6609
+ return isCancel(result) ? DIR_PROMPT_CANCEL : result;
6610
+ }
6611
+ return await new Promise((resolve) => {
6612
+ let buffer = options.initialValue ?? ".";
6613
+ let cursor = [...buffer].length;
6614
+ let errorMessage = "";
6615
+ let selectedIndex = 0;
6616
+ let lastRenderedLines = 0;
6617
+ let settled = false;
6618
+ let tabCycle;
6619
+ const dirCache = /* @__PURE__ */ new Map();
6620
+ let completions = getDirectoryCompletions(buffer, { cache: dirCache });
6621
+ const refreshSuggestions = (resetSelection = true) => {
6622
+ tabCycle = void 0;
6623
+ completions = getDirectoryCompletions(buffer, { cache: dirCache });
6624
+ if (completions.matches.length === 0) selectedIndex = 0;
6625
+ else if (resetSelection) selectedIndex = 0;
6626
+ else if (selectedIndex >= completions.matches.length) selectedIndex = completions.matches.length - 1;
6627
+ };
6628
+ const buildActiveInputDisplay = () => {
6629
+ const chars = [...buffer];
6630
+ const before = chars.slice(0, cursor).join("");
6631
+ if (cursor < chars.length) {
6632
+ const atCursor = chars[cursor] ?? " ";
6633
+ const after = chars.slice(cursor + 1).join("");
6634
+ return `${before}${pc.inverse(atCursor)}${after}`;
6635
+ }
6636
+ if (tabCycle) return `${buffer}${pc.inverse(" ")}`;
6637
+ const activeCandidate = completions.matches[selectedIndex];
6638
+ const ghostSuffix = computeGhostSuffix(buffer, activeCandidate);
6639
+ if (ghostSuffix.length > 0) {
6640
+ const ghostChars = [...ghostSuffix];
6641
+ const firstGhost = ghostChars[0] ?? " ";
6642
+ const restGhost = ghostChars.slice(1).join("");
6643
+ return `${buffer}${pc.inverse(firstGhost)}${pc.dim(restGhost)}`;
6644
+ }
6645
+ if (buffer.length === 0 && options.placeholder) {
6646
+ const placeholderChars = [...options.placeholder];
6647
+ const firstPh = placeholderChars[0] ?? " ";
6648
+ const restPh = placeholderChars.slice(1).join("");
6649
+ return `${pc.inverse(firstPh)}${pc.dim(restPh)}`;
6650
+ }
6651
+ return `${buffer}${pc.inverse(" ")}`;
6652
+ };
6653
+ const renderState = (state) => {
6654
+ const columns = Math.max(20, output.columns || 80);
6655
+ const rows = Math.max(8, output.rows || 24);
6656
+ const maxLineWidth = Math.max(19, columns - 1);
6657
+ const lines = [];
6658
+ lines.push(`${symbol(state)} ${options.message}`);
6659
+ if (state === "submit") lines.push(`${pc.gray(S_BAR)} ${pc.dim(buffer)}`);
6660
+ else if (state === "cancel") {
6661
+ if (buffer.length > 0) lines.push(`${pc.gray(S_BAR)} ${pc.strikethrough(pc.dim(buffer))}`);
6662
+ lines.push(pc.gray(S_BAR));
6663
+ } else {
6664
+ const bar = `${symbolBar(state)} `;
6665
+ const barEnd = state === "error" ? pc.yellow(S_BAR_END) : pc.cyan(S_BAR_END);
6666
+ lines.push(`${bar}${buildActiveInputDisplay()}`);
6667
+ const activeLabels = tabCycle ? tabCycle.labels : completions.labels;
6668
+ const activeHighlight = tabCycle ? tabCycle.index : selectedIndex;
6669
+ const reservedRows = options.preview !== void 0 ? 6 : 5;
6670
+ const maxVisible = Math.max(2, Math.min(5, rows - reservedRows));
6671
+ if (activeLabels.length > 0) {
6672
+ let start = 0;
6673
+ let end = activeLabels.length;
6674
+ if (activeLabels.length > maxVisible) {
6675
+ const half = Math.floor(maxVisible / 2);
6676
+ start = Math.max(0, activeHighlight - half);
6677
+ if (start + maxVisible > activeLabels.length) start = Math.max(0, activeLabels.length - maxVisible);
6678
+ end = Math.min(activeLabels.length, start + maxVisible);
6679
+ }
6680
+ const labelBudget = Math.max(10, maxLineWidth - 6);
6681
+ for (let i = start; i < end; i += 1) {
6682
+ const shownLabel = truncatePlain(activeLabels[i] ?? "", labelBudget);
6683
+ if (i === activeHighlight) lines.push(`${bar} ${pc.cyan(CHEVRON)} ${pc.cyan(shownLabel)}`);
6684
+ else lines.push(`${bar} ${pc.dim(shownLabel)}`);
6685
+ }
6686
+ const hiddenCount = activeLabels.length - (end - start);
6687
+ if (hiddenCount > 0) lines.push(`${bar} ${pc.dim(`${ELLIPSIS} +${hiddenCount} more`)}`);
6688
+ }
6689
+ if (options.preview) {
6690
+ const previewText = options.preview(buffer);
6691
+ if (previewText) {
6692
+ const shownPreview = truncatePlain(previewText, Math.max(10, maxLineWidth - 6));
6693
+ lines.push(`${bar}${pc.dim(`${ARROW_RIGHT} ${shownPreview}`)}`);
6694
+ }
6695
+ }
6696
+ if (state === "error" && errorMessage) lines.push(`${barEnd} ${pc.yellow(errorMessage)}`);
6697
+ else {
6698
+ const hintText = "Tab: complete • →: accept • ↑/↓: pick • Enter: confirm";
6699
+ const hintBudget = Math.max(10, maxLineWidth - 3);
6700
+ const shownHint = getDisplayWidth(hintText) <= hintBudget ? hintText : "Tab • → • ↑/↓ • Enter";
6701
+ lines.push(`${barEnd} ${pc.dim(shownHint)}`);
6702
+ }
6703
+ }
6704
+ const clampedLines = lines.map((line) => truncateAnsi(line, maxLineWidth));
6705
+ let frame = "";
6706
+ if (lastRenderedLines > 1) frame += `\x1b[${lastRenderedLines - 1}A`;
6707
+ if (lastRenderedLines > 0) frame += "\r\x1B[0J";
6708
+ frame += clampedLines.join("\n");
6709
+ if (state === "submit" || state === "cancel") frame += "\n";
6710
+ output.write(frame);
6711
+ lastRenderedLines = clampedLines.length;
6712
+ };
6713
+ const rl = readline.createInterface({
6714
+ input,
6715
+ tabSize: 2,
6716
+ prompt: "",
6717
+ escapeCodeTimeout: 50,
6718
+ terminal: true
6719
+ });
6720
+ const onResize = () => {
6721
+ if (!settled) renderState(errorMessage ? "error" : "active");
6722
+ };
6723
+ const onExit = () => {
6724
+ output.write(CURSOR_SHOW);
6725
+ };
6726
+ const cleanup = () => {
6727
+ if (settled) return;
6728
+ settled = true;
6729
+ input.off("keypress", onKeypress);
6730
+ output.off("resize", onResize);
6731
+ process.off("exit", onExit);
6732
+ rl.terminal = false;
6733
+ rl.close();
6734
+ rawInputSetMode(false);
6735
+ output.write(CURSOR_SHOW);
6736
+ };
6737
+ const rawInputSetMode = (mode) => {
6738
+ if (input.isTTY && typeof input.setRawMode === "function") input.setRawMode(mode);
6739
+ };
6740
+ const acceptCandidate = (candidate) => {
6741
+ buffer = candidate;
6742
+ cursor = [...buffer].length;
6743
+ errorMessage = "";
6744
+ refreshSuggestions(true);
6745
+ };
6746
+ const onKeypress = (str, key) => {
6747
+ if (settled) return;
6748
+ const keyName = key?.name ?? "";
6749
+ if (keyName === "escape" || key?.ctrl && keyName === "c") {
6750
+ renderState("cancel");
6751
+ cleanup();
6752
+ resolve(DIR_PROMPT_CANCEL);
6753
+ return;
6754
+ }
6755
+ if (keyName === "return" || keyName === "enter") {
6756
+ tabCycle = void 0;
6757
+ const validationError = options.validate?.(buffer);
6758
+ if (validationError) {
6759
+ errorMessage = validationError;
6760
+ renderState("error");
6761
+ return;
6762
+ }
6763
+ errorMessage = "";
6764
+ renderState("submit");
6765
+ cleanup();
6766
+ resolve(buffer);
6767
+ return;
6768
+ }
6769
+ if (keyName === "tab") {
6770
+ errorMessage = "";
6771
+ if (tabCycle && tabCycle.candidates.length > 0) {
6772
+ const len = tabCycle.candidates.length;
6773
+ tabCycle.index = key?.shift ? (tabCycle.index - 1 + len) % len : (tabCycle.index + 1) % len;
6774
+ const nextCandidate = tabCycle.candidates[tabCycle.index];
6775
+ if (nextCandidate !== void 0) {
6776
+ buffer = nextCandidate;
6777
+ cursor = [...buffer].length;
6778
+ }
6779
+ renderState("active");
6780
+ return;
6781
+ }
6782
+ if (completions.matches.length === 1 && completions.matches[0]) {
6783
+ acceptCandidate(completions.matches[0]);
6784
+ renderState("active");
6785
+ return;
6786
+ }
6787
+ if (completions.matches.length > 1) {
6788
+ if (completions.commonPrefix.length > buffer.length && completions.commonPrefix.toLowerCase().startsWith(buffer.toLowerCase())) {
6789
+ buffer = completions.commonPrefix;
6790
+ cursor = [...buffer].length;
6791
+ refreshSuggestions(true);
6792
+ renderState("active");
6793
+ return;
6794
+ }
6795
+ const initialIdx = key?.shift ? completions.matches.length - 1 : selectedIndex;
6796
+ const chosen = completions.matches[initialIdx];
6797
+ if (chosen !== void 0) {
6798
+ tabCycle = {
6799
+ candidates: completions.matches,
6800
+ labels: completions.labels,
6801
+ index: initialIdx
6802
+ };
6803
+ buffer = chosen;
6804
+ cursor = [...buffer].length;
6805
+ }
6806
+ renderState("active");
6807
+ return;
6808
+ }
6809
+ renderState("active");
6810
+ return;
6811
+ }
6812
+ if (keyName === "up" || keyName === "down") {
6813
+ errorMessage = "";
6814
+ const delta = keyName === "up" ? -1 : 1;
6815
+ if (tabCycle && tabCycle.candidates.length > 0) {
6816
+ const len = tabCycle.candidates.length;
6817
+ tabCycle.index = (tabCycle.index + delta + len) % len;
6818
+ const nextCandidate = tabCycle.candidates[tabCycle.index];
6819
+ if (nextCandidate !== void 0) {
6820
+ buffer = nextCandidate;
6821
+ cursor = [...buffer].length;
6822
+ }
6823
+ } else if (completions.matches.length > 0) {
6824
+ const len = completions.matches.length;
6825
+ selectedIndex = (selectedIndex + delta + len) % len;
6826
+ }
6827
+ renderState("active");
6828
+ return;
6829
+ }
6830
+ if (keyName === "right") {
6831
+ errorMessage = "";
6832
+ if (tabCycle) {
6833
+ refreshSuggestions(true);
6834
+ renderState("active");
6835
+ return;
6836
+ }
6837
+ const chars = [...buffer];
6838
+ if (cursor < chars.length) {
6839
+ cursor += 1;
6840
+ renderState("active");
6841
+ return;
6842
+ }
6843
+ const activeCandidate = completions.matches[selectedIndex];
6844
+ if (activeCandidate && computeGhostSuffix(buffer, activeCandidate).length > 0) {
6845
+ acceptCandidate(activeCandidate);
6846
+ renderState("active");
6847
+ }
6848
+ return;
6849
+ }
6850
+ if (keyName === "end" || key?.ctrl && keyName === "e") {
6851
+ errorMessage = "";
6852
+ if (tabCycle) {
6853
+ refreshSuggestions(true);
6854
+ renderState("active");
6855
+ return;
6856
+ }
6857
+ const chars = [...buffer];
6858
+ if (cursor < chars.length) {
6859
+ cursor = chars.length;
6860
+ renderState("active");
6861
+ return;
6862
+ }
6863
+ const activeCandidate = completions.matches[selectedIndex];
6864
+ if (activeCandidate && computeGhostSuffix(buffer, activeCandidate).length > 0) {
6865
+ acceptCandidate(activeCandidate);
6866
+ renderState("active");
6867
+ }
6868
+ return;
6869
+ }
6870
+ if (keyName === "left") {
6871
+ errorMessage = "";
6872
+ tabCycle = void 0;
6873
+ cursor = Math.max(0, cursor - 1);
6874
+ renderState("active");
6875
+ return;
6876
+ }
6877
+ if (keyName === "home" || key?.ctrl && keyName === "a") {
6878
+ errorMessage = "";
6879
+ tabCycle = void 0;
6880
+ cursor = 0;
6881
+ renderState("active");
6882
+ return;
6883
+ }
6884
+ if (keyName === "backspace") {
6885
+ errorMessage = "";
6886
+ tabCycle = void 0;
6887
+ if (cursor > 0) {
6888
+ const chars = [...buffer];
6889
+ chars.splice(cursor - 1, 1);
6890
+ buffer = chars.join("");
6891
+ cursor -= 1;
6892
+ refreshSuggestions(true);
6893
+ }
6894
+ renderState("active");
6895
+ return;
6896
+ }
6897
+ if (keyName === "delete") {
6898
+ errorMessage = "";
6899
+ tabCycle = void 0;
6900
+ const chars = [...buffer];
6901
+ if (cursor < chars.length) {
6902
+ chars.splice(cursor, 1);
6903
+ buffer = chars.join("");
6904
+ refreshSuggestions(true);
6905
+ }
6906
+ renderState("active");
6907
+ return;
6908
+ }
6909
+ if (key?.ctrl && keyName === "u") {
6910
+ errorMessage = "";
6911
+ tabCycle = void 0;
6912
+ if (cursor > 0) {
6913
+ buffer = [...buffer].slice(cursor).join("");
6914
+ cursor = 0;
6915
+ refreshSuggestions(true);
6916
+ }
6917
+ renderState("active");
6918
+ return;
6919
+ }
6920
+ if (key?.ctrl && keyName === "w") {
6921
+ errorMessage = "";
6922
+ tabCycle = void 0;
6923
+ if (cursor > 0) {
6924
+ const chars = [...buffer];
6925
+ const before = chars.slice(0, cursor).join("");
6926
+ const after = chars.slice(cursor).join("");
6927
+ const newBefore = deleteLastPathSegment(before);
6928
+ buffer = `${newBefore}${after}`;
6929
+ cursor = [...newBefore].length;
6930
+ refreshSuggestions(true);
6931
+ }
6932
+ renderState("active");
6933
+ return;
6934
+ }
6935
+ if (!key?.ctrl && !key?.meta && str !== void 0 && str.length > 0) {
6936
+ const printable = stripNonPrintable(str);
6937
+ if (printable.length > 0) {
6938
+ errorMessage = "";
6939
+ const chars = [...buffer];
6940
+ const insertedChars = [...printable];
6941
+ chars.splice(cursor, 0, ...insertedChars);
6942
+ buffer = chars.join("");
6943
+ cursor += insertedChars.length;
6944
+ refreshSuggestions(true);
6945
+ renderState("active");
6946
+ }
6947
+ }
6948
+ };
6949
+ rl.prompt();
6950
+ output.write(`${pc.gray(S_BAR)}\n${CURSOR_HIDE}`);
6951
+ input.on("keypress", onKeypress);
6952
+ output.on("resize", onResize);
6953
+ process.on("exit", onExit);
6954
+ rawInputSetMode(true);
6955
+ renderState("active");
6956
+ });
6957
+ }
6384
6958
  // src/interactive.ts
6385
6959
  var WizardCancelledError = class extends Error {
6386
6960
  constructor() {
@@ -6389,7 +6963,7 @@ var WizardCancelledError = class extends Error {
6389
6963
  }
6390
6964
  };
6391
6965
  function unwrapPrompt(value) {
6392
- if (isCancel(value)) {
6966
+ if (isCancel(value) || isDirectoryPromptCancel(value)) {
6393
6967
  cancel("Operation cancelled.");
6394
6968
  throw new WizardCancelledError();
6395
6969
  }
@@ -6717,11 +7291,16 @@ async function runInteractiveWizard() {
6717
7291
  label: "Merged (single EPUB for all selected volumes)"
6718
7292
  }]
6719
7293
  }));
6720
- const outputDir = unwrapPrompt(await text({
6721
- message: "Output directory:",
7294
+ const outputDir = unwrapPrompt(await promptDirectory({
7295
+ message: `Base output directory (subdir: ${sanitizeFilename(novel.title)}):`,
6722
7296
  initialValue: config.outputDir,
6723
- defaultValue: config.outputDir,
6724
- validate: (value) => value?.trim() ? void 0 : "Output directory cannot be empty"
7297
+ placeholder: ".",
7298
+ preview: (value) => {
7299
+ const trimmed = value.trim();
7300
+ if (!trimmed) return;
7301
+ return resolveExportTargetDir(trimmed, novel.title, true);
7302
+ },
7303
+ validate: (value) => value.trim() ? void 0 : "Output directory cannot be empty"
6725
7304
  })).trim();
6726
7305
  const illustrations = unwrapPrompt(await confirm({
6727
7306
  message: "Download and embed chapter illustrations?",
@@ -6746,6 +7325,7 @@ async function runInteractiveWizard() {
6746
7325
  source,
6747
7326
  token,
6748
7327
  outputDir,
7328
+ subdir: true,
6749
7329
  mode,
6750
7330
  volumes: selectedVolumeIndices.join(","),
6751
7331
  illustrations,