micloud-cli 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.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/README.en.md +118 -0
  3. package/README.md +117 -2
  4. package/dist/cli.js +59 -0
  5. package/dist/commands/account.js +76 -0
  6. package/dist/core/account.js +22 -0
  7. package/dist/core/auth.js +338 -0
  8. package/dist/core/config.js +75 -0
  9. package/dist/core/http.js +172 -0
  10. package/dist/core/lock.js +90 -0
  11. package/dist/core/output.js +137 -0
  12. package/dist/core/template.js +39 -0
  13. package/dist/core/utils.js +205 -0
  14. package/dist/note/client.js +298 -0
  15. package/dist/note/commands/create.js +44 -0
  16. package/dist/note/commands/delete.js +32 -0
  17. package/dist/note/commands/export.js +20 -0
  18. package/dist/note/commands/folder.js +101 -0
  19. package/dist/note/commands/get.js +35 -0
  20. package/dist/note/commands/list.js +57 -0
  21. package/dist/note/commands/move.js +37 -0
  22. package/dist/note/commands/pin.js +41 -0
  23. package/dist/note/commands/search.js +45 -0
  24. package/dist/note/commands/shared.js +37 -0
  25. package/dist/note/commands/sync.js +203 -0
  26. package/dist/note/commands/update.js +61 -0
  27. package/dist/note/commands/upload-image.js +27 -0
  28. package/dist/note/config.js +157 -0
  29. package/dist/note/converter.js +664 -0
  30. package/dist/note/extra-info.js +23 -0
  31. package/dist/note/images.js +100 -0
  32. package/dist/note/register.js +172 -0
  33. package/dist/note/sync-diff.js +143 -0
  34. package/dist/note/sync.js +744 -0
  35. package/dist/note/text-diff.js +71 -0
  36. package/dist/note/types.js +2 -0
  37. package/dist/recording/client.js +115 -0
  38. package/dist/recording/commands/config.js +73 -0
  39. package/dist/recording/commands/delete.js +171 -0
  40. package/dist/recording/commands/list.js +161 -0
  41. package/dist/recording/commands/shared.js +47 -0
  42. package/dist/recording/commands/transfer.js +192 -0
  43. package/dist/recording/commands/trash.js +140 -0
  44. package/dist/recording/config.js +104 -0
  45. package/dist/recording/dates.js +61 -0
  46. package/dist/recording/download.js +308 -0
  47. package/dist/recording/progress.js +77 -0
  48. package/dist/recording/pull.js +433 -0
  49. package/dist/recording/recording.js +294 -0
  50. package/dist/recording/register.js +202 -0
  51. package/dist/recording/template.js +44 -0
  52. package/dist/recording/types.js +2 -0
  53. package/package.json +53 -4
