Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

Add Evernote import flow

tianma16dce39fcf65
diff --git a/README.md b/README.md
index f6c5aebf..63106d4c 100644
--- a/README.md
+++ b/README.md
@@ -171,6 +171,8 @@ bun run cli -- --profile prod search edgeever
bun run cli -- --profile prod export <memo-id> --format markdown --out ./memo.md
```
+自托管管理员或开发者从印象笔记迁移到 EdgeEver 时,可以按笔记本分别导出 `.notes` 或 `.enex` 文件,再使用 MCP 导入工具逐个笔记本确认结果。普通产品用户更适合使用应用内导入入口。详见:[从印象笔记迁移到 EdgeEver](docs/evernote-migration.md)。
+
## 图片压缩规则
图片压缩以减少大图体积为目标,不会强制重压所有图片。原图较小、已是 WebP 且体积不大,或压缩后收益不明显时,会保留原图,避免影响截图、文字和笔记内容的清晰度。
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 29c31484..7730d045 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -1763,6 +1763,8 @@ const MCP_TOOLS = [
title: { type: "string" },
contentMarkdown: { type: "string" },
tags: { type: "array", items: { type: "string" } },
+ createdAt: { type: "string", format: "date-time" },
+ updatedAt: { type: "string", format: "date-time" },
},
},
},
@@ -1781,6 +1783,8 @@ const MCP_TOOLS = [
tags: { type: "array", items: { type: "string" } },
notebookId: { type: "string" },
expectedRevision: { type: "integer", minimum: 0 },
+ createdAt: { type: "string", format: "date-time" },
+ updatedAt: { type: "string", format: "date-time" },
},
},
},
diff --git a/apps/web/src/components/EvernoteImportCard.tsx b/apps/web/src/components/EvernoteImportCard.tsx
new file mode 100644
index 00000000..1e12f39c
--- /dev/null
+++ b/apps/web/src/components/EvernoteImportCard.tsx
@@ -0,0 +1,254 @@
+import { useMemo, useRef, useState, type ChangeEvent } from "react";
+import { FileArchive, FileCheck2, Play, RotateCcw, UploadCloud } from "lucide-react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { api } from "@/lib/api";
+import { cn } from "@/lib/utils";
+import { parseEvernoteExportFiles, type EvernoteImportNotebook } from "@/lib/evernote-import";
+
+type ImportPhase = "idle" | "planned" | "importing" | "awaiting-confirmation" | "done" | "error";
+
+type ImportedNotebookSummary = {
+ name: string;
+ createdCount: number;
+};
+
+export const EvernoteImportCard = () => {
+ const queryClient = useQueryClient();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [phase, setPhase] = useState<ImportPhase>("idle");
+ const [notebooks, setNotebooks] = useState<EvernoteImportNotebook[]>([]);
+ const [currentIndex, setCurrentIndex] = useState(0);
+ const [currentMemoIndex, setCurrentMemoIndex] = useState(0);
+ const [error, setError] = useState<string | null>(null);
+ const [imported, setImported] = useState<ImportedNotebookSummary[]>([]);
+
+ const totalNotes = useMemo(
+ () => notebooks.reduce((sum, notebook) => sum + notebook.notes.length, 0),
+ [notebooks]
+ );
+ const currentNotebook = notebooks[currentIndex] ?? null;
+ const importedNoteCount = imported.reduce((sum, item) => sum + item.createdCount, 0);
+ const progressLabel =
+ phase === "importing" && currentNotebook
+ ? `${currentNotebook.name}:${currentMemoIndex}/${currentNotebook.notes.length}`
+ : imported.length > 0
+ ? `已导入 ${importedNoteCount}/${totalNotes} 条笔记`
+ : "等待选择导出文件";
+
+ const handleFilesChange = async (event: ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(event.target.files || []);
+ setError(null);
+ setImported([]);
+ setCurrentIndex(0);
+ setCurrentMemoIndex(0);
+
+ try {
+ const parsed = await parseEvernoteExportFiles(files);
+
+ if (parsed.length === 0) {
+ throw new Error("请选择 .notes 或 .enex 文件。");
+ }
+
+ setNotebooks(parsed);
+ setPhase("planned");
+ } catch (parseError) {
+ setNotebooks([]);
+ setPhase("error");
+ setError(parseError instanceof Error ? parseError.message : "解析印象笔记导出文件失败。");
+ }
+ };
+
+ const reset = () => {
+ setPhase("idle");
+ setNotebooks([]);
+ setCurrentIndex(0);
+ setCurrentMemoIndex(0);
+ setError(null);
+ setImported([]);
+
+ if (inputRef.current) {
+ inputRef.current.value = "";
+ }
+ };
+
+ const importNotebook = async (index: number) => {
+ const notebook = notebooks[index];
+
+ if (!notebook) {
+ return;
+ }
+
+ setPhase("importing");
+ setError(null);
+ setCurrentIndex(index);
+ setCurrentMemoIndex(0);
+
+ try {
+ const existingNotebooks = (await api.listNotebooks()).notebooks;
+ const targetNotebook =
+ existingNotebooks.find((item) => item.parentId === null && item.name === notebook.name) ??
+ (await api.createNotebook({ name: notebook.name, parentId: null })).notebook;
+ let createdCount = 0;
+
+ for (const note of notebook.notes) {
+ const result = await api.createMemo({
+ notebookId: targetNotebook.id,
+ title: note.title,
+ contentMarkdown: note.markdown,
+ tags: note.tags,
+ createdAt: note.createdAt,
+ updatedAt: note.updatedAt,
+ });
+
+ if (result.memo.createdAt !== note.createdAt || result.memo.updatedAt !== note.updatedAt) {
+ throw new Error(`「${note.title}」导入后的创建时间或修改时间与印象笔记原始时间不一致。`);
+ }
+
+ createdCount += 1;
+ setCurrentMemoIndex(createdCount);
+ }
+
+ setImported((items) => [...items, { name: notebook.name, createdCount }]);
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["notebooks"] }),
+ queryClient.invalidateQueries({ queryKey: ["memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["tags"] }),
+ ]);
+ setPhase(index < notebooks.length - 1 ? "awaiting-confirmation" : "done");
+ } catch (importError) {
+ setPhase("error");
+ setError(importError instanceof Error ? importError.message : "导入失败。");
+ }
+ };
+
+ const continueImport = () => {
+ void importNotebook(currentIndex + 1);
+ };
+
+ return (
+ <Card className="hidden w-full min-w-0 overflow-hidden shadow-none lg:block">
+ <CardHeader className="p-4">
+ <CardTitle className="flex items-center gap-2 text-sm">
+ <UploadCloud className="h-4 w-4 text-emerald-700" />
+ 导入印象笔记
+ </CardTitle>
+ <CardDescription className="text-xs leading-4">
+ 按笔记本选择 .notes 或 .enex 文件,EdgeEver 会逐个笔记本导入并保留原始创建、修改时间。
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4 p-4 pt-0">
+ <div className="flex min-h-16 items-center gap-3 rounded-lg border border-dashed border-slate-200 bg-slate-50/70 p-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-white text-emerald-700">
+ <FileArchive className="h-5 w-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-semibold text-slate-900">{progressLabel}</div>
+ <div className="mt-0.5 truncate text-xs font-medium text-slate-500">
+ 每个文件会作为一个同名根笔记本导入,导完一个后需要确认再继续。
+ </div>
+ </div>
+ <input
+ ref={inputRef}
+ className="hidden"
+ type="file"
+ accept=".notes,.enex"
+ multiple
+ onChange={(event) => void handleFilesChange(event)}
+ />
+ <Button
+ size="md"
+ variant="outline"
+ className="h-9 shrink-0 bg-white"
+ type="button"
+ disabled={phase === "importing"}
+ onClick={() => inputRef.current?.click()}
+ >
+ <UploadCloud className="h-4 w-4" />
+ 选择文件
+ </Button>
+ </div>
+
+ {notebooks.length > 0 && (
+ <div className="overflow-hidden rounded-lg border border-slate-100">
+ <div className="grid grid-cols-[1fr_7rem] bg-slate-50 px-3 py-2 text-xs font-bold text-slate-500">
+ <span>笔记本</span>
+ <span className="text-right">笔记数</span>
+ </div>
+ <div className="max-h-52 overflow-auto">
+ {notebooks.map((notebook, index) => {
+ const state =
+ imported[index] ? "done" : index === currentIndex && phase === "importing" ? "importing" : "pending";
+
+ return (
+ <div
+ key={`${notebook.fileName}-${index}`}
+ className="grid min-h-10 grid-cols-[1fr_7rem] items-center border-t border-slate-100 px-3 py-2 text-sm"
+ >
+ <span className="min-w-0 truncate font-semibold text-slate-800" title={notebook.fileName}>
+ {state === "done" && <FileCheck2 className="mr-1.5 inline h-4 w-4 text-emerald-600" />}
+ {notebook.name}
+ </span>
+ <span
+ className={cn(
+ "text-right text-xs font-bold",
+ state === "done" ? "text-emerald-700" : state === "importing" ? "text-slate-900" : "text-slate-500"
+ )}
+ >
+ {notebook.notes.length}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <div className="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm font-medium text-rose-700">
+ {error}
+ </div>
+ )}
+
+ <div className="flex flex-wrap justify-end gap-2">
+ {(phase === "planned" || phase === "error" || phase === "done" || phase === "awaiting-confirmation") && notebooks.length > 0 && (
+ <Button size="md" variant="ghost" className="h-9" type="button" onClick={reset}>
+ <RotateCcw className="h-4 w-4" />
+ 重新选择
+ </Button>
+ )}
+ {phase === "planned" && (
+ <Button
+ size="md"
+ variant="solid"
+ className="h-9 bg-emerald-600 text-white hover:bg-emerald-700"
+ type="button"
+ onClick={() => void importNotebook(0)}
+ >
+ <Play className="h-4 w-4" />
+ 开始导入
+ </Button>
+ )}
+ {phase === "awaiting-confirmation" && (
+ <Button
+ size="md"
+ variant="solid"
+ className="h-9 bg-emerald-600 text-white hover:bg-emerald-700"
+ type="button"
+ onClick={continueImport}
+ >
+ <Play className="h-4 w-4" />
+ 确认结果,继续下一个
+ </Button>
+ )}
+ {phase === "importing" && (
+ <Button size="md" variant="outline" className="h-9 bg-white" type="button" disabled>
+ 正在导入
+ </Button>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ );
+};
diff --git a/apps/web/src/components/SettingsPane.tsx b/apps/web/src/components/SettingsPane.tsx
index a8c46465..679adb2d 100644
--- a/apps/web/src/components/SettingsPane.tsx
+++ b/apps/web/src/components/SettingsPane.tsx
@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/switch";
import { api } from "@/lib/api";
import { cn, formatDateTime } from "@/lib/utils";
import { AppConfirmDialog } from "./dialogs/ConfirmDialogs";
+import { EvernoteImportCard } from "./EvernoteImportCard";
const ALL_TOKEN_SCOPES = [
"read:notebooks",
@@ -602,6 +603,7 @@ export const SettingsPane = ({
imageCompressionEnabled={imageCompressionEnabled}
onImageCompressionChange={onImageCompressionChange}
/>
+ <EvernoteImportCard />
<TokenCard
name={name}
onNameChange={setName}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index fc716bea..f4bd23c7 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -172,7 +172,7 @@ export const api = {
return request<ListMemosResponse>(`/api/v1/memos?${search.toString()}`);
},
- createMemo: (payload: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[] }) =>
+ createMemo: (payload: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[]; createdAt?: string; updatedAt?: string }) =>
request<MemoResponse>("/api/v1/memos", {
method: "POST",
body: JSON.stringify(payload),
diff --git a/apps/web/src/lib/evernote-import.ts b/apps/web/src/lib/evernote-import.ts
new file mode 100644
index 00000000..726e9fab
--- /dev/null
+++ b/apps/web/src/lib/evernote-import.ts
@@ -0,0 +1,169 @@
+import { XMLParser } from "fast-xml-parser";
+import TurndownService from "turndown";
+
+export type EvernoteImportNote = {
+ title: string;
+ markdown: string;
+ tags: string[];
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type EvernoteImportNotebook = {
+ name: string;
+ fileName: string;
+ notes: EvernoteImportNote[];
+};
+
+export const parseEvernoteExportFiles = async (files: File[]): Promise<EvernoteImportNotebook[]> => {
+ const notebooks: EvernoteImportNotebook[] = [];
+
+ for (const file of files.filter(isSupportedEvernoteExportFile).sort((a, b) => a.name.localeCompare(b.name, "zh-Hans-CN"))) {
+ const xml = await file.text();
+ assertReadableEvernoteXml(xml, file.name);
+ notebooks.push({
+ name: notebookNameFromFile(file.name),
+ fileName: file.name,
+ notes: parseEvernoteXml(xml, file.name),
+ });
+ }
+
+ return notebooks;
+};
+
+export const isSupportedEvernoteExportFile = (file: File) => {
+ const normalized = file.name.toLowerCase();
+ return normalized.endsWith(".notes") || normalized.endsWith(".enex");
+};
+
+const parseEvernoteXml = (xml: string, fileName: string): EvernoteImportNote[] => {
+ const parser = new XMLParser({
+ ignoreAttributes: false,
+ parseTagValue: false,
+ trimValues: false,
+ cdataPropName: "__cdata",
+ isArray: (_, jpath) => jpath === "en-export.note" || jpath === "en-export.note.tag",
+ });
+ const parsed = parser.parse(xml);
+ const notes = parsed?.["en-export"]?.note || [];
+
+ if (!Array.isArray(notes)) {
+ throw new Error(`${fileName} 中没有找到可导入的笔记。`);
+ }
+
+ return notes.map((note, index) => normalizeNote(note, index, fileName));
+};
+
+const normalizeNote = (note: unknown, index: number, fileName: string): EvernoteImportNote => {
+ const current = note && typeof note === "object" ? (note as Record<string, unknown>) : {};
+ const title = getText(current.title).trim() || `Untitled ${index + 1}`;
+ const content = getText(current.content);
+ const createdAt = enexDateToIso(getText(current.created));
+ const updatedAt = enexDateToIso(getText(current.updated));
+ const tags = Array.isArray(current.tag)
+ ? current.tag.map((tag) => getText(tag).trim()).filter(Boolean)
+ : [];
+
+ if (!createdAt || !updatedAt) {
+ throw new Error(`${fileName} 中的「${title}」缺少合法的创建时间或修改时间。`);
+ }
+
+ return {
+ title: title.slice(0, 160),
+ markdown: evernoteContentToMarkdown(content),
+ tags,
+ createdAt,
+ updatedAt,
+ };
+};
+
+const evernoteContentToMarkdown = (content: string) => {
+ const body = content
+ .replace(/<\?xml[\s\S]*?\?>/i, "")
+ .replace(/<!DOCTYPE[\s\S]*?>/i, "")
+ .trim();
+ const turndown = new TurndownService({
+ headingStyle: "atx",
+ bulletListMarker: "-",
+ codeBlockStyle: "fenced",
+ });
+
+ turndown.addRule("evernoteTodo", {
+ filter: (node) => node.nodeName.toLowerCase() === "en-todo",
+ replacement: (_, node) => {
+ const element = node as HTMLElement;
+ const checked = element.getAttribute("checked") === "true" || element.getAttribute("checked") === "checked";
+ return checked ? "[x] " : "[ ] ";
+ },
+ });
+
+ turndown.addRule("evernoteCrypt", {
+ filter: (node) => node.nodeName.toLowerCase() === "en-crypt",
+ replacement: () => "[Encrypted Evernote content]",
+ });
+
+ turndown.addRule("evernoteMedia", {
+ filter: (node) => node.nodeName.toLowerCase() === "en-media",
+ replacement: (_, node) => {
+ const element = node as HTMLElement;
+ const type = element.getAttribute("type") || "attachment";
+ const hash = element.getAttribute("hash") || "unknown";
+
+ return type.startsWith("image/")
+ ? `\n\n![Evernote image ${hash}](evernote-resource:${hash})\n\n`
+ : `\n\n[Evernote attachment ${hash}](evernote-resource:${hash})\n\n`;
+ },
+ });
+
+ return turndown
+ .turndown(body || "")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+};
+
+const assertReadableEvernoteXml = (xml: string, fileName: string) => {
+ if (/encoding\s*=\s*["']base64:aes["']/i.test(xml)) {
+ throw new Error(`${fileName} 是加密 .notes 文件,EdgeEver 不能直接读取其中内容。请改用未加密导出、HTML 导出,或先转换为可读的 ENEX/Markdown。`);
+ }
+
+ if (!/<en-export[\s>]/i.test(xml) || !/<note[\s>]/i.test(xml)) {
+ throw new Error(`${fileName} 看起来不是可读取的印象笔记 XML 导出文件。`);
+ }
+};
+
+const getText = (value: unknown): string => {
+ if (value === undefined || value === null) {
+ return "";
+ }
+
+ if (typeof value === "string") {
+ return value;
+ }
+
+ if (typeof value === "object") {
+ const current = value as Record<string, unknown>;
+ return typeof current.__cdata === "string"
+ ? current.__cdata
+ : typeof current["#text"] === "string"
+ ? current["#text"]
+ : "";
+ }
+
+ return String(value);
+};
+
+const enexDateToIso = (value: string) => {
+ const match = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(value || "");
+
+ if (!match) {
+ return undefined;
+ }
+
+ return `${match[1]}-${match[2]}-${match[3]}T${match[4]}:${match[5]}:${match[6]}.000Z`;
+};
+
+const notebookNameFromFile = (fileName: string) =>
+ fileName
+ .replace(/\.(notes|enex)$/i, "")
+ .trim()
+ .slice(0, 80) || "Evernote Import";
diff --git a/bun.lock b/bun.lock
index 3341c1e0..09307dc2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -25,12 +25,14 @@
"clsx": "latest",
"cmdk": "^1.1.1",
"dexie": "latest",
+ "fast-xml-parser": "^5.9.3",
"hono": "latest",
"lucide-react": "latest",
"react": "latest",
"react-dom": "latest",
"tailwind-merge": "latest",
"tailwindcss-animate": "^1.0.7",
+ "turndown": "^7.2.4",
"vaul": "^1.1.2",
"workbox-window": "^7.4.1",
"zod": "latest",
@@ -40,6 +42,7 @@
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
+ "@types/turndown": "^5.0.6",
"@vitejs/plugin-react": "latest",
"autoprefixer": "latest",
"concurrently": "latest",
@@ -407,8 +410,12 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
+ "@mixmark-io/domino": ["@mixmark-io/[email protected]", "", {}, "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="],
+
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="],
+ "@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="],
+
"@nodelib/fs.scandir": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
"@nodelib/fs.stat": ["@nodelib/[email protected]", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="],
@@ -673,6 +680,8 @@
"@types/trusted-types": ["@types/[email protected]", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
+ "@types/turndown": ["@types/[email protected]", "", {}, "sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg=="],
+
"@types/use-sync-external-store": ["@types/[email protected]", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="],
@@ -689,6 +698,8 @@
"anymatch": ["[email protected]", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="],
+ "anynum": ["[email protected]", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="],
+
"arg": ["[email protected]", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="],
"aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
@@ -839,6 +850,10 @@
"fast-uri": ["[email protected]", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
+ "fast-xml-builder": ["[email protected]", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="],
+
+ "fast-xml-parser": ["[email protected]", "", { "dependencies": { "@nodable/entities": "^2.2.0", "fast-xml-builder": "^1.2.0", "is-unsafe": "^1.0.1", "path-expression-matcher": "^1.5.0", "strnum": "^2.4.1", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-brCNCeScma/kqa54J4PIDriSSSLssRkuYaUCpvHJulGc3HGI/xxKUCTDcYkAdqJsyb//ydpbxecjC3hB9+tb/g=="],
+
"fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
@@ -965,6 +980,8 @@
"is-typed-array": ["[email protected]", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="],
+ "is-unsafe": ["[email protected]", "", {}, "sha512-CLK2+VdgERgD96EYm5lUQssZYlRg2tkZnbsxZoacmSiRxiFJ4Nk4SzjCl+Ur+v3kXIY9dTIdb3IH22y1mZ56LA=="],
+
"is-weakmap": ["[email protected]", "", {}, "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w=="],
"is-weakref": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3" } }, "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew=="],
@@ -1075,6 +1092,8 @@
"package-json-from-dist": ["[email protected]", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="],
+ "path-expression-matcher": ["[email protected]", "", {}, "sha512-h7bxdzhHk8Knyc4Tj+jMaa7fEEoUJy7p1qtbVgkYg1Uhpe5Np5VuGXCRZnkZvU+Q42M1vStt0ifa3ueykRJPmQ=="],
+
"path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-parse": ["[email protected]", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="],
@@ -1247,6 +1266,8 @@
"strip-comments": ["[email protected]", "", {}, "sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw=="],
+ "strnum": ["[email protected]", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg=="],
+
"sucrase": ["[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", "tinyglobby": "^0.2.11", "ts-interface-checker": "^0.1.9" }, "bin": { "sucrase": "bin/sucrase", "sucrase-node": "bin/sucrase-node" } }, "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw=="],
"supports-color": ["[email protected]", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
@@ -1281,6 +1302,8 @@
"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+ "turndown": ["[email protected]", "", { "dependencies": { "@mixmark-io/domino": "^2.2.0" } }, "sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ=="],
+
"type-fest": ["[email protected]", "", {}, "sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg=="],
"typed-array-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-typed-array": "^1.1.14" } }, "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw=="],
@@ -1387,6 +1410,8 @@
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],
+ "xml-naming": ["[email protected]", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="],
+
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
diff --git a/docs/evernote-migration.md b/docs/evernote-migration.md
new file mode 100644
index 00000000..460a313e
--- /dev/null
+++ b/docs/evernote-migration.md
@@ -0,0 +1,129 @@
+# 从印象笔记迁移到 EdgeEver
+
+本文档说明如何把印象笔记笔记按笔记本逐个迁移到 EdgeEver。迁移工具通过 EdgeEver MCP 写入数据,适合需要可检查、可暂停、可回滚节奏的迁移场景。
+
+普通产品用户可以直接在 EdgeEver Web 应用的 PC 端设置页中导入,不需要克隆 EdgeEver 源码仓库。仓库内脚本主要面向自托管管理员、开发者和需要命令行批处理的高级用户。
+
+## 迁移前准备
+
+如果你是普通产品用户,请在电脑浏览器中打开 EdgeEver,进入左侧“个人中心 / 我的”,使用“导入印象笔记”入口。移动端不开放该入口,因为 `.notes` 文件通常较大,且逐笔记本确认更适合 PC 操作。
+
+1. 在 EdgeEver 左侧设置里创建一个 API Token。
+2. Token 至少需要这些 scopes:
+ - `read:notebooks`
+ - `write:notebooks`
+ - `write:memos`
+3. 在印象笔记客户端中按笔记本分别导出 `.notes` 文件。如果你的客户端仍支持 `.enex`,也可以使用 `.enex`。
+4. 把所有 `.notes` 或 `.enex` 文件放到同一个目录,文件名会作为 EdgeEver 笔记本名称,例如:
+
+```text
+evernote-export/
+ 工作项目.notes
+ 学习资料.notes
+ 生活记录.notes
+```
+
+建议一次只迁移一个账号的数据。迁移前保留原始 `.notes` / `.enex` 文件,不要在导入完成前删除印象笔记中的原笔记。
+
+## 在 Web 应用中导入
+
+1. 在电脑浏览器中打开 EdgeEver。
+2. 进入左侧“个人中心 / 我的”。
+3. 找到“导入印象笔记”。
+4. 选择一个或多个 `.notes` / `.enex` 文件。
+5. 检查导入计划中的笔记本数量和笔记数量。
+6. 点击“开始导入”。
+7. 每导完一个笔记本,先在 EdgeEver 中检查结果,再点击“确认结果,继续下一个”。
+
+Web 导入会强制校验时间字段:如果导出文件中某条笔记缺少合法的创建时间或更新时间,导入会停止;如果 EdgeEver 创建后的 `createdAt` 或 `updatedAt` 与印象笔记原始时间不一致,导入也会停止并显示对应笔记标题。
+
+## 使用命令行脚本
+
+命令行脚本适合自托管管理员或开发者批量处理迁移。普通产品用户优先使用上面的 Web 导入入口。
+
+本节命令需要在 EdgeEver 项目源码目录中运行,并且本机已经安装 Bun。这是当前自托管/开发者迁移工具的要求,不是长期面向普通用户的理想交互。
+
+可以直接使用环境变量:
+
+```sh
+EDGEEVER_URL=https://你的域名 \
+EDGEEVER_TOKEN=<api-token> \
+bun run import:evernote -- --input ./evernote-export --dry-run
+```
+
+也可以先保存为本机 profile:
+
+```sh
+bun run cli -- profile set prod --url https://你的域名 --token <api-token>
+bun run import:evernote -- --profile prod --input ./evernote-export --dry-run
+```
+
+## 先生成导入计划
+
+正式导入前先 dry-run:
+
+```sh
+bun run import:evernote -- --profile prod --input ./evernote-export --dry-run
+```
+
+检查输出里的笔记本数量、笔记数量和导出文件路径是否符合预期。如果发现笔记本名称不对,先修改导出文件名再重新 dry-run。
+
+如果 dry-run 提示 `encoding="base64:aes"`,说明这个 `.notes` 文件是印象笔记加密导出文件,EdgeEver 不能直接读取其中内容。此时不要正式导入,改用未加密导出、HTML 导出,或使用可信的备份/转换工具先转换为可读的 ENEX/Markdown,并确认转换结果仍保留原始创建时间和更新时间。
+
+## 正式导入
+
+确认计划无误后执行:
+
+```sh
+bun run import:evernote -- --profile prod --input ./evernote-export
+```
+
+导入流程会按文件名排序逐个处理笔记本:
+
+1. 如果 EdgeEver 已有同名根笔记本,工具会复用它。
+2. 如果没有同名根笔记本,工具会创建新笔记本。
+3. 工具逐条创建笔记,并保留标题、Markdown 内容、标签、创建时间和更新时间。
+4. 每导完一个笔记本,工具会输出本次创建条数和该笔记本的计数变化。
+5. 你需要打开 EdgeEver 检查结果,然后在终端输入 `yes` 才会继续下一个笔记本。
+
+如果检查结果不符合预期,不要输入 `yes`。工具会停止,已经导入的笔记会保留在 EdgeEver 中,方便你先检查或手动清理。
+
+迁移工具会强制校验时间字段:如果导出文件中某条笔记缺少合法的创建时间或更新时间,导入会停止;如果 EdgeEver 创建后的 `createdAt` 或 `updatedAt` 与印象笔记原始时间不一致,导入也会停止并显示对应笔记标题。
+
+## 无人值守导入
+
+如果已经在测试环境验证过,也可以跳过每个笔记本后的确认:
+
+```sh
+bun run import:evernote -- --profile prod --input ./evernote-export --yes
+```
+
+不建议第一次迁移时使用 `--yes`。
+
+## 附件和图片说明
+
+当前迁移工具主要迁移笔记文本内容、标题、标签和时间。印象笔记导出文件中的图片和附件会被转换成 `evernote-resource:<hash>` 形式的占位链接,便于后续定位原始资源。
+
+建议处理方式:
+
+1. 先完成文本迁移,确认笔记数量和主要内容无误。
+2. 保留原始 `.notes` / `.enex` 文件作为附件来源。
+3. 对重要笔记中的图片或附件,后续可通过 EdgeEver 的资源上传能力补传到对应笔记。
+
+## 常见问题
+
+### 导入中断了怎么办?
+
+重新运行同一条命令即可。工具会复用同名根笔记本,但不会自动去重已经导入过的笔记。为了避免重复,建议先在 EdgeEver 中检查最后一个已导入笔记本,必要时手动清理后再继续。
+
+### 为什么要求一个笔记本一个导出文件?
+
+印象笔记导出文件本身不稳定携带原始笔记本层级。用“一个笔记本一个导出文件”的方式,可以让文件名成为明确的目标笔记本名称,也方便每导完一个笔记本后人工确认。
+
+### 能保留印象笔记的创建和更新时间吗?
+
+必须保留。迁移工具会读取导出文件中的 `created` 和 `updated` 字段,并通过 EdgeEver MCP 写入 `createdAt` 和 `updatedAt`。工具还会在每条笔记创建后校验 EdgeEver 返回的时间;只要创建时间或更新时间不一致,就会停止导入,避免继续写入有问题的数据。
+
+### 笔记格式会完全一致吗?
+
+不会完全一致。工具会把印象笔记的 XHTML 内容转换为 Markdown,再交给 EdgeEver 保存。常规标题、段落、列表、代码块、链接和待办项会尽量保留;复杂表格、加密块、特殊样式和附件需要迁移后抽查。
diff --git a/package.json b/package.json
index 0b91130a..b7895bf7 100644
--- a/package.json
+++ b/package.json
@@ -23,6 +23,7 @@
"db:migrate:remote": "bun scripts/run-wrangler.mjs d1 migrations apply DB --remote",
"auth:hash": "bun scripts/hash-password.mjs",
"cli": "bun scripts/edgeever.mjs",
+ "import:evernote": "bun scripts/import-evernote-enex-via-mcp.mjs",
"mcp:stdio": "bun scripts/edgeever-mcp-stdio.mjs",
"deploy": "bun run build && bun run db:migrate:remote && bun scripts/run-wrangler.mjs deploy",
"deploy:tianma": "EDGE_EVER_INSTANCE=tianma bun run deploy",
@@ -63,12 +64,14 @@
"clsx": "latest",
"cmdk": "^1.1.1",
"dexie": "latest",
+ "fast-xml-parser": "^5.9.3",
"hono": "latest",
"lucide-react": "latest",
"react": "latest",
"react-dom": "latest",
"tailwind-merge": "latest",
"tailwindcss-animate": "^1.0.7",
+ "turndown": "^7.2.4",
"vaul": "^1.1.2",
"workbox-window": "^7.4.1",
"zod": "latest"
@@ -78,6 +81,7 @@
"@types/node": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
+ "@types/turndown": "^5.0.6",
"@vitejs/plugin-react": "latest",
"autoprefixer": "latest",
"concurrently": "latest",
diff --git a/scripts/import-evernote-enex-via-mcp.mjs b/scripts/import-evernote-enex-via-mcp.mjs
new file mode 100644
index 00000000..3a84c514
--- /dev/null
+++ b/scripts/import-evernote-enex-via-mcp.mjs
@@ -0,0 +1,420 @@
+#!/usr/bin/env bun
+
+import { createInterface } from "node:readline/promises";
+import { stdin as input, stdout as output } from "node:process";
+import { readdir, readFile } from "node:fs/promises";
+import { basename, extname, join } from "node:path";
+import { homedir } from "node:os";
+import { XMLParser } from "fast-xml-parser";
+import TurndownService from "turndown";
+
+const CONFIG_PATH = process.env.EDGEEVER_CONFIG || join(homedir(), ".edgeever", "config.json");
+const DEFAULT_URL = "http://127.0.0.1:8787";
+const options = parseOptions(process.argv.slice(2));
+
+const usage = `Import Evernote ENEX/NOTES files into EdgeEver through MCP.
+
+Usage:
+ EDGEEVER_URL=https://your.edgeever.host EDGEEVER_TOKEN=... \\
+ bun scripts/import-evernote-enex-via-mcp.mjs --input ./evernote-export
+
+ bun scripts/import-evernote-enex-via-mcp.mjs --profile prod --input ./evernote-export --dry-run
+
+Options:
+ --input <path> ENEX/NOTES file or a directory containing one export file per notebook.
+ --profile <name> Read URL and token from ~/.edgeever/config.json.
+ --dry-run Parse and print the plan without writing to EdgeEver.
+ --yes Import all notebooks without interactive confirmations.
+`;
+
+if (options.help || options.h) {
+ console.log(usage);
+ process.exit(0);
+}
+
+const inputPath = requireValue(options.input, "--input");
+const dryRun = Boolean(options["dry-run"]);
+const assumeYes = Boolean(options.yes);
+const readline = assumeYes ? null : createInterface({ input, output });
+
+try {
+ await main();
+} catch (error) {
+ console.error(error instanceof Error ? error.message : error);
+ process.exit(1);
+} finally {
+ readline?.close();
+}
+
+async function main() {
+ const client = dryRun ? null : await createMcpClient(options.profile);
+ const notebooks = await readEnexNotebooks(inputPath);
+
+ if (notebooks.length === 0) {
+ throw new Error(`No .enex or .notes files found: ${inputPath}`);
+ }
+
+ printPlan(notebooks);
+
+ if (dryRun) {
+ process.exit(0);
+ }
+
+ if (!assumeYes) {
+ await confirmOrExit("Start importing the first notebook? Type yes to continue: ");
+ }
+
+ let importedNotebookCount = 0;
+ let importedMemoCount = 0;
+
+ for (const [index, notebook] of notebooks.entries()) {
+ console.log(`\n[${index + 1}/${notebooks.length}] Importing notebook: ${notebook.name}`);
+ const before = await mcpCall(client, "list_notebooks", {});
+ const targetNotebook = await findOrCreateNotebook(client, before.notebooks || [], notebook.name, index);
+ const beforeMemoCount = Number(targetNotebook.memoCount || 0);
+ const createdMemoIds = [];
+
+ for (const [memoIndex, note] of notebook.notes.entries()) {
+ const result = await mcpCall(client, "create_memo", {
+ notebookId: targetNotebook.id,
+ title: note.title,
+ contentMarkdown: note.markdown,
+ tags: note.tags,
+ createdAt: note.createdAt,
+ updatedAt: note.updatedAt,
+ });
+
+ assertImportedMemoTimestamps(result.memo, note);
+ createdMemoIds.push(result.memo.id);
+ console.log(` ${memoIndex + 1}/${notebook.notes.length} ${note.title || "Untitled"}`);
+ }
+
+ const after = await mcpCall(client, "list_notebooks", {});
+ const verifiedNotebook = (after.notebooks || []).find((item) => item.id === targetNotebook.id);
+ const afterMemoCount = Number(verifiedNotebook?.memoCount || 0);
+ const delta = afterMemoCount - beforeMemoCount;
+
+ importedNotebookCount += 1;
+ importedMemoCount += createdMemoIds.length;
+
+ console.log(`\nNotebook imported: ${notebook.name}`);
+ console.log(` Created memos: ${createdMemoIds.length}`);
+ console.log(` Notebook memo count before: ${beforeMemoCount}`);
+ console.log(` Notebook memo count after: ${afterMemoCount}`);
+
+ if (delta !== createdMemoIds.length) {
+ console.log(` Warning: memo count delta is ${delta}, expected ${createdMemoIds.length}. Check for concurrent edits or retries.`);
+ }
+
+ if (!assumeYes && index < notebooks.length - 1) {
+ const answer = await readline.question("Review the result in EdgeEver. Continue with the next notebook? Type yes, or anything else to stop: ");
+
+ if (answer.trim().toLowerCase() !== "yes") {
+ console.log("Stopped by user confirmation.");
+ break;
+ }
+ }
+ }
+
+ console.log(`\nDone. Imported notebooks: ${importedNotebookCount}; imported memos: ${importedMemoCount}.`);
+}
+
+async function readEnexNotebooks(path) {
+ const files = await listEnexFiles(path);
+ const notebooks = [];
+
+ for (const filePath of files) {
+ const notes = await parseEnex(filePath);
+ notebooks.push({
+ name: notebookNameFromFile(filePath),
+ filePath,
+ notes,
+ });
+ }
+
+ return notebooks;
+}
+
+async function listEnexFiles(path) {
+ if (path.toLowerCase().endsWith(".enex")) {
+ return [path];
+ }
+
+ if (path.toLowerCase().endsWith(".notes")) {
+ return [path];
+ }
+
+ const entries = await readdir(path, { withFileTypes: true });
+ return entries
+ .filter((entry) => entry.isFile() && isSupportedExportFile(entry.name))
+ .map((entry) => join(path, entry.name))
+ .sort((a, b) => a.localeCompare(b, "zh-Hans-CN"));
+}
+
+async function parseEnex(filePath) {
+ const xml = await readFile(filePath, "utf8");
+ assertReadableEvernoteXml(xml, filePath);
+
+ const parser = new XMLParser({
+ ignoreAttributes: false,
+ parseTagValue: false,
+ trimValues: false,
+ cdataPropName: "__cdata",
+ isArray: (_, jpath) => jpath === "en-export.note" || jpath === "en-export.note.tag",
+ });
+ const parsed = parser.parse(xml);
+ const notes = parsed?.["en-export"]?.note || [];
+
+ return notes.map((note, index) => normalizeNote(note, index));
+}
+
+function isSupportedExportFile(filePath) {
+ const normalized = filePath.toLowerCase();
+ return normalized.endsWith(".enex") || normalized.endsWith(".notes");
+}
+
+function assertReadableEvernoteXml(xml, filePath) {
+ if (/encoding\s*=\s*["']base64:aes["']/i.test(xml)) {
+ throw new Error(
+ `${filePath} is an encrypted .notes export (encoding="base64:aes"). EdgeEver cannot import encrypted NOTES files because Yinxiang has not published the decryption key. Export an unencrypted NOTES/ENEX file, export HTML, or use a trusted backup/export tool that can produce ENEX/Markdown with original timestamps.`
+ );
+ }
+
+ if (!/<en-export[\s>]/i.test(xml) || !/<note[\s>]/i.test(xml)) {
+ throw new Error(`${filePath} does not look like a readable Evernote XML export.`);
+ }
+}
+
+function normalizeNote(note, index) {
+ const title = getText(note.title)?.trim() || `Untitled ${index + 1}`;
+ const content = getText(note.content) || "";
+ const createdAt = enexDateToIso(getText(note.created));
+ const updatedAt = enexDateToIso(getText(note.updated));
+ const tags = Array.isArray(note.tag)
+ ? note.tag.map((tag) => getText(tag)?.trim()).filter(Boolean)
+ : [];
+
+ if (!createdAt || !updatedAt) {
+ throw new Error(`Note "${title}" is missing a valid Evernote created/updated timestamp.`);
+ }
+
+ return {
+ title: title.slice(0, 160),
+ markdown: enexContentToMarkdown(content),
+ tags,
+ createdAt,
+ updatedAt,
+ };
+}
+
+function assertImportedMemoTimestamps(memo, note) {
+ if (memo.createdAt !== note.createdAt || memo.updatedAt !== note.updatedAt) {
+ throw new Error(
+ `Timestamp mismatch for "${note.title}". Expected createdAt=${note.createdAt}, updatedAt=${note.updatedAt}; got createdAt=${memo.createdAt}, updatedAt=${memo.updatedAt}.`
+ );
+ }
+}
+
+function enexContentToMarkdown(content) {
+ const body = content
+ .replace(/<\?xml[\s\S]*?\?>/i, "")
+ .replace(/<!DOCTYPE[\s\S]*?>/i, "")
+ .trim();
+ const turndown = new TurndownService({
+ headingStyle: "atx",
+ bulletListMarker: "-",
+ codeBlockStyle: "fenced",
+ });
+
+ turndown.addRule("evernoteTodo", {
+ filter: "en-todo",
+ replacement: (_, node) => {
+ const checked = node.getAttribute("checked") === "true" || node.getAttribute("checked") === "checked";
+ return checked ? "[x] " : "[ ] ";
+ },
+ });
+
+ turndown.addRule("evernoteCrypt", {
+ filter: "en-crypt",
+ replacement: () => "[Encrypted Evernote content]",
+ });
+
+ turndown.addRule("evernoteMedia", {
+ filter: "en-media",
+ replacement: (_, node) => {
+ const type = node.getAttribute("type") || "attachment";
+ const hash = node.getAttribute("hash") || "unknown";
+ return type.startsWith("image/")
+ ? `\n\n![Evernote image ${hash}](evernote-resource:${hash})\n\n`
+ : `\n\n[Evernote attachment ${hash}](evernote-resource:${hash})\n\n`;
+ },
+ });
+
+ return turndown
+ .turndown(body || "")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+async function findOrCreateNotebook(client, notebooks, name, index) {
+ const existing = notebooks.find((notebook) => notebook.parentId === null && notebook.name === name);
+
+ if (existing) {
+ console.log(`Using existing notebook: ${name}`);
+ return existing;
+ }
+
+ const result = await mcpCall(client, "create_notebook", {
+ name: name.slice(0, 80),
+ parentId: null,
+ sortOrder: 1000 + index,
+ });
+
+ console.log(`Created notebook: ${result.notebook.name}`);
+ return result.notebook;
+}
+
+async function createMcpClient(profileName) {
+ const config = await readConfig();
+ const profile = profileName ? config.profiles?.[profileName] : undefined;
+ const baseUrl = (process.env.EDGEEVER_URL || profile?.url || DEFAULT_URL).replace(/\/+$/, "");
+ const token = process.env.EDGEEVER_TOKEN || profile?.token;
+
+ if (!token) {
+ throw new Error("EDGEEVER_TOKEN is required, or configure a profile with `bun run cli -- profile set`.");
+ }
+
+ return { baseUrl, token, nextId: 1 };
+}
+
+async function mcpCall(client, toolName, args) {
+ const id = client.nextId++;
+ const response = await fetch(`${client.baseUrl}/mcp`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${client.token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id,
+ method: "tools/call",
+ params: {
+ name: toolName,
+ arguments: args,
+ },
+ }),
+ });
+ const body = await response.json().catch(() => null);
+
+ if (!response.ok || body?.error) {
+ throw new Error(body?.error?.message || `${response.status} ${response.statusText}`);
+ }
+
+ return parseMcpToolResult(body.result);
+}
+
+function parseMcpToolResult(result) {
+ const text = result?.content?.find((item) => item.type === "text")?.text;
+
+ if (!text) {
+ return result;
+ }
+
+ return JSON.parse(text);
+}
+
+async function readConfig() {
+ try {
+ const value = JSON.parse(await readFile(CONFIG_PATH, "utf8"));
+ return value && typeof value === "object" ? value : {};
+ } catch {
+ return {};
+ }
+}
+
+async function confirmOrExit(question) {
+ const answer = await readline.question(question);
+
+ if (answer.trim().toLowerCase() !== "yes") {
+ console.log("Canceled.");
+ process.exit(0);
+ }
+}
+
+function printPlan(notebooks) {
+ const total = notebooks.reduce((sum, notebook) => sum + notebook.notes.length, 0);
+
+ console.log("Evernote import plan:");
+ console.log(` Notebooks: ${notebooks.length}`);
+ console.log(` Notes: ${total}`);
+
+ for (const notebook of notebooks) {
+ console.log(` - ${notebook.name}: ${notebook.notes.length} notes (${notebook.filePath})`);
+ }
+}
+
+function getText(value) {
+ if (value === undefined || value === null) {
+ return "";
+ }
+
+ if (typeof value === "string") {
+ return value;
+ }
+
+ if (typeof value === "object") {
+ return value.__cdata || value["#text"] || "";
+ }
+
+ return String(value);
+}
+
+function enexDateToIso(value) {
+ const match = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(value || "");
+
+ if (!match) {
+ return undefined;
+ }
+
+ return `${match[1]}-${match[2]}-${match[3]}T${match[4]}:${match[5]}:${match[6]}.000Z`;
+}
+
+function notebookNameFromFile(filePath) {
+ return basename(filePath, extname(filePath)).trim().slice(0, 80) || "Evernote Import";
+}
+
+function parseOptions(args) {
+ const parsed = {};
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (!arg.startsWith("--")) {
+ continue;
+ }
+
+ const key = arg.slice(2);
+ const next = args[index + 1];
+
+ if (!next || next.startsWith("--")) {
+ parsed[key] = "true";
+ continue;
+ }
+
+ parsed[key] = next;
+ index += 1;
+ }
+
+ return parsed;
+}
+
+function requireValue(value, name) {
+ if (!value) {
+ console.error(`${name} is required.\n`);
+ console.error(usage);
+ process.exit(1);
+ }
+
+ return value;
+}