micloud-cli 0.0.0-stage → 0.5.1
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/LICENSE +661 -0
- package/README.en.md +118 -0
- package/README.md +117 -2
- package/dist/cli.js +59 -0
- package/dist/commands/account.js +76 -0
- package/dist/core/account.js +22 -0
- package/dist/core/auth.js +338 -0
- package/dist/core/config.js +81 -0
- package/dist/core/http.js +172 -0
- package/dist/core/lock.js +90 -0
- package/dist/core/output.js +137 -0
- package/dist/core/template.js +39 -0
- package/dist/core/utils.js +205 -0
- package/dist/note/client.js +298 -0
- package/dist/note/commands/create.js +44 -0
- package/dist/note/commands/delete.js +32 -0
- package/dist/note/commands/export.js +20 -0
- package/dist/note/commands/folder.js +101 -0
- package/dist/note/commands/get.js +35 -0
- package/dist/note/commands/list.js +57 -0
- package/dist/note/commands/move.js +37 -0
- package/dist/note/commands/pin.js +41 -0
- package/dist/note/commands/search.js +45 -0
- package/dist/note/commands/shared.js +37 -0
- package/dist/note/commands/sync.js +217 -0
- package/dist/note/commands/update.js +61 -0
- package/dist/note/commands/upload-image.js +27 -0
- package/dist/note/config.js +166 -0
- package/dist/note/converter.js +664 -0
- package/dist/note/extra-info.js +23 -0
- package/dist/note/images.js +100 -0
- package/dist/note/register.js +172 -0
- package/dist/note/sync-diff.js +143 -0
- package/dist/note/sync.js +748 -0
- package/dist/note/text-diff.js +71 -0
- package/dist/note/types.js +2 -0
- package/dist/recording/client.js +115 -0
- package/dist/recording/commands/config.js +73 -0
- package/dist/recording/commands/delete.js +171 -0
- package/dist/recording/commands/list.js +161 -0
- package/dist/recording/commands/shared.js +47 -0
- package/dist/recording/commands/transfer.js +192 -0
- package/dist/recording/commands/trash.js +140 -0
- package/dist/recording/config.js +104 -0
- package/dist/recording/dates.js +61 -0
- package/dist/recording/download.js +308 -0
- package/dist/recording/progress.js +77 -0
- package/dist/recording/pull.js +433 -0
- package/dist/recording/recording.js +294 -0
- package/dist/recording/register.js +202 -0
- package/dist/recording/template.js +44 -0
- package/dist/recording/types.js +2 -0
- package/package.json +53 -4
|
@@ -0,0 +1,664 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { renderTemplate, dateVars } from "../core/template.js";
|
|
3
|
+
import { formatDateTime, sanitizeFileName } from "../core/utils.js";
|
|
4
|
+
const MIME_CATEGORY_MAP = {
|
|
5
|
+
image: { type: "img", defaultSuffix: "jpg" },
|
|
6
|
+
audio: { type: "audio", defaultSuffix: "mp3" },
|
|
7
|
+
video: { type: "video", defaultSuffix: "mp4" },
|
|
8
|
+
};
|
|
9
|
+
const MEDIA_TAG_FORMATS = [
|
|
10
|
+
{ tag: "img", format: (name, path) => `` },
|
|
11
|
+
{ tag: "sound", format: (name, path) => `[🔊 ${name}](${path})` },
|
|
12
|
+
{ tag: "video", format: (name, path) => `[🎬 ${name}](${path})` },
|
|
13
|
+
];
|
|
14
|
+
const HEADING_TAGS = [
|
|
15
|
+
{ tag: "size", prefix: "#" },
|
|
16
|
+
{ tag: "mid-size", prefix: "##" },
|
|
17
|
+
{ tag: "h3-size", prefix: "###" },
|
|
18
|
+
].map(({ tag, prefix }) => ({
|
|
19
|
+
tag,
|
|
20
|
+
prefix,
|
|
21
|
+
matchRegex: new RegExp(`^<${tag}>([\\s\\S]*?)</${tag}>$`),
|
|
22
|
+
inlineRegex: new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "g"),
|
|
23
|
+
}));
|
|
24
|
+
const LIST_TYPES = ["checkbox", "bullet", "order"];
|
|
25
|
+
// ============ 解析原始 entry ============
|
|
26
|
+
/** 解析 extraInfo(可能是 JSON 字符串或对象) */
|
|
27
|
+
export function parseExtraInfo(raw) {
|
|
28
|
+
if (!raw)
|
|
29
|
+
return {};
|
|
30
|
+
if (typeof raw !== "string")
|
|
31
|
+
return raw;
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(raw);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** 派生笔记标题(extraInfo.title > subject > 内容首行 > 创建时间) */
|
|
40
|
+
export function deriveTitle(note) {
|
|
41
|
+
const raw = deriveRawTitle(note);
|
|
42
|
+
if (raw)
|
|
43
|
+
return raw;
|
|
44
|
+
// legacy fallback:抽内容首行作为标题(用于无模板时的默认文件名)
|
|
45
|
+
// 注意此分支**仅用于 `ParsedNote.subject` 的 legacy 默认路径**,不进入 `rawTitle`,
|
|
46
|
+
// 因此模板 `${title}` 在无真标题时不会拿到内容首行——避免把正文一句话扔进文件名。
|
|
47
|
+
const firstLine = xmlToMarkdown(note.snippet ?? note.content ?? "")
|
|
48
|
+
.split("\n")
|
|
49
|
+
.map((l) => l.trim())
|
|
50
|
+
.find((l) => l.length > 0);
|
|
51
|
+
if (firstLine)
|
|
52
|
+
return firstLine;
|
|
53
|
+
return formatDateTime(note.createDate || Date.now());
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 派生「真标题」:仅取 `extraInfo.title` 或 `RawNoteEntry.subject` 这两个**显式标题字段**,
|
|
57
|
+
* 都为空则返回空字符串。
|
|
58
|
+
*
|
|
59
|
+
* 与 `deriveTitle` 的区别:**不**回退到「内容首行」——内容首行属于正文,把它当标题贴进
|
|
60
|
+
* 文件名模板会让 `${title}` 拿到一句话甚至一长串文字,违背「title 表示用户为笔记起的名字」
|
|
61
|
+
* 这一直觉。文件名模板专用,由调用方决定空值时如何兜底(智能裁分隔符 / datetime 等)。
|
|
62
|
+
*/
|
|
63
|
+
export function deriveRawTitle(note) {
|
|
64
|
+
const extra = parseExtraInfo(note.extraInfo);
|
|
65
|
+
const extraTitle = extra.title?.trim();
|
|
66
|
+
if (extraTitle)
|
|
67
|
+
return extraTitle;
|
|
68
|
+
if (note.subject?.trim())
|
|
69
|
+
return note.subject.trim();
|
|
70
|
+
return "";
|
|
71
|
+
}
|
|
72
|
+
/** 解析原始 entry 为领域模型 */
|
|
73
|
+
export function parseNoteEntry(note) {
|
|
74
|
+
const id = String(note.id);
|
|
75
|
+
const folderId = String(note.folderId || "");
|
|
76
|
+
const extra = parseExtraInfo(note.extraInfo);
|
|
77
|
+
let content = note.content || note.snippet || "";
|
|
78
|
+
if (extra.mind_content) {
|
|
79
|
+
content = extra.mind_content;
|
|
80
|
+
}
|
|
81
|
+
const subject = sanitizeFileName(deriveTitle(note));
|
|
82
|
+
const rawTitle = deriveRawTitle(note);
|
|
83
|
+
const files = parseNoteFiles(note);
|
|
84
|
+
return {
|
|
85
|
+
id,
|
|
86
|
+
folderId,
|
|
87
|
+
subject,
|
|
88
|
+
rawTitle,
|
|
89
|
+
content,
|
|
90
|
+
files,
|
|
91
|
+
createDate: note.createDate,
|
|
92
|
+
modifyDate: note.modifyDate,
|
|
93
|
+
contentType: extra.note_content_type || "note",
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function parseNoteFiles(note) {
|
|
97
|
+
const rawFiles = note.setting?.data || note.files || [];
|
|
98
|
+
if (!Array.isArray(rawFiles))
|
|
99
|
+
return [];
|
|
100
|
+
return rawFiles.map((file) => {
|
|
101
|
+
const rawId = file.rawId || file.fileId || file.digest || "";
|
|
102
|
+
const mimeType = file.mimeType || "";
|
|
103
|
+
const dotIndex = rawId.indexOf(".");
|
|
104
|
+
const id = dotIndex >= 0 ? rawId.slice(dotIndex + 1) : rawId;
|
|
105
|
+
const { type, suffix } = inferFileType(mimeType);
|
|
106
|
+
const dateStr = formatDateTime(note.createDate || Date.now());
|
|
107
|
+
const name = `${type}_${dateStr}_${id.slice(-8)}.${suffix}`;
|
|
108
|
+
return { rawId, name, id, type, suffix, fileId: rawId };
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
function inferFileType(mimeType) {
|
|
112
|
+
const [category, subtype] = mimeType.split("/");
|
|
113
|
+
const mapping = MIME_CATEGORY_MAP[category];
|
|
114
|
+
if (!mapping)
|
|
115
|
+
return { type: "file", suffix: "bin" };
|
|
116
|
+
let suffix = subtype || mapping.defaultSuffix;
|
|
117
|
+
if (suffix === "jpeg")
|
|
118
|
+
suffix = "jpg";
|
|
119
|
+
return { type: mapping.type, suffix };
|
|
120
|
+
}
|
|
121
|
+
// ============ XML → Markdown ============
|
|
122
|
+
/**
|
|
123
|
+
* 将笔记 XML 内容转换为 Markdown(逐行解析)。
|
|
124
|
+
* @param content 原始 XML 内容
|
|
125
|
+
* @param files 附件列表(用于替换 <img>/<sound>/<video> 标记为本地路径)
|
|
126
|
+
* @param assetPrefix 附件路径前缀(默认 "assets/",传入 "minote://image/" 等可定制)
|
|
127
|
+
*/
|
|
128
|
+
export function xmlToMarkdown(content, files = [], assetPrefix = "assets/") {
|
|
129
|
+
if (!content)
|
|
130
|
+
return "";
|
|
131
|
+
let text = content.replace(/\r\n/g, "\n");
|
|
132
|
+
// 预处理:替换附件标记
|
|
133
|
+
text = replaceAttachments(text, files, assetPrefix);
|
|
134
|
+
// 未登记在 setting.data 里的图片没有本地文件可指向,保留为 minote 引用,避免转换时丢图
|
|
135
|
+
text = text.replace(/<img\s+[^>]*fileid="([^"]+)"[^>]*\/>/g, (_m, fileId) => ``);
|
|
136
|
+
// 移除格式标记
|
|
137
|
+
text = text.replace(/<new-format\s*\/>/g, "");
|
|
138
|
+
text = text.replace(/<0\/>/g, "");
|
|
139
|
+
// 多行 <quote>...</quote>:把内部换行用占位符替换,让整个 quote 合并成单行 token
|
|
140
|
+
// 交给 parseLine 解析时再还原。这样可以复用逐行解析的主循环。
|
|
141
|
+
text = text.replace(/<quote>([\s\S]*?)<\/quote>/g, (_m, inner) => `<quote>${inner.replace(/\n/g, "\u2028")}</quote>`);
|
|
142
|
+
const lines = text.split("\n");
|
|
143
|
+
const mdLines = [];
|
|
144
|
+
let prevType = "";
|
|
145
|
+
// 按 indent 分组的运行计数器:解析 inputNumber=0 时的真实序号。
|
|
146
|
+
// 任何非 order 行(或无法识别行)都会清空,与 Mi Note 客户端「order 链被打断即重置」的语义对齐。
|
|
147
|
+
const orderCounters = new Map();
|
|
148
|
+
for (const line of lines) {
|
|
149
|
+
const parsed = parseLine(line.trim(), orderCounters);
|
|
150
|
+
if (parsed === null) {
|
|
151
|
+
orderCounters.clear();
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (mdLines.length > 0 && needsBlankLine(prevType, parsed.type)) {
|
|
155
|
+
mdLines.push("");
|
|
156
|
+
}
|
|
157
|
+
mdLines.push(parsed.text);
|
|
158
|
+
prevType = parsed.type;
|
|
159
|
+
}
|
|
160
|
+
let result = mdLines.join("\n");
|
|
161
|
+
result = result.replace(/\n{3,}/g, "\n\n");
|
|
162
|
+
return result.trim();
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 将已解析的笔记转换为 Markdown(便捷封装)。
|
|
166
|
+
* 会用解析出的附件列表把 <img>/<sound>/<video> 标记替换为 assets/ 本地路径。
|
|
167
|
+
*/
|
|
168
|
+
export function noteToMarkdown(note) {
|
|
169
|
+
return xmlToMarkdown(note.content, note.files, "assets/");
|
|
170
|
+
}
|
|
171
|
+
function needsBlankLine(prevType, currType) {
|
|
172
|
+
if (!prevType)
|
|
173
|
+
return false;
|
|
174
|
+
if (prevType === currType && LIST_TYPES.includes(currType))
|
|
175
|
+
return false;
|
|
176
|
+
if (prevType === "text" && currType === "text")
|
|
177
|
+
return true;
|
|
178
|
+
const blockTypes = ["heading", "hr", "quote"];
|
|
179
|
+
if (blockTypes.includes(currType) || blockTypes.includes(prevType))
|
|
180
|
+
return true;
|
|
181
|
+
if (LIST_TYPES.includes(prevType) !== LIST_TYPES.includes(currType))
|
|
182
|
+
return true;
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
function parseLine(line, orderCounters) {
|
|
186
|
+
if (!line) {
|
|
187
|
+
orderCounters?.clear();
|
|
188
|
+
return { type: "blank", text: "" };
|
|
189
|
+
}
|
|
190
|
+
// order:小米客户端原生形态 `<order indent="N" inputNumber="X" />文本`
|
|
191
|
+
// - inputNumber>0:显式数字,刷新该层运行计数器为该值(后续 inputNumber=0 接续 +1)
|
|
192
|
+
// - inputNumber=0 或缺省:取该层运行计数 +1(首次出现即 1)
|
|
193
|
+
// - 进入更浅层时,所有更深 indent 的计数器作废
|
|
194
|
+
// 此分支必须放在「清空计数器」之前——它是唯一会读写计数器的分支。
|
|
195
|
+
const orderSelfMatch = line.match(/^<order\s+indent="(\d+)"(?:\s+inputNumber="(\d+)")?\s*\/>(.*)$/);
|
|
196
|
+
if (orderSelfMatch) {
|
|
197
|
+
const indent = getIndentLevel(orderSelfMatch[1]);
|
|
198
|
+
const numberRaw = orderSelfMatch[2];
|
|
199
|
+
const explicit = numberRaw ? Number(numberRaw) : 0;
|
|
200
|
+
let number;
|
|
201
|
+
if (orderCounters) {
|
|
202
|
+
for (const k of [...orderCounters.keys()]) {
|
|
203
|
+
if (k > indent)
|
|
204
|
+
orderCounters.delete(k);
|
|
205
|
+
}
|
|
206
|
+
number =
|
|
207
|
+
explicit > 0 ? explicit : (orderCounters.get(indent) ?? 0) + 1;
|
|
208
|
+
orderCounters.set(indent, number);
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
number = explicit > 0 ? explicit : 1;
|
|
212
|
+
}
|
|
213
|
+
return formatListItem("order", `${number}.`, orderSelfMatch[1], orderSelfMatch[3]);
|
|
214
|
+
}
|
|
215
|
+
// 其余分支均视为 order 链被打断(含 hr / 复选框 / bullet / quote / 普通文本 / 标题等)
|
|
216
|
+
orderCounters?.clear();
|
|
217
|
+
if (/^<hr\s*\/>$/.test(line))
|
|
218
|
+
return { type: "hr", text: "---" };
|
|
219
|
+
// 复选框(可能自闭合后跟文本,或包裹文本)
|
|
220
|
+
const checkboxMatch = line.match(/^<input\s+([^>]*?)type="checkbox"([^>]*?)\s*\/>(.*)$/);
|
|
221
|
+
if (checkboxMatch) {
|
|
222
|
+
const attrs = checkboxMatch[1] + checkboxMatch[2];
|
|
223
|
+
const indentMatch = attrs.match(/indent="(\d+)"/);
|
|
224
|
+
const checkedMatch = attrs.match(/checked="(true|false)"/);
|
|
225
|
+
const indent = getIndentLevel(indentMatch?.[1]);
|
|
226
|
+
const checked = checkedMatch?.[1] === "true";
|
|
227
|
+
const inner = stripTrailingTags(checkboxMatch[3]).trim();
|
|
228
|
+
const txt = convertInlineStyles(inner);
|
|
229
|
+
const spaces = " ".repeat(indent);
|
|
230
|
+
return { type: "checkbox", text: `${spaces}- [${checked ? "x" : " "}] ${txt}` };
|
|
231
|
+
}
|
|
232
|
+
const bulletMatch = line.match(/^<bullet(?:\s+indent="(\d+)")?\s*>([\s\S]*?)<\/bullet>$/);
|
|
233
|
+
if (bulletMatch)
|
|
234
|
+
return formatListItem("bullet", "-", bulletMatch[1], bulletMatch[2]);
|
|
235
|
+
// 自闭合 bullet:<bullet indent="1" />文本
|
|
236
|
+
const bulletSelfMatch = line.match(/^<bullet\s+indent="(\d+)"\s*\/>(.*)$/);
|
|
237
|
+
if (bulletSelfMatch) {
|
|
238
|
+
return formatListItem("bullet", "-", bulletSelfMatch[1], bulletSelfMatch[2]);
|
|
239
|
+
}
|
|
240
|
+
const quoteMatch = line.match(/^<quote>([\s\S]*?)<\/quote>$/);
|
|
241
|
+
if (quoteMatch) {
|
|
242
|
+
// 把 xmlToMarkdown 预处理时塞入的 \u2028 占位符还原为换行
|
|
243
|
+
const inner = quoteMatch[1].replace(/\u2028/g, "\n");
|
|
244
|
+
// 内部可能是小米客户端的多行形态:<text indent="1">行</text>\n<text>...</text>
|
|
245
|
+
// 也可能是旧的简单形态:直接 inline 文本
|
|
246
|
+
const innerTexts = [...inner.matchAll(/<text[^>]*>([\s\S]*?)<\/text>/g)].map((m) => m[1].trim());
|
|
247
|
+
const quoteLines = innerTexts.length > 0 ? innerTexts : [inner.trim()];
|
|
248
|
+
const text = quoteLines
|
|
249
|
+
.map((l) => `> ${convertInlineStyles(l)}`)
|
|
250
|
+
.join("\n");
|
|
251
|
+
return { type: "quote", text };
|
|
252
|
+
}
|
|
253
|
+
const textMatch = line.match(/^<text(?:\s+indent="(\d+)")?\s*>([\s\S]*?)<\/text>$/);
|
|
254
|
+
if (textMatch) {
|
|
255
|
+
const indentStr = textMatch[1];
|
|
256
|
+
const inner = textMatch[2];
|
|
257
|
+
if (!inner.trim())
|
|
258
|
+
return { type: "blank", text: "" };
|
|
259
|
+
if (indentStr === "NaN")
|
|
260
|
+
return { type: "blank", text: "" };
|
|
261
|
+
const heading = tryParseHeading(inner);
|
|
262
|
+
if (heading)
|
|
263
|
+
return heading;
|
|
264
|
+
const indent = getIndentLevel(indentStr);
|
|
265
|
+
const spaces = " ".repeat(indent);
|
|
266
|
+
return { type: "text", text: `${spaces}${convertInlineStyles(inner.trim())}` };
|
|
267
|
+
}
|
|
268
|
+
const alignMatch = line.match(/^<align\s+align="(center|left|right)">([\s\S]*?)<\/align>$/);
|
|
269
|
+
if (alignMatch) {
|
|
270
|
+
return {
|
|
271
|
+
type: "text",
|
|
272
|
+
text: `<div align="${alignMatch[1]}">${convertInlineStyles(alignMatch[2].trim())}</div>`,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
if (/^☺\s/.test(line))
|
|
276
|
+
return null;
|
|
277
|
+
// 无法识别:去掉未知标签后保留文本
|
|
278
|
+
const cleaned = convertInlineStyles(line).replace(/<[^>]+>/g, "").trim();
|
|
279
|
+
return cleaned ? { type: "text", text: cleaned } : null;
|
|
280
|
+
}
|
|
281
|
+
function stripTrailingTags(s) {
|
|
282
|
+
// 去除复选框文本尾部可能残留的 <0/> 等空标记
|
|
283
|
+
return s.replace(/<0\/>/g, "");
|
|
284
|
+
}
|
|
285
|
+
function formatListItem(type, marker, indentStr, content) {
|
|
286
|
+
const indent = getIndentLevel(indentStr);
|
|
287
|
+
const text = convertInlineStyles(content.trim());
|
|
288
|
+
const spaces = " ".repeat(indent);
|
|
289
|
+
return { type, text: `${spaces}${marker} ${text}` };
|
|
290
|
+
}
|
|
291
|
+
function tryParseHeading(content) {
|
|
292
|
+
const trimmed = content.trim();
|
|
293
|
+
for (const { prefix, matchRegex } of HEADING_TAGS) {
|
|
294
|
+
const match = trimmed.match(matchRegex);
|
|
295
|
+
if (match) {
|
|
296
|
+
return { type: "heading", text: `${prefix} ${convertInlineStyles(match[1].trim())}` };
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
function convertInlineStyles(text) {
|
|
302
|
+
if (!text)
|
|
303
|
+
return "";
|
|
304
|
+
text = text.replace(/<b>([\s\S]*?)<\/b>/g, "**$1**");
|
|
305
|
+
text = text.replace(/<i>([\s\S]*?)<\/i>/g, "*$1*");
|
|
306
|
+
text = text.replace(/<delete>([\s\S]*?)<\/delete>/g, "~~$1~~");
|
|
307
|
+
text = text.replace(/<u>([\s\S]*?)<\/u>/g, "<u>$1</u>");
|
|
308
|
+
text = text.replace(/<background\s+color="([^"]+)">([\s\S]*?)<\/background>/g, (_m, color, inner) => `<mark style="background:${bgrToRgb(color)}">${inner}</mark>`);
|
|
309
|
+
for (const { inlineRegex } of HEADING_TAGS) {
|
|
310
|
+
text = text.replace(inlineRegex, "**$1**");
|
|
311
|
+
}
|
|
312
|
+
return decodeHtmlEntities(text);
|
|
313
|
+
}
|
|
314
|
+
function getIndentLevel(indentStr) {
|
|
315
|
+
const n = Number(indentStr || 0);
|
|
316
|
+
if (Number.isNaN(n))
|
|
317
|
+
return 0;
|
|
318
|
+
return Math.max(0, n - 1);
|
|
319
|
+
}
|
|
320
|
+
function replaceAttachments(content, files, assetPrefix) {
|
|
321
|
+
for (const file of files) {
|
|
322
|
+
const assetPath = `${assetPrefix}${file.name}`;
|
|
323
|
+
const escapedId = escapeRegex(file.rawId);
|
|
324
|
+
const imgMd = ``;
|
|
325
|
+
for (const { tag, format } of MEDIA_TAG_FORMATS) {
|
|
326
|
+
const regex = new RegExp(`<${tag}\\s+[^>]*(?:id|fileid|data)="[^"]*${escapedId}[^"]*"[^>]*/>`, "g");
|
|
327
|
+
content = content.replace(regex, format(file.name, assetPath));
|
|
328
|
+
}
|
|
329
|
+
content = content.replace(new RegExp(`☺\\s*${escapedId}<[^>]*></>`, "g"), imgMd);
|
|
330
|
+
content = content.replace(new RegExp(`☺\\s*${escapedId}(?!<)`, "g"), imgMd);
|
|
331
|
+
}
|
|
332
|
+
return content;
|
|
333
|
+
}
|
|
334
|
+
// ============ Markdown → XML ============
|
|
335
|
+
const INDENT_TAB = "\t";
|
|
336
|
+
const IMAGE_RE = /!\[[^\]]*\]\(([^)]+)\)/;
|
|
337
|
+
/**
|
|
338
|
+
* 将 Markdown 转换为小米笔记 XML 内容(用于创建/更新)。
|
|
339
|
+
* @param markdown Markdown 文本
|
|
340
|
+
* @param imageMap 可选:Markdown 图片 target → fileId 映射(本地上传后回填)
|
|
341
|
+
*/
|
|
342
|
+
export function markdownToXml(markdown, imageMap = new Map()) {
|
|
343
|
+
if (!markdown)
|
|
344
|
+
return "";
|
|
345
|
+
const out = [];
|
|
346
|
+
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
|
|
347
|
+
const blocks = [];
|
|
348
|
+
for (let i = 0; i < lines.length; i++) {
|
|
349
|
+
const m = lines[i].match(/^>\s?(.*)$/);
|
|
350
|
+
if (m) {
|
|
351
|
+
const quoteLines = [m[1]];
|
|
352
|
+
while (i + 1 < lines.length) {
|
|
353
|
+
const m2 = lines[i + 1].match(/^>\s?(.*)$/);
|
|
354
|
+
if (!m2)
|
|
355
|
+
break;
|
|
356
|
+
quoteLines.push(m2[1]);
|
|
357
|
+
i++;
|
|
358
|
+
}
|
|
359
|
+
blocks.push({ kind: "quote", lines: quoteLines });
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
blocks.push({ kind: "raw", line: lines[i] });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
// 列表层级推断(栈式相对缩进)
|
|
366
|
+
// 维护一个 { width, level } 栈:遇到比栈顶宽的缩进进入下一级;相等保持;更窄则弹栈。
|
|
367
|
+
// 这样能容忍 2/3/4 空格混用、tab 缩进,无需做 CommonMark 完整解析。
|
|
368
|
+
const indentStack = [];
|
|
369
|
+
const widthOfLeading = (leading) => {
|
|
370
|
+
let w = 0;
|
|
371
|
+
for (const c of leading) {
|
|
372
|
+
if (c === "\t")
|
|
373
|
+
w += 4;
|
|
374
|
+
else if (c === " ")
|
|
375
|
+
w += 1;
|
|
376
|
+
else
|
|
377
|
+
break;
|
|
378
|
+
}
|
|
379
|
+
return w;
|
|
380
|
+
};
|
|
381
|
+
const determineListLevel = (leading) => {
|
|
382
|
+
const width = widthOfLeading(leading);
|
|
383
|
+
while (indentStack.length > 0 && indentStack[indentStack.length - 1].width > width) {
|
|
384
|
+
indentStack.pop();
|
|
385
|
+
}
|
|
386
|
+
if (indentStack.length > 0 && indentStack[indentStack.length - 1].width === width) {
|
|
387
|
+
return indentStack[indentStack.length - 1].level;
|
|
388
|
+
}
|
|
389
|
+
const newLevel = indentStack.length === 0 ? 1 : indentStack[indentStack.length - 1].level + 1;
|
|
390
|
+
indentStack.push({ width, level: newLevel });
|
|
391
|
+
return newLevel;
|
|
392
|
+
};
|
|
393
|
+
const resetListStack = () => {
|
|
394
|
+
indentStack.length = 0;
|
|
395
|
+
};
|
|
396
|
+
for (const block of blocks) {
|
|
397
|
+
if (block.kind === "quote") {
|
|
398
|
+
// 多行 quote:每行作为一个内部 <text indent="1">;
|
|
399
|
+
// 单行 quote 也用同一格式,便于反向解析统一处理。
|
|
400
|
+
const inner = block.lines
|
|
401
|
+
.map((l) => `<text indent="1">${inlineMdToXml(l)}</text>`)
|
|
402
|
+
.join("\n");
|
|
403
|
+
out.push(`<quote>${inner}</quote>`);
|
|
404
|
+
resetListStack();
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
const rawLine = block.line;
|
|
408
|
+
const line = rawLine.replace(/\s+$/g, "");
|
|
409
|
+
// 图片:minote://image/{id} 或本地映射
|
|
410
|
+
const imageMatch = line.match(IMAGE_RE);
|
|
411
|
+
if (imageMatch) {
|
|
412
|
+
const fileId = resolveImageFileId(imageMatch[1], imageMap);
|
|
413
|
+
if (fileId) {
|
|
414
|
+
out.push(`<img fileid="${fileId}" imgshow="0" imgdes="" />`);
|
|
415
|
+
resetListStack();
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
// 标题
|
|
420
|
+
const heading = line.match(/^(#{1,3})\s+(.*)$/);
|
|
421
|
+
if (heading) {
|
|
422
|
+
const level = heading[1].length;
|
|
423
|
+
const tag = level === 1 ? "size" : level === 2 ? "mid-size" : "h3-size";
|
|
424
|
+
out.push(`<text indent="1"><${tag}>${escapeXml(heading[2])}</${tag}></text>`);
|
|
425
|
+
resetListStack();
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
// 分割线
|
|
429
|
+
if (/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())) {
|
|
430
|
+
out.push("<hr />");
|
|
431
|
+
resetListStack();
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
// 复选框(小米原生形态:indent="N" level="3",level 含义未明但小米客户端固定写 3)
|
|
435
|
+
const checkbox = line.match(/^(\s*)- \[([xX ])\]\s+(.*)$/);
|
|
436
|
+
if (checkbox) {
|
|
437
|
+
const indent = determineListLevel(checkbox[1]);
|
|
438
|
+
const checked = checkbox[2].toLowerCase() === "x";
|
|
439
|
+
const checkedAttr = checked ? ' checked="true"' : "";
|
|
440
|
+
out.push(`<input type="checkbox" indent="${indent}" level="3"${checkedAttr} />${inlineMdToXml(checkbox[3])}`);
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
// 无序列表
|
|
444
|
+
const bullet = line.match(/^(\s*)[-*]\s+(.*)$/);
|
|
445
|
+
if (bullet) {
|
|
446
|
+
const indent = determineListLevel(bullet[1]);
|
|
447
|
+
out.push(`<bullet indent="${indent}" />${inlineMdToXml(bullet[2])}`);
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
// 有序列表
|
|
451
|
+
// 小米客户端原生形态:`<order indent="N" inputNumber="X" />文本`
|
|
452
|
+
// - 必须自闭合 + 后置文本(与 bullet 一致;闭合包裹形式 `<order>...</order>` 会被吞内容)
|
|
453
|
+
// - 必须显式带 inputNumber,按用户写的数字渲染;否则被 <text> 段落打断后,相邻自增计数会重置
|
|
454
|
+
const order = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
|
|
455
|
+
if (order) {
|
|
456
|
+
const indent = determineListLevel(order[1]);
|
|
457
|
+
const number = order[2];
|
|
458
|
+
out.push(`<order indent="${indent}" inputNumber="${number}" />${inlineMdToXml(order[3])}`);
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
// 空行:保留 <text indent="1"></text> 占位;列表栈不变(允许列表中间夹空行)
|
|
462
|
+
if (!line.trim()) {
|
|
463
|
+
out.push(`<text indent="1"></text>`);
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
// 普通文本:会终止上一段列表的层级关系
|
|
467
|
+
const indent = line.startsWith(INDENT_TAB) ? 2 : 1;
|
|
468
|
+
const normalized = line.replace(/^\t/, "");
|
|
469
|
+
out.push(`<text indent="${indent}">${inlineMdToXml(normalized)}</text>`);
|
|
470
|
+
resetListStack();
|
|
471
|
+
}
|
|
472
|
+
// 文末因文件换行产生的空段落:xmlToMarkdown 会 trim,小米云端也会丢掉。
|
|
473
|
+
// 不写进 XML,避免 round-trip 因末尾多一个 <text></text> 假失败。
|
|
474
|
+
while (out.length > 0 && out[out.length - 1] === '<text indent="1"></text>') {
|
|
475
|
+
out.pop();
|
|
476
|
+
}
|
|
477
|
+
return out.join("\n");
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* 行内 Markdown → XML(加粗/斜体/删除线/下划线)。
|
|
481
|
+
* 下划线在 markdown 中以 HTML 形式 `<u>...</u>` 书写——是 markdown 允许的内联 HTML。
|
|
482
|
+
*/
|
|
483
|
+
function inlineMdToXml(text) {
|
|
484
|
+
// 抽出 <u>...</u> 内容到占位符,避免被 escapeXml 转义;最后把内容(仍需 escape)放回 <u> 标签
|
|
485
|
+
const uPlaceholders = [];
|
|
486
|
+
const PH_OPEN = "\uE000U";
|
|
487
|
+
const PH_CLOSE = "\uE001";
|
|
488
|
+
let stage = text.replace(/<u>([\s\S]*?)<\/u>/g, (_m, inner) => {
|
|
489
|
+
const idx = uPlaceholders.length;
|
|
490
|
+
uPlaceholders.push(inner);
|
|
491
|
+
return `${PH_OPEN}${idx}${PH_CLOSE}`;
|
|
492
|
+
});
|
|
493
|
+
stage = escapeXml(stage);
|
|
494
|
+
stage = stage.replace(/\*\*(.+?)\*\*/g, "<b>$1</b>");
|
|
495
|
+
stage = stage.replace(/(?<!\*)\*(?!\*)([^*]+?)\*(?!\*)/g, "<i>$1</i>");
|
|
496
|
+
stage = stage.replace(/~~(.+?)~~/g, "<delete>$1</delete>");
|
|
497
|
+
// 占位符还原成 <u>...</u>,内容仍需 escape(防 < & 等字符)
|
|
498
|
+
stage = stage.replace(new RegExp(`${PH_OPEN}(\\d+)${PH_CLOSE}`, "g"), (_m, idx) => `<u>${escapeXml(uPlaceholders[+idx])}</u>`);
|
|
499
|
+
return stage;
|
|
500
|
+
}
|
|
501
|
+
function resolveImageFileId(target, imageMap) {
|
|
502
|
+
if (target.startsWith("minote://image/")) {
|
|
503
|
+
return target.substring("minote://image/".length);
|
|
504
|
+
}
|
|
505
|
+
return imageMap.get(target);
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* 附件落盘引用 → fileId 映射,与 xmlToMarkdown 产出的 `<prefix><name>` 引用一一对应。
|
|
509
|
+
* 上行(markdownToXml)时传入,才能把本地 Markdown 里的图片还原成云端 <img>。
|
|
510
|
+
* 可传多个前缀以兼容不同位置/旧版本写出的引用。
|
|
511
|
+
*/
|
|
512
|
+
export function buildImageMap(files, ...assetPrefixes) {
|
|
513
|
+
const prefixes = assetPrefixes.length > 0 ? assetPrefixes : ["assets/"];
|
|
514
|
+
const map = new Map();
|
|
515
|
+
for (const prefix of prefixes) {
|
|
516
|
+
for (const f of files)
|
|
517
|
+
map.set(`${prefix}${f.name}`, f.fileId);
|
|
518
|
+
}
|
|
519
|
+
return map;
|
|
520
|
+
}
|
|
521
|
+
/** 每行第一个图片引用的 target(与 markdownToXml 的识别规则一致) */
|
|
522
|
+
export function listImageTargets(markdown) {
|
|
523
|
+
const targets = [];
|
|
524
|
+
for (const line of markdown.replace(/\r\n/g, "\n").split("\n")) {
|
|
525
|
+
const m = line.match(IMAGE_RE);
|
|
526
|
+
if (m)
|
|
527
|
+
targets.push(m[1]);
|
|
528
|
+
}
|
|
529
|
+
return targets;
|
|
530
|
+
}
|
|
531
|
+
/** 是否为需要上传的本地图片引用(外链与 minote 引用之外的都算) */
|
|
532
|
+
export function isLocalImageTarget(target) {
|
|
533
|
+
return !/^https?:\/\//i.test(target) && !target.startsWith("minote://image/");
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* 找出 markdownToXml 无法还原、上传后会退化成纯文本的附件引用:
|
|
537
|
+
* - 不在 imageMap 里的本地图片(通常是文件找不到;外链 http(s) 图片按原样保留为文本,不算)
|
|
538
|
+
* - 与文字同行的图片(整行会被替换为 <img>,同行文字丢失)
|
|
539
|
+
* - 指向 assets/ 的音频/视频等非图片链接(暂不支持回写)
|
|
540
|
+
*/
|
|
541
|
+
export function findUnresolvedAttachments(markdown, imageMap = new Map()) {
|
|
542
|
+
const problems = [];
|
|
543
|
+
for (const raw of markdown.replace(/\r\n/g, "\n").split("\n")) {
|
|
544
|
+
const line = raw.trim();
|
|
545
|
+
const image = line.match(IMAGE_RE);
|
|
546
|
+
if (image && !/^https?:\/\//i.test(image[1])) {
|
|
547
|
+
if (!resolveImageFileId(image[1], imageMap)) {
|
|
548
|
+
problems.push(`找不到图片文件或格式不支持:${image[1]}`);
|
|
549
|
+
}
|
|
550
|
+
else if (line !== image[0]) {
|
|
551
|
+
problems.push(`图片需独占一行:${line}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
for (const m of line.matchAll(/(?<!!)\[[^\]]*\]\(([^)]+)\)/g)) {
|
|
555
|
+
if (/(^|\/)assets\//.test(m[1])) {
|
|
556
|
+
problems.push(`暂不支持回写的附件:${m[1]}`);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
return problems;
|
|
561
|
+
}
|
|
562
|
+
/** 上行前的附件守护:存在会退化成纯文本的引用时直接报错,避免覆盖云端附件 */
|
|
563
|
+
export function assertAttachmentsResolvable(markdown, imageMap = new Map()) {
|
|
564
|
+
const problems = findUnresolvedAttachments(markdown, imageMap);
|
|
565
|
+
if (problems.length > 0) {
|
|
566
|
+
throw new Error(`内容里有无法回写到云端的附件引用,已中止以免丢失附件:\n ${problems.join("\n ")}\n` +
|
|
567
|
+
" 本地图片路径相对 Markdown 文件所在目录(--content / 标准输入时相对当前目录)。");
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
/** 从 XML 内容提取首行非空文本作为 snippet */
|
|
571
|
+
export function extractSnippet(xml) {
|
|
572
|
+
return (xml
|
|
573
|
+
.split("\n")
|
|
574
|
+
.map((l) => l.trim())
|
|
575
|
+
.find((l) => l.length > 0) ?? "");
|
|
576
|
+
}
|
|
577
|
+
// ============ 文件路径 ============
|
|
578
|
+
/**
|
|
579
|
+
* 计算笔记落盘路径(含目录:云端 folder → 一级子目录)。
|
|
580
|
+
*
|
|
581
|
+
* - `template` 缺省:文件名直接用 `note.subject`(已含 datetime fallback,向后兼容)
|
|
582
|
+
* - `template` 非空:按模板渲染(占位符替换 + 智能裁分隔符 + sanitize),
|
|
583
|
+
* 渲染后为空时回退到创建时间字符串,避免产出空文件名
|
|
584
|
+
*/
|
|
585
|
+
export function getNoteFilePath(note, folders, outputDir, template) {
|
|
586
|
+
const folder = note.folderId ? folders[note.folderId] : undefined;
|
|
587
|
+
const folderName = folder ? sanitizeFileName(folder.subject || "") : "";
|
|
588
|
+
const baseName = template && template.trim() ? renderFileNameTemplate(template, note) : note.subject;
|
|
589
|
+
const fileName = `${baseName}.md`;
|
|
590
|
+
return folderName
|
|
591
|
+
? join(outputDir, folderName, fileName)
|
|
592
|
+
: join(outputDir, fileName);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* 渲染文件名模板。
|
|
596
|
+
*
|
|
597
|
+
* 占位符(字面替换):
|
|
598
|
+
* - `${YYYY}` `${YY}` `${MM}` `${DD}` `${HH}` `${mm}` `${ss}`:基于 `createDate` 的本地时区分量
|
|
599
|
+
* (`YYYY`=4 位年,`YY`=2 位年,其余两位零填充)
|
|
600
|
+
* - `${title}`:真实标题,用户没填即空字符串
|
|
601
|
+
* - `${subject}`:带兜底的笔记称呼(标题 → 内容首行 → datetime),永远非空
|
|
602
|
+
* - `${id}`:笔记 id
|
|
603
|
+
* - 未识别的 `${xxx}` 原样保留
|
|
604
|
+
*
|
|
605
|
+
* 条件段语法 `[...]`:
|
|
606
|
+
* 方括号内的内容只有当所有 `${var}` 都非空时才渲染,否则**整块丢弃**——
|
|
607
|
+
* 主要用法是把可选段连同其引导分隔符一起包起来,避免空 title 导致多余分隔符。
|
|
608
|
+
* - 例:`${YYYY}-${MM}-${DD}[_${title}]` → 有标题 `2026-06-06_工作`,无标题 `2026-06-06`
|
|
609
|
+
* - 不支持嵌套;未匹配的 `[` 当字面保留
|
|
610
|
+
* - 字面 `[` `]` 用 `\[` `\]` 转义
|
|
611
|
+
*
|
|
612
|
+
* 后处理:
|
|
613
|
+
* 1. 经 `sanitizeFileName` 清理 OS 非法字符
|
|
614
|
+
* 2. 若结果为空(如模板仅有 `${title}` 且无标题),回退到 datetime 防止产出空文件名
|
|
615
|
+
*
|
|
616
|
+
* 不做首尾/连续分隔符的隐式处理——所见即所得,可选段请用 `[...]` 显式表达。
|
|
617
|
+
*/
|
|
618
|
+
export function renderFileNameTemplate(template, note) {
|
|
619
|
+
const ts = note.createDate || Date.now();
|
|
620
|
+
const vars = {
|
|
621
|
+
...dateVars(ts),
|
|
622
|
+
title: note.rawTitle,
|
|
623
|
+
subject: note.subject,
|
|
624
|
+
id: note.id,
|
|
625
|
+
};
|
|
626
|
+
const cleaned = sanitizeFileName(renderTemplate(template, vars));
|
|
627
|
+
if (cleaned)
|
|
628
|
+
return cleaned;
|
|
629
|
+
// 兜底:模板渲染为空时(如纯 `${title}` 无标题)退回 datetime,绝不产出空文件名
|
|
630
|
+
return formatDateTime(ts);
|
|
631
|
+
}
|
|
632
|
+
// ============ 工具 ============
|
|
633
|
+
function bgrToRgb(bgrColor) {
|
|
634
|
+
if (!bgrColor || bgrColor.length < 6)
|
|
635
|
+
return bgrColor;
|
|
636
|
+
const hex = bgrColor.replace("#", "");
|
|
637
|
+
const b = hex.slice(0, 2);
|
|
638
|
+
const g = hex.slice(2, 4);
|
|
639
|
+
const r = hex.slice(4, 6);
|
|
640
|
+
return `#${r}${g}${b}`;
|
|
641
|
+
}
|
|
642
|
+
function escapeRegex(str) {
|
|
643
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
644
|
+
}
|
|
645
|
+
function escapeXml(text) {
|
|
646
|
+
return text
|
|
647
|
+
.replace(/&/g, "&")
|
|
648
|
+
.replace(/</g, "<")
|
|
649
|
+
.replace(/>/g, ">");
|
|
650
|
+
}
|
|
651
|
+
const HTML_ENTITY_MAP = {
|
|
652
|
+
amp: "&",
|
|
653
|
+
lt: "<",
|
|
654
|
+
gt: ">",
|
|
655
|
+
quot: '"',
|
|
656
|
+
apos: "'",
|
|
657
|
+
nbsp: " ",
|
|
658
|
+
};
|
|
659
|
+
function decodeHtmlEntities(value) {
|
|
660
|
+
return value.replace(/&([a-z]+);/gi, (_m, entity) => {
|
|
661
|
+
const decoded = HTML_ENTITY_MAP[entity.toLowerCase()];
|
|
662
|
+
return decoded ?? `&${entity};`;
|
|
663
|
+
});
|
|
664
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { parseExtraInfo } from "./converter.js";
|
|
2
|
+
/**
|
|
3
|
+
* 构造 extraInfo JSON 字符串。
|
|
4
|
+
* - 保留已有字段(更新场景),仅覆盖 title。
|
|
5
|
+
* - 默认 note_content_type 为 "common"。
|
|
6
|
+
*/
|
|
7
|
+
export function buildExtraInfoString(title, existing) {
|
|
8
|
+
const base = parseExtraInfo(existing);
|
|
9
|
+
const info = {
|
|
10
|
+
note_content_type: base.note_content_type ?? "common",
|
|
11
|
+
title: base.title,
|
|
12
|
+
web_images: base.web_images,
|
|
13
|
+
mind_content: base.mind_content,
|
|
14
|
+
mind_content_plain_text: base.mind_content_plain_text,
|
|
15
|
+
};
|
|
16
|
+
if (title !== undefined) {
|
|
17
|
+
info.title = title;
|
|
18
|
+
}
|
|
19
|
+
const entries = Object.entries(info).filter(([, v]) => v !== undefined && v !== "");
|
|
20
|
+
if (entries.length === 0)
|
|
21
|
+
return undefined;
|
|
22
|
+
return JSON.stringify(Object.fromEntries(entries));
|
|
23
|
+
}
|