@@ -0,0 +1,192 @@
1
+ import { getClient, resolveTransferSettings, showProgress, buildFilter, DEVICE_SYNC_WARNING } from "./shared.js";
2
+ import { resolveOutputDir } from "../config.js";
3
+ import { downloadToStream, urlExpiresAt } from "../download.js";
4
+ import { downloadRecordings, listCloud, pullRecordings, resolveIds } from "../pull.js";
5
+ import { success, logInfo, fail, isJsonMode, confirmDestructive, canPrompt, finishBatch } from "../../core/output.js";
6
+ import { formatBytes, formatDuration, formatTime, parsePositiveInt } from "../../core/utils.js";
7
+ /** pull:增量拉取云端录音到本地目录 */
8
+ export async function pullCommand(opts) {
9
+ try {
10
+ const filter = buildFilter(opts);
11
+ const limit = opts.limit !== undefined ? parsePositiveInt(opts.limit, Infinity, "--limit") : undefined;
12
+ const outputDir = await resolveOutputDir(opts.output);
13
+ const { template, concurrency } = await resolveTransferSettings(opts);
14
+ if (opts.allowMoved && !opts.deleteCloud)
15
+ throw new Error("--allow-moved 只能与 --delete-cloud 一起使用");
16
+ if (opts.deleteCloud && !opts.dryRun && !opts.yes && !canPrompt()) {
17
+ throw new Error("--delete-cloud 会删除云端录音,非交互模式(--json / 无终端)下需同时加 -y 明确确认");
18
+ }
19
+ const client = await getClient();
20
+ const quiet = isJsonMode();
21
+ const result = await pullRecordings(client, {
22
+ outputDir,
23
+ template,
24
+ concurrency,
25
+ filter,
26
+ limit,
27
+ force: opts.force,
28
+ dryRun: opts.dryRun,
29
+ deleteCloud: opts.deleteCloud,
30
+ allowMoved: opts.allowMoved,
31
+ confirmDelete: async (count) => {
32
+ if (!quiet)
33
+ logInfo(`⚠️ 拉取并校验成功后,将把 ${count} 条云端录音移到回收站。${DEVICE_SYNC_WARNING}`);
34
+ return await confirmDestructive("确认继续吗?", opts.yes);
35
+ },
36
+ quiet,
37
+ showProgress: showProgress(),
38
+ });
39
+ const failures = [...result.failed, ...result.deleteFailed];
40
+ const succeeded = result.pulled.length + result.deletedFromCloud.length;
41
+ finishBatch(result, { succeeded, failed: failures, warnings: result.warnings.length }, () => {
42
+ if (result.cancelled) {
43
+ logInfo("已取消");
44
+ return;
45
+ }
46
+ const printSkipped = () => {
47
+ if (result.deleteSkipped.length === 0)
48
+ return;
49
+ logInfo(`ℹ️ ${result.deleteSkipped.length} 条录音未删除云端:`);
50
+ for (const s of result.deleteSkipped.slice(0, 20))
51
+ logInfo(` ${s.title}:${s.reason}`);
52
+ if (result.deleteSkipped.length > 20)
53
+ logInfo(` ……其余 ${result.deleteSkipped.length - 20} 条略(--json 查看全部)`);
54
+ };
55
+ if (result.dryRun) {
56
+ logInfo(`🔍 预览(未下载任何文件):将拉取 ${result.pulled.length} 条,已拉取过 ${result.alreadyPulled} 条 → ${outputDir}`);
57
+ for (const item of result.pulled) {
58
+ const tag = item.existing ? "(本地已有相同文件)" : "";
59
+ process.stdout.write(` ${formatTime(item.recordedAt)} ${formatDuration(item.duration).padStart(8)} ${formatBytes(item.size).padStart(9)} ${item.relativePath}${tag}\n`);
60
+ }
61
+ if (opts.deleteCloud) {
62
+ logInfo(`将把 ${result.deletedFromCloud.length} 条云端录音移到回收站`);
63
+ printSkipped();
64
+ }
65
+ for (const f of result.failed)
66
+ logInfo(`❌ ${f.title || f.id}:${f.error}`);
67
+ return;
68
+ }
69
+ printSkipped();
70
+ for (const w of result.warnings)
71
+ logInfo(`⚠️ ${w}`);
72
+ const parts = [`拉取 ${result.pulled.length} 条(下载 ${formatBytes(result.downloadedBytes)})`, `已拉取过 ${result.alreadyPulled} 条`];
73
+ if (result.failed.length)
74
+ parts.push(`失败 ${result.failed.length} 条`);
75
+ if (opts.deleteCloud)
76
+ parts.push(`云端移到回收站 ${result.deletedFromCloud.length} 条`);
77
+ if (result.deleteFailed.length)
78
+ parts.push(`云端删除失败 ${result.deleteFailed.length} 条`);
79
+ const problem = result.failed.length || result.deleteFailed.length || result.warnings.length;
80
+ logInfo(`\n${problem ? "⚠️" : "🎉"} 完成:${parts.join(",")}`);
81
+ });
82
+ }
83
+ catch (err) {
84
+ fail(err);
85
+ }
86
+ }
87
+ /** download:按 id 下载指定录音(不记录拉取状态) */
88
+ export async function downloadCommand(ids, opts) {
89
+ try {
90
+ if (opts.stdout) {
91
+ await downloadToStdout(ids);
92
+ return;
93
+ }
94
+ const outputDir = opts.output ? (await resolveOutputDir(opts.output)) : process.cwd();
95
+ const { template, concurrency } = await resolveTransferSettings(opts);
96
+ const client = await getClient();
97
+ const result = await downloadRecordings(client, ids, {
98
+ outputDir,
99
+ template,
100
+ concurrency,
101
+ quiet: isJsonMode(),
102
+ showProgress: showProgress(),
103
+ });
104
+ finishBatch(result, { succeeded: result.downloaded.length, failed: result.failed }, () => {
105
+ logInfo(`\n完成:下载 ${result.downloaded.length} 条(${formatBytes(result.downloadedBytes)})${result.failed.length ? `,失败 ${result.failed.length} 条` : ""}`);
106
+ });
107
+ }
108
+ catch (err) {
109
+ fail(err);
110
+ }
111
+ }
112
+ /** 把单条录音写到 stdout(便于管道交给转写等工具);先下载校验,通过后才输出 */
113
+ async function downloadToStdout(ids) {
114
+ if (ids.length !== 1)
115
+ throw new Error("--stdout 一次只能输出一条录音");
116
+ if (isJsonMode())
117
+ throw new Error("--stdout 输出的是音频二进制,不能与 --json 同时使用");
118
+ if (process.stdout.isTTY)
119
+ throw new Error("--stdout 会输出音频二进制,请重定向到文件或管道(如 `> a.mp3` / `| ffmpeg -i - ...`)");
120
+ const client = await getClient();
121
+ const all = await listCloud(client, true);
122
+ const { found, failures } = await resolveIds(client, all, ids);
123
+ if (failures.length > 0)
124
+ throw new Error(failures[0].error);
125
+ await downloadToStream(client, found[0], process.stdout);
126
+ }
127
+ /** url:获取录音的临时直链(可直接在浏览器 / 播放器 / 下载工具中使用) */
128
+ export async function urlCommand(ids, _opts = {}) {
129
+ try {
130
+ const client = await getClient();
131
+ const all = await listCloud(client, true);
132
+ const { found, failures } = await resolveIds(client, all, ids);
133
+ const items = [];
134
+ for (const r of found) {
135
+ const url = await client.getDownloadUrl(r.id);
136
+ const expiresAt = urlExpiresAt(url);
137
+ items.push({ id: r.id, title: r.title, url, ...(expiresAt ? { expiresAt } : {}) });
138
+ }
139
+ finishBatch({ items, failed: failures }, { succeeded: items.length, failed: failures }, () => {
140
+ for (const item of items) {
141
+ if (items.length > 1)
142
+ logInfo(`# ${item.title}`);
143
+ process.stdout.write(item.url + "\n");
144
+ }
145
+ if (items.length > 0) {
146
+ const expiresAt = items[0].expiresAt;
147
+ logInfo(`直链无需登录即可访问${expiresAt ? `,约 ${formatTime(expiresAt)} 前有效` : ",有效期有限"},请勿公开分享`);
148
+ }
149
+ for (const f of failures)
150
+ logInfo(`❌ ${f.id}:${f.error}`);
151
+ });
152
+ }
153
+ catch (err) {
154
+ fail(err);
155
+ }
156
+ }
157
+ /** play:用系统默认播放器(或浏览器)打开录音直链 */
158
+ export async function playCommand(id) {
159
+ try {
160
+ const client = await getClient();
161
+ const all = await listCloud(client, true);
162
+ const { found, failures } = await resolveIds(client, all, [id]);
163
+ if (failures.length > 0)
164
+ throw new Error(failures[0].error);
165
+ const r = found[0];
166
+ const url = await client.getDownloadUrl(r.id);
167
+ await openExternal(url);
168
+ success({ id: r.id, title: r.title, url }, () => {
169
+ logInfo(`▶️ 已在默认播放器 / 浏览器中打开:${r.title}(${formatDuration(r.duration)})`);
170
+ });
171
+ }
172
+ catch (err) {
173
+ fail(err);
174
+ }
175
+ }
176
+ async function openExternal(url) {
177
+ const { spawn } = await import("node:child_process");
178
+ // Windows 不经过 cmd:直链里的 & 会被 cmd 当成命令分隔符
179
+ const [command, args] = process.platform === "darwin"
180
+ ? ["open", [url]]
181
+ : process.platform === "win32"
182
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
183
+ : ["xdg-open", [url]];
184
+ await new Promise((resolve, reject) => {
185
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
186
+ child.once("error", (err) => reject(new Error(`无法打开播放器:${err.message}`)));
187
+ child.once("spawn", () => {
188
+ child.unref();
189
+ resolve();
190
+ });
191
+ });
192
+ }
@@ -0,0 +1,140 @@
1
+ import { getClient } from "./shared.js";
2
+ import { summarize } from "./list.js";
3
+ import { TRASH_RETENTION_DAYS } from "../../core/account.js";
4
+ import { MiApiError, isFatalError } from "../../core/http.js";
5
+ import { success, logInfo, fail, isJsonMode, confirmDestructive, finishBatch } from "../../core/output.js";
6
+ import { formatBytes, formatDuration, formatTime, padEndDisplay, padStartDisplay, randomDelay, truncateDisplay, } from "../../core/utils.js";
7
+ import { CODE_SPACE_FULL } from "../client.js";
8
+ import { errorMessage } from "../pull.js";
9
+ import { parseTrashedRecording, shortTypeName } from "../recording.js";
10
+ /** 回收站列表(按删除时间倒序),附带按会员等级推算的自动清除时间 */
11
+ async function loadTrash(client) {
12
+ const [raws, quota] = await Promise.all([client.listTrash(), client.getQuota().catch(() => undefined)]);
13
+ const retention = quota?.level ? TRASH_RETENTION_DAYS[quota.level] : undefined;
14
+ return raws
15
+ .map((raw) => parseTrashedRecording(raw, retention))
16
+ .sort((a, b) => b.deletedAt - a.deletedAt || a.id.localeCompare(b.id));
17
+ }
18
+ /** trash list:查看回收站(最近删除) */
19
+ export async function trashListCommand() {
20
+ try {
21
+ const client = await getClient();
22
+ const items = await loadTrash(client);
23
+ success(items, () => {
24
+ if (items.length === 0) {
25
+ logInfo("(回收站为空)");
26
+ return;
27
+ }
28
+ for (const r of items) {
29
+ const cells = [
30
+ r.id.padEnd(17),
31
+ `删除于 ${formatTime(r.deletedAt)}`,
32
+ padStartDisplay(formatDuration(r.duration), 8),
33
+ padStartDisplay(formatBytes(r.size), 9),
34
+ padEndDisplay(shortTypeName(r), 8),
35
+ truncateDisplay(r.title, 48),
36
+ ];
37
+ process.stdout.write(cells.join(" ") + "\n");
38
+ }
39
+ const total = summarize(items);
40
+ const expiry = items[0].expiresAt ? `;删除超过保留期限的录音会被自动清除` : "";
41
+ logInfo(`\n共 ${items.length} 条,${formatDuration(total.duration)},${formatBytes(total.size)}${expiry}`);
42
+ });
43
+ }
44
+ catch (err) {
45
+ fail(err);
46
+ }
47
+ }
48
+ /** trash restore:从回收站恢复录音 */
49
+ export async function trashRestoreCommand(ids, opts) {
50
+ await trashAction("restore", ids, opts);
51
+ }
52
+ /** trash purge:从回收站永久删除录音(不可恢复) */
53
+ export async function trashPurgeCommand(ids, opts) {
54
+ await trashAction("purge", ids, opts);
55
+ }
56
+ async function trashAction(action, ids, opts) {
57
+ try {
58
+ if (ids.length > 0 && opts.all)
59
+ throw new Error("指定 id 时不能再加 --all");
60
+ if (ids.length === 0 && !opts.all)
61
+ throw new Error("请指定回收站里录音的 id,或用 --all 表示全部");
62
+ const client = await getClient();
63
+ const trash = await loadTrash(client);
64
+ const { targets, missing } = selectTrashTargets(trash, ids, !!opts.all);
65
+ const failed = missing.map((id) => ({ id, title: "", error: "回收站里没有这条录音" }));
66
+ const verb = action === "restore" ? "恢复" : "永久删除";
67
+ if (targets.length === 0) {
68
+ finishBatch({ [action === "restore" ? "restored" : "purged"]: [], failed, count: 0 }, { succeeded: 0, failed }, () => {
69
+ logInfo(opts.all ? "(回收站为空)" : "(没有可操作的录音)");
70
+ for (const f of failed)
71
+ logInfo(`❌ ${f.id}:${f.error}`);
72
+ });
73
+ return;
74
+ }
75
+ if (action === "purge") {
76
+ if (!isJsonMode()) {
77
+ logInfo(`将永久删除以下 ${targets.length} 条录音,删除后无法恢复:`);
78
+ for (const r of targets.slice(0, 20))
79
+ logInfo(` [${r.id}] ${r.title}`);
80
+ if (targets.length > 20)
81
+ logInfo(` ……其余 ${targets.length - 20} 条略`);
82
+ }
83
+ if (!(await confirmDestructive(`确认永久删除这 ${targets.length} 条录音吗?`, opts.yes))) {
84
+ success({ cancelled: true }, () => logInfo("已取消"));
85
+ return;
86
+ }
87
+ }
88
+ const done = [];
89
+ let fatal = null;
90
+ for (const r of targets) {
91
+ if (fatal) {
92
+ failed.push({ id: r.id, title: r.title, error: fatal });
93
+ continue;
94
+ }
95
+ try {
96
+ if (action === "restore")
97
+ await client.recoverRecording(r.id, r.ver);
98
+ else
99
+ await client.purgeRecording(r.id, r.ver);
100
+ done.push(r);
101
+ if (!isJsonMode())
102
+ logInfo(`${action === "restore" ? "♻️ " : "🔥"} ${r.title}`);
103
+ }
104
+ catch (err) {
105
+ const message = errorMessage(err);
106
+ failed.push({ id: r.id, title: r.title, error: message });
107
+ if (!isJsonMode())
108
+ logInfo(`❌ ${r.title}:${message}`);
109
+ // 空间已满时后续恢复必然失败;登录失效时后续请求都会失败
110
+ if (isFatalError(err) || (err instanceof MiApiError && err.code === CODE_SPACE_FULL))
111
+ fatal = message;
112
+ }
113
+ if (targets.length > 1)
114
+ await randomDelay(150);
115
+ }
116
+ const key = action === "restore" ? "restored" : "purged";
117
+ finishBatch({ [key]: done, failed, count: done.length }, { succeeded: done.length, failed }, () => {
118
+ logInfo(`\n已${verb} ${done.length} 条录音${failed.length ? `,${failed.length} 条失败` : ""}`);
119
+ });
120
+ }
121
+ catch (err) {
122
+ fail(err);
123
+ }
124
+ }
125
+ /** 从回收站里挑出目标;ver 必须用回收站条目当前的值(删除时 ver 会变) */
126
+ export function selectTrashTargets(trash, ids, all) {
127
+ if (all)
128
+ return { targets: trash, missing: [] };
129
+ const byId = new Map(trash.map((r) => [r.id, r]));
130
+ const targets = [];
131
+ const missing = [];
132
+ for (const id of new Set(ids.map((s) => s.trim()).filter(Boolean))) {
133
+ const r = byId.get(id);
134
+ if (r)
135
+ targets.push(r);
136
+ else
137
+ missing.push(id);
138
+ }
139
+ return { targets, missing };
140
+ }
@@ -0,0 +1,104 @@
1
+ import { readFile, rm } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { loadSection, resolveOutputPath, saveSection } from "../core/config.js";
4
+ import { lockDir } from "../core/lock.js";
5
+ import { fileExists, writeFileAtomic } from "../core/utils.js";
6
+ /**
7
+ * 两类元数据按位置与归属拆分:
8
+ *
9
+ * - 配置:项目配置 `.micloud/config.json` 的 `recording` 节(手写或 `recording config set`)
10
+ * - 拉取状态:`<拉取目录>/.micloud-recording.json`(自动生成、跟拉取目录 1:1 绑定)
11
+ */
12
+ const STATE_FILENAME = ".micloud-recording.json";
13
+ /** 合并前的独立录音工具写的状态文件,读取时兼容 */
14
+ const LEGACY_STATE_FILENAME = ".mi-recording-cli.state.json";
15
+ export const DEFAULT_CONCURRENCY = 3;
16
+ export const MAX_CONCURRENCY = 8;
17
+ export const CONFIG_KEYS = ["output", "fileNameTemplate", "concurrency"];
18
+ // ============ 配置 ============
19
+ /** 读取录音配置;字段类型不对的忽略(消费者用 `??` 回落默认值) */
20
+ export async function loadRecordingConfig() {
21
+ const raw = await loadSection("recording");
22
+ const cfg = {};
23
+ if (typeof raw.output === "string" && raw.output.trim())
24
+ cfg.output = raw.output;
25
+ if (typeof raw.fileNameTemplate === "string" && raw.fileNameTemplate.trim())
26
+ cfg.fileNameTemplate = raw.fileNameTemplate;
27
+ if (typeof raw.concurrency === "number")
28
+ cfg.concurrency = raw.concurrency;
29
+ return cfg;
30
+ }
31
+ export async function saveRecordingConfig(cfg) {
32
+ await saveSection("recording", { ...cfg });
33
+ }
34
+ /** 校验并转换 `config set` 的值 */
35
+ export function parseConfigValue(key, raw) {
36
+ switch (key) {
37
+ case "concurrency":
38
+ return parseConcurrency(raw);
39
+ case "output":
40
+ case "fileNameTemplate":
41
+ if (!raw.trim())
42
+ throw new Error(`${key} 不能为空`);
43
+ return raw;
44
+ }
45
+ }
46
+ /** 并发数:1 ~ MAX_CONCURRENCY 的整数 */
47
+ export function parseConcurrency(raw) {
48
+ const n = Number(raw);
49
+ if (!Number.isInteger(n) || n < 1 || n > MAX_CONCURRENCY) {
50
+ throw new Error(`并发数必须是 1 ~ ${MAX_CONCURRENCY} 的整数,收到:${raw}`);
51
+ }
52
+ return n;
53
+ }
54
+ /**
55
+ * 解析生效的拉取目录(绝对路径)。
56
+ * 优先级:命令行 `-o`(相对当前目录)> 配置 output(相对项目根)> `<项目根>/.micloud/recording/`
57
+ */
58
+ export async function resolveOutputDir(cliOutput) {
59
+ return resolveOutputPath("recording", cliOutput, cliOutput ? undefined : (await loadRecordingConfig()).output);
60
+ }
61
+ // ============ 拉取状态 ============
62
+ /** 拉取目录内的状态文件路径 */
63
+ export function getStatePath(outputDir) {
64
+ return join(outputDir, STATE_FILENAME);
65
+ }
66
+ function emptyState() {
67
+ return { version: 1, recordings: {} };
68
+ }
69
+ /** 拉取目录里是否有拉取记录(含合并前的旧状态文件) */
70
+ export async function hasState(outputDir) {
71
+ return (await fileExists(getStatePath(outputDir))) || (await fileExists(join(outputDir, LEGACY_STATE_FILENAME)));
72
+ }
73
+ /**
74
+ * 读取拉取目录内的状态;不存在时返回空壳,损坏时报错(避免把已拉取的录音当成新的重复下载)。
75
+ * 只有旧状态文件时读取它,下次保存写到新文件名。
76
+ */
77
+ export async function loadState(outputDir) {
78
+ let file = getStatePath(outputDir);
79
+ if (!(await fileExists(file))) {
80
+ file = join(outputDir, LEGACY_STATE_FILENAME);
81
+ if (!(await fileExists(file)))
82
+ return emptyState();
83
+ }
84
+ const raw = await readFile(file, "utf-8");
85
+ try {
86
+ const parsed = JSON.parse(raw);
87
+ return { version: 1, recordings: parsed.recordings ?? {} };
88
+ }
89
+ catch {
90
+ throw new Error(`拉取状态文件已损坏:${file}。请修复或删除后重试(删除后已拉取的录音会按同名文件重新认领)`);
91
+ }
92
+ }
93
+ /** 原子写回拉取状态(先写临时文件再改名,进程中断也不会留下半截 JSON);写成功后移除合并前的旧状态文件 */
94
+ export async function saveState(outputDir, state) {
95
+ await writeFileAtomic(getStatePath(outputDir), JSON.stringify(state, null, 2) + "\n");
96
+ await rm(join(outputDir, LEGACY_STATE_FILENAME), { force: true });
97
+ }
98
+ /**
99
+ * 独占拉取目录:同一目录同时只允许一个会写入它的命令(pull / download / delete --pulled)运行。
100
+ * 返回释放函数。
101
+ */
102
+ export async function lockOutputDir(outputDir) {
103
+ return await lockDir(outputDir);
104
+ }
@@ -0,0 +1,61 @@
1
+ const UNIT_MS = {
2
+ s: 1000,
3
+ m: 60_000,
4
+ h: 3_600_000,
5
+ d: 86_400_000,
6
+ w: 604_800_000,
7
+ };
8
+ /**
9
+ * 解析时间参数(--since / --until 等),返回毫秒时间戳:
10
+ * - 相对时间:`30m` `12h` `7d` `2w`(距今)
11
+ * - `today` / `yesterday`
12
+ * - 日期:`2026-07-01`、`2026/7/1`、`20260701`
13
+ * - 日期时间:`2026-07-01 18:30`、`2026-07-01T18:30:05`(本地时间),或带时区的 ISO 字符串
14
+ * - Unix 时间戳:13 位毫秒 / 10 位秒
15
+ *
16
+ * endOfDay:只给到日期(含 today / yesterday)时取当天 23:59:59.999,用于 --until 包含整天。
17
+ */
18
+ export function parseTimeInput(raw, opts = {}) {
19
+ const text = raw.trim();
20
+ const now = opts.now ?? Date.now();
21
+ const lower = text.toLowerCase();
22
+ const relative = lower.match(/^(\d+)\s*([smhdw])$/);
23
+ if (relative)
24
+ return now - Number(relative[1]) * UNIT_MS[relative[2]];
25
+ if (lower === "today" || lower === "yesterday") {
26
+ const d = new Date(now);
27
+ if (lower === "yesterday")
28
+ d.setDate(d.getDate() - 1);
29
+ return dayBoundary(d.getFullYear(), d.getMonth() + 1, d.getDate(), opts.endOfDay);
30
+ }
31
+ if (/^\d{13}$/.test(text))
32
+ return Number(text);
33
+ if (/^\d{10}$/.test(text))
34
+ return Number(text) * 1000;
35
+ const compact = text.match(/^(\d{4})(\d{2})(\d{2})$/);
36
+ if (compact) {
37
+ return checked(dayBoundary(Number(compact[1]), Number(compact[2]), Number(compact[3]), opts.endOfDay), raw);
38
+ }
39
+ const local = text.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/);
40
+ if (local) {
41
+ const [y, mo, d] = [Number(local[1]), Number(local[2]), Number(local[3])];
42
+ if (local[4] === undefined)
43
+ return checked(dayBoundary(y, mo, d, opts.endOfDay), raw);
44
+ const date = new Date(y, mo - 1, d, Number(local[4]), Number(local[5]), Number(local[6] ?? 0));
45
+ return checked(sameDay(date, y, mo, d) ? date.getTime() : NaN, raw);
46
+ }
47
+ return checked(Date.parse(text), raw);
48
+ }
49
+ function dayBoundary(y, mo, d, endOfDay) {
50
+ const date = endOfDay ? new Date(y, mo - 1, d, 23, 59, 59, 999) : new Date(y, mo - 1, d);
51
+ return sameDay(date, y, mo, d) ? date.getTime() : NaN;
52
+ }
53
+ function sameDay(date, y, mo, d) {
54
+ return date.getFullYear() === y && date.getMonth() === mo - 1 && date.getDate() === d;
55
+ }
56
+ function checked(ts, raw) {
57
+ if (!Number.isFinite(ts)) {
58
+ throw new Error(`无法识别的时间:${raw}(支持 2026-07-01、2026-07-01 18:30、7d / 12h、today 等)`);
59
+ }
60
+ return ts;
61
+ }