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,61 @@
1
+ import { getClient, resolveContent, contentBaseDir } from "./shared.js";
2
+ import { markdownToXml, extractSnippet, parseNoteEntry, buildImageMap, } from "../converter.js";
3
+ import { uploadLocalImages, withAttachments } from "../images.js";
4
+ import { buildExtraInfoString } from "../extra-info.js";
5
+ import { success, logInfo, fail } from "../../core/output.js";
6
+ /**
7
+ * 更新笔记。先 GET 拿到最新 tag(乐观锁),改字段后再提交。
8
+ * 若未提供新内容,则保留原内容(仅改 title/folder/color 等元数据)。
9
+ */
10
+ export async function updateCommand(id, opts) {
11
+ try {
12
+ let colorOverride;
13
+ if (opts.color !== undefined) {
14
+ colorOverride = parseInt(opts.color, 10);
15
+ if (Number.isNaN(colorOverride)) {
16
+ throw new Error(`--color 必须是数字,收到:${opts.color}`);
17
+ }
18
+ }
19
+ const client = await getClient();
20
+ const current = await client.getNote(id);
21
+ const newContent = await resolveContent(opts);
22
+ let xmlContent = current.content ?? "";
23
+ let setting = current.setting ?? { themeId: 0, stickyTime: 0, version: 0 };
24
+ if (newContent !== null) {
25
+ // get / sync 写出的附件引用按当前笔记附件还原,内容可原样 get → 改 → update;新的本地图片自动上传
26
+ const known = buildImageMap(parseNoteEntry(current).files, "assets/", "../assets/");
27
+ const { imageMap, uploaded } = await uploadLocalImages(client, newContent, known, [contentBaseDir(opts)]);
28
+ xmlContent = markdownToXml(newContent, imageMap);
29
+ setting = withAttachments(setting, uploaded);
30
+ }
31
+ const now = Date.now();
32
+ const entry = {
33
+ id: String(current.id),
34
+ tag: current.tag,
35
+ status: current.status,
36
+ createDate: current.createDate ?? now,
37
+ modifyDate: now,
38
+ colorId: colorOverride ?? current.colorId ?? 0,
39
+ content: xmlContent,
40
+ setting,
41
+ folderId: opts.folder ?? String(current.folderId ?? "0"),
42
+ alertDate: current.alertDate ?? 0,
43
+ extraInfo: buildExtraInfoString(opts.title, normalizeExtraInfo(current.extraInfo)),
44
+ subject: current.subject,
45
+ snippet: extractSnippet(xmlContent),
46
+ };
47
+ await client.updateNote(id, entry);
48
+ success({ id, updated: true }, () => {
49
+ logInfo(`✅ 笔记 ${id} 更新完成`);
50
+ });
51
+ }
52
+ catch (err) {
53
+ fail(err);
54
+ }
55
+ }
56
+ /** extraInfo 可能是 string 或对象,统一为 string 传给 buildExtraInfoString */
57
+ function normalizeExtraInfo(raw) {
58
+ if (raw === undefined)
59
+ return undefined;
60
+ return typeof raw === "string" ? raw : JSON.stringify(raw);
61
+ }
@@ -0,0 +1,27 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename } from "node:path";
3
+ import { getClient } from "./shared.js";
4
+ import { inferImageMimeType } from "../images.js";
5
+ import { success, logInfo, fail } from "../../core/output.js";
6
+ /** 上传图片,返回可嵌入笔记的 fileId 与 Markdown 引用 */
7
+ export async function uploadImageCommand(path, opts) {
8
+ try {
9
+ const buffer = await readFile(path);
10
+ const filename = opts.filename ?? basename(path);
11
+ const mimeType = opts.mime ?? inferImageMimeType(filename);
12
+ const client = await getClient();
13
+ const { fileId, digest } = await client.uploadImage(new Uint8Array(buffer), {
14
+ filename,
15
+ mimeType,
16
+ });
17
+ const markdown = `![图片](minote://image/${fileId})`;
18
+ success({ fileId, digest, markdown }, () => {
19
+ logInfo(`✅ 上传成功:fileId=${fileId}`);
20
+ process.stdout.write(`${markdown}\n`);
21
+ logInfo("提示:把上面的 Markdown 放进 create/update 的内容里,即可在笔记中引用该图片。");
22
+ });
23
+ }
24
+ catch (err) {
25
+ fail(err);
26
+ }
27
+ }
@@ -0,0 +1,157 @@
1
+ import { readFile, rm } from "node:fs/promises";
2
+ import { join, resolve, relative, isAbsolute } from "node:path";
3
+ import { getConfigPath, getDefaultOutputDir as coreDefaultOutputDir, getProjectRoot, loadSection, resolveOutputPath, saveSection, } from "../core/config.js";
4
+ import { logInfo } from "../core/output.js";
5
+ import { fileExists, writeFileAtomic } from "../core/utils.js";
6
+ /**
7
+ * 两类元数据按位置与归属拆分:
8
+ *
9
+ * - 笔记配置:项目配置 `.micloud/config.json` 的 `note` 节(手写、可入版控、可团队共享)
10
+ * - 同步状态:`<outputDir>/.micloud-note.state.json`(自动生成、跟 output 1:1 绑定)
11
+ *
12
+ * 兼容旧版(mi-note-cli):没有 `note` 节时读 `.mi-note-cli/config.json`;
13
+ * 没有新状态文件时读 `.mi-note-cli.state.json`(保存时改用新文件名并移除旧文件);
14
+ * 既没传 `-o` 也没配 output 时,若旧的默认目录 `.mi-note-cli/output/` 存在则继续用它。
15
+ */
16
+ const STATE_FILENAME = ".micloud-note.state.json";
17
+ const LEGACY_STATE_FILENAME = ".mi-note-cli.state.json";
18
+ const LEGACY_CONFIG = join(".mi-note-cli", "config.json");
19
+ const LEGACY_DEFAULT_OUTPUT = join(".mi-note-cli", "output");
20
+ const DEFAULT_SYNC_MODE = "manual";
21
+ export { getProjectRoot };
22
+ // ============================================================
23
+ // 路径解析
24
+ // ============================================================
25
+ /** 配置文件绝对路径:`<root>/.micloud/config.json` */
26
+ export function getUserConfigPath() {
27
+ return getConfigPath();
28
+ }
29
+ /** 默认 output 目录绝对路径:`<root>/.micloud/note/` */
30
+ export function getDefaultOutputDir() {
31
+ return coreDefaultOutputDir("note");
32
+ }
33
+ /** 给定 output 目录,返回其内的 state 文件绝对路径 */
34
+ export function getStatePath(outputDir) {
35
+ return join(outputDir, STATE_FILENAME);
36
+ }
37
+ /** 绝对路径 → 相对 output(用于写入 state.notes[].filePath) */
38
+ export function toOutputRel(absPath, outputDir) {
39
+ return relative(outputDir, absPath);
40
+ }
41
+ /** 相对 output 的路径 → 绝对路径(用于实际文件读写) */
42
+ export function toOutputAbs(relPath, outputDir) {
43
+ return isAbsolute(relPath) ? relPath : resolve(outputDir, relPath);
44
+ }
45
+ // ============================================================
46
+ // 笔记配置(UserConfig)
47
+ // ============================================================
48
+ /**
49
+ * 读取笔记配置(不存在则返回空壳)。
50
+ *
51
+ * 回落形态:返回 `{}`(全字段 undefined)。消费者通过 `??` 链回落到默认值;
52
+ * 显式 syncMode/output/fileNameTemplate 白名单也防止无关字段误漂进 UserConfig。
53
+ * 与 `loadState` 的容错风格刻意不同:state 由工具自动写入,schema 漂移可控。
54
+ */
55
+ export async function loadUserConfig() {
56
+ const raw = await loadSection("note");
57
+ return {
58
+ syncMode: typeof raw.syncMode === "string" ? raw.syncMode : undefined,
59
+ output: typeof raw.output === "string" ? raw.output : undefined,
60
+ fileNameTemplate: typeof raw.fileNameTemplate === "string" ? raw.fileNameTemplate : undefined,
61
+ };
62
+ }
63
+ /** 写入笔记配置(其他服务的配置原样保留);旧版配置文件从此不再使用,提示可删除 */
64
+ export async function saveUserConfig(cfg) {
65
+ const section = {};
66
+ for (const [key, value] of Object.entries(cfg)) {
67
+ if (value !== undefined)
68
+ section[key] = value;
69
+ }
70
+ await saveSection("note", section);
71
+ const legacy = join(getProjectRoot(), LEGACY_CONFIG);
72
+ if (await fileExists(legacy)) {
73
+ logInfo(`ℹ️ 笔记配置已写入 ${getConfigPath()},旧的 ${legacy} 不再使用,可删除`);
74
+ }
75
+ }
76
+ // ============================================================
77
+ // 同步状态(SyncState)
78
+ // ============================================================
79
+ function emptyState() {
80
+ return { lastSync: null, notes: {}, folders: {} };
81
+ }
82
+ /**
83
+ * 读取指定 output 内的同步状态;不存在或解析失败时返回空壳。
84
+ *
85
+ * 回落形态与 `loadUserConfig` 不同:state 是「数据载体」,消费者要直接遍历
86
+ * `notes`/`folders`,因此回落到带空容器的对象(`{ lastSync: null, notes: {}, folders: {} }`);
87
+ * 而 `loadUserConfig` 回落到全字段 undefined(消费者用 `??` 链回落到默认值)。
88
+ */
89
+ export async function loadState(outputDir) {
90
+ let file = getStatePath(outputDir);
91
+ if (!(await fileExists(file))) {
92
+ file = join(outputDir, LEGACY_STATE_FILENAME);
93
+ if (!(await fileExists(file)))
94
+ return emptyState();
95
+ }
96
+ try {
97
+ const parsed = JSON.parse(await readFile(file, "utf-8"));
98
+ return {
99
+ lastSync: parsed.lastSync ?? null,
100
+ syncTag: parsed.syncTag,
101
+ notes: parsed.notes ?? {},
102
+ folders: parsed.folders ?? {},
103
+ };
104
+ }
105
+ catch {
106
+ return emptyState();
107
+ }
108
+ }
109
+ /**
110
+ * 原子写回同步状态(自动创建父目录,幂等)。
111
+ * 写成功后移除旧版状态文件,避免两份状态并存、旧版工具读到过期的基线。
112
+ */
113
+ export async function saveState(outputDir, state) {
114
+ await writeFileAtomic(getStatePath(outputDir), JSON.stringify(state, null, 2));
115
+ await rm(join(outputDir, LEGACY_STATE_FILENAME), { force: true });
116
+ }
117
+ // ============================================================
118
+ // 解析(output / mode)
119
+ // ============================================================
120
+ /**
121
+ * 解析生效的 output 目录(绝对路径)。
122
+ * 优先级:命令行 `-o <dir>` > 配置 output > 旧版默认目录 `.mi-note-cli/output/`(存在时)> `<root>/.micloud/note/`
123
+ *
124
+ * 相对路径基准:命令行 `-o` 基于当前目录(符合 Unix 工具约定);配置 output 与默认值基于项目根。
125
+ */
126
+ export async function resolveOutputDir(cliOutput) {
127
+ if (cliOutput)
128
+ return resolve(cliOutput);
129
+ const cfg = await loadUserConfig();
130
+ if (cfg.output)
131
+ return resolveOutputPath("note", undefined, cfg.output);
132
+ const legacy = join(getProjectRoot(), LEGACY_DEFAULT_OUTPUT);
133
+ if (await fileExists(legacy))
134
+ return legacy;
135
+ return getDefaultOutputDir();
136
+ }
137
+ /** 解析生效的同步模式:命令行 > 配置 > 默认 */
138
+ export async function resolveSyncMode(cliMode) {
139
+ if (cliMode)
140
+ return cliMode;
141
+ const cfg = await loadUserConfig();
142
+ return cfg.syncMode ?? DEFAULT_SYNC_MODE;
143
+ }
144
+ /** 设置默认同步模式(写入配置) */
145
+ export async function setSyncMode(mode) {
146
+ const cfg = await loadUserConfig();
147
+ cfg.syncMode = mode;
148
+ await saveUserConfig(cfg);
149
+ }
150
+ /** 设置默认 output 目录(写入配置) */
151
+ export async function setOutput(output) {
152
+ const cfg = await loadUserConfig();
153
+ cfg.output = output;
154
+ await saveUserConfig(cfg);
155
+ }
156
+ export const ALL_MODES = ["cloud-first", "local-first", "two-way", "manual"];
157
+ export { DEFAULT_SYNC_MODE };