From 2d38c76a241e55bdae2eb4b8a3468fe0ef329c0b Mon Sep 17 00:00:00 2001 From: harris Date: Wed, 25 Nov 2026 23:58:09 -0800 Subject: [PATCH] Update plugin Live Markdown v0.1.1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add plugin ide-open v1.0.0 - chore: ignore test directory - fix: address PR review feedback - chore: add CHANGELOG.md - chore: add auto-changelog script and release command - fix: remove double-escaping in openProject that broke paths - fix: remove double-escaping in openProject and clean trailing backslash in uriToPath - fix: remove Cmd+D shortcut for delete (intercepted by system) - Add plugin ide-open v1.0.0 - Add plugin ide-open v1.0.0 - Add WeChat multiopen plugin - Add plugin 微信多开 v1.0.0 - Add plugin 微信多开 v1.0.0 - Add plugin 微信多开 v1.0.0 - feat(image-batch-studio): 支持 Windows 多架构发布 - revert(image-batch-studio): 恢复动态运行组件 - Add plugin 图片压缩 v1.0.1 - Add plugin 时间戳工具 v1.0.1 - fix(device-link): 加固配对与设备授权一致性 - feat(device-link): 支持扫码自动连接设备 - docs(device-link): 更新扫码连接与安全边界 - chore(device-link): 发布 0.1.7 扫码自动连接 - Add plugin 截图标注 v1.3.12 - init - Update plugin 远程桌面管理 v1.0.7 - Add plugin 时间戳工具 v1.0.1 - Merge pull request #478 from WorldmeQC/plugin/remote-manager - Merge pull request #479 from TheLastSheep/plugin/device-link - fix(device-link): 延长扫码自动连接状态展示 - fix(device-link): 支持电脑端可靠下载附件 - Add plugin 图片压缩 v1.0.1 - feat: 馒头ocr 更新logo - Merge pull request #480 from TheLastSheep/plugin/device-link - Merge pull request #463 from z-hanzhe/plugin/timestamp-tool - Merge pull request #460 from z-hanzhe/plugin/img-comp - Add plugin 截图标注 v1.3.12 - feat: 截图全局快捷键触发不显示主窗口 - Update plugin 简单便签 v1.7.3 - Add plugin 聚光灯 v1.0.0 - feat(address-parser): 适配 ZTools 3.2 文件拖拽与版本门禁 - feat(pdf-office): 支持安全拖出与版本门禁 - feat(format-converter): 适配截图导入、文件拖拽与 pluginData - Update plugin 隐阅盒 v1.4.1 - feat(ztools-cc-switch): 适配 pluginData、文件拖拽与重入 - feat(office-suite): 适配 AI 模型协议与调用取消 - feat(image-batch-studio): 适配截图导入与文件拖拽 - feat(device-link): 适配 pluginData 与宿主生命周期 - Update plugin 自动化助手 v1.0.0 - Update plugin 自动化助手 v1.0.1 - Add plugin 截图标注 v1.3.12 - Merge pull request #488 from me1dlinger/plugin/hushreader - Update plugin Unity启动器 v1.0.1 - Add plugin 截图标注 v1.3.12 - Add plugin 呼哈表情包管理器 v1.0.0 - Merge pull request #504 from zhang00lei/plugin/unity-launcher - Merge pull request #498 from D06F6E67/plugin/automatic-assistant - Merge pull request #487 from Reaosen/plugin/spotlight - Merge pull request #486 from LowProfile666/plugin/easynote - Merge pull request #477 from Mutants-X/plugin/zashboard-panel - Merge pull request #506 from HUHAGE/plugin/huhabiaoqingbao - Merge pull request #505 from zhaoyuyang8520/plugin/screenshot-annotate - chore(release): ztools source v1.7.0 - Merge pull request #507 from cuteyuchen/plugin/project-manager - fix(format-converter): 清理已迁移的旧运行时 - fix(image-batch-studio): 迁移运行时至插件目录 - fix(ztools-cc-switch): 迁移插件数据至专属目录 - fix(device-link): 迁移设备连接数据至插件目录 - feat: 发布 Markdown 笔记 v0.1.0 - feat(system-manager): optimize dashboard ui with tabs, real hardware battery telemetry, and enhanced speedtest animation - Merge pull request #508 from dufan1032/plugin/ztools-markdown-notes - add: 人民币大写插件 v1.0.1 - Merge pull request #509 from SZYPXJ/plugin/rmb-capitalized - feat(system-manager): add app icons, startup grouping, and batch uninstaller - update: remove homepage link, bump to 2.1.1 - feat: 书签与历史记录搜索 v2.4.0 - Add plugin 书签与历史记录搜索 v2.4.0 - feat: topwindow适配asar - Add plugin Mise 控制台 v0.0.1 - feat: 歌词搜索插件 - Update plugin Markdown Notes v0.1.1 - Merge pull request #514 from GIWTO/plugin/ztools-lyrics - Merge pull request #513 from GIWTO/plugin/ztools-mise-manager - Merge pull request #512 from Mutants-X/plugin/browser-bookmarks-history - init - Replace default icon for WeChat multi-open - Update plugin 网页快开 v1.0.0 - feat: 插件图标处理失败时直接action失败 - chore(web-quick-open): bump version to 1.0.2 - feat: implement incremental plugin releases - Merge pull request #518 from bltx95/plugin/web-quick-open - Merge pull request #516 from dufan1032/plugin/ztools-markdown-notes-v0.1.1 - Add plugin 汉典查询 v0.3.2 - Merge pull request #511 from Mutants-X/plugin/zashboard-panel - Merge pull request #519 from rusyue/plugin/ztools-plugin-zdic-search - Merge pull request #517 from zhang00lei/plugin/ztools-kill-process - CD: 加快构建速度 - Merge pull request #349 from fxwl/plugin/wechat-multiopen - feat: 修复快翻译报错 - Update plugin 书签与历史记录搜索 v2.4.1 - Merge pull request #520 from Mutants-X/plugin/browser-bookmarks-history - Add plugin 文本差异对比 v1.0.0 - Merge pull request #521 from Particaly/plugin/diffffff - 添加网页搜索插件 v1.0.0 - Merge pull request #522 from Mutants-X/plugin/web-search - chore: remove unused release metadata assets - Update plugin 杀进程/进程管理 v1.0.1 - Update plugin 杀进程/进程管理 v1.0.1 - Merge pull request #524 from zhang00lei/plugin/ztools-kill-process - Update plugin 文件共享 v1.2.0 - Update plugin 文件共享 v1.2.0 - Merge pull request #525 from me1dlinger/plugin/fileshare - feat: first commit - Update plugin 隐阅盒 v1.4.2 - feat: update - Merge pull request #527 from me1dlinger/plugin/hushreader - release(loan-calculator): v1.9.2 plugin.json - release(loan-calculator): v1.9.2 index.html - release(loan-calculator): v1.9.2 preload.js - release(loan-calculator): v1.9.2 logo.png - release(loan-calculator): v1.9.2 README.md - release(loan-calculator): v1.9.2 LICENSE - release(loan-calculator): v2.0.0 plugin.json - release(loan-calculator): v2.0.0 index.html - release(loan-calculator): v2.0.0 preload.js - release(loan-calculator): v2.0.0 logo.png - release(loan-calculator): v2.0.0 README.md - release(loan-calculator): v2.0.0 LICENSE - fix(system-manager): suppress jetsamproperties warning and integrate app icons into system-cleaner - feat: vibe coding优化文件读取和编辑 - fix(system-manager): fix icon matching false positive and aggregate cleaner items by app - fix(system-manager): fix cleaner hang by restoring correct DOM elements and render loop - fix(system-cleaner): hide statusPanel and show resultPanel upon render completion - fix(system-cleaner): fix UI layout alignment, checkbox overlap, and warnings stringification - fix(application-uninstaller): expose app icon in publicApp DTO projection - feat(system-manager): unify icon resolution with hierarchical bundle fallback across modules - Merge pull request #530 from Samson1990-09/plugin/loan-calculator - Update plugin 科研小盒 v1.3.1 - Merge pull request #534 from Asa12138/plugin/micro-tools - Merge pull request #526 from lzx8589561/plugin/gomoku-3d-ztools - fix: 运行时文件迁移至 ztools.getPath("pluginData") 插件数据目录 - Merge pull request #535 from Samson1990-09/plugin/native-ocr - feat: 标准化所有插件变更日志 - Update plugin Native OCR v0.6.13 - feat(format-converter): 支持转换 HEIC/HEIF 格式图片 - Merge branch 'main' into plugin/native-ocr - 修复变更日志 - fix(format-converter): 将 package-lock.json 中的内网私有源地址替换为官方 npm registry - Merge pull request #538 from Samson1990-09/plugin/native-ocr - fix(image-batch-studio): 解决 HEIC 预览裂图与裁剪失效问题 - Merge branch 'main' into codex/image-batch-studio-3.0.2 - Merge pull request #374 from TheLastSheep/codex/image-batch-studio-3.0.2 - Update plugin Unity启动器 v1.0.2 - Add plugin 图标创建工具 v1.0.0 - fix(image-batch-studio): 解决 iOS HEIC 照片 security limits 超限及批处理失败问题 - Add plugin 图标创建工具 v1.0.0 - fix(image-batch-studio): 优化图片压缩机制与防负优化策略 - Merge pull request #541 from Particaly/plugin/icon-creator - chore(image-batch-studio): 升级版本号至 0.1.3 - Update plugin Unity启动器 v1.0.3 - Merge branch 'main' into plugin/unity-launcher - Merge pull request #540 from zhang00lei/plugin/unity-launcher - Merge pull request #542 from TheLastSheep/plugin/image-batch-studio-fix-heic-and-compress - Add plugin 文件解锁器 v1.0.0 - 🔖 release: First Commit - Update plugin 文件共享 v1.2.1 - Merge pull request #544 from xyflii/plugin/git-commit-message - Update plugin 隐阅盒 v1.4.3 - Add plugin 批量命令执行 v1.0.0 - Merge pull request #548 from 1182977069/plugin/ssh-batch-exec - feat: 网页快开,修复打开缓慢的问题,不在重复创建动态指令 - Update plugin 网页搜索 v1.0.0 - Update plugin 网页搜索 v1.0.1 - Merge branch 'main' into plugin/web-search - 表情罐头 v1.2.1 - Update plugin 隐阅盒 v1.5.0 - 优化CHANGELOG - Merge branch 'main' into plugin/hushreader - Merge pull request #552 from me1dlinger/plugin/hushreader - Merge pull request #553 from LowProfile666/plugin/easynote - Merge branch 'main' into plugin/stickercan - Merge pull request #551 from MoruTeaven/plugin/stickercan - Add plugin 批量启动 v0.1.0 - docs: add manage UI screenshot for PR - Update plugin 开发百宝箱 v2.7.0 - Update plugin 文件共享 v1.2.1 - Merge branch 'main' into plugin/fileshare - Merge pull request #545 from me1dlinger/plugin/fileshare - Update plugin 杀进程/进程管理 v1.0.2 - Merge branch 'main' into plugin/ztools-kill-process - Update plugin Native OCR v1.0.0 - Merge pull request #559 from Samson1990-09/plugin/native-ocr - Merge pull request #554 from ArthurYang999/plugin/batch-start - 1.1.0 - Merge pull request #556 from LowProfile666/plugin/quickterm - feat(system-manager): release v0.2.2 with dark purple dashboard, archive tree view, and plugin-guard scoping - chore(system-manager): bump version to v0.3.0 - feat(system-manager): add hardware metrics, archive inspection, and plugin audit MCP tools - 更新变更日志符合规范 - Merge pull request #550 from Mutants-X/plugin/web-search - Merge pull request #557 from zhang00lei/plugin/ztools-kill-process - Merge pull request #555 from LowProfile666/plugin/devbox - Merge pull request #543 from zhang00lei/plugin/ztools-file-unlocker - Update plugin 文件解锁器 v1.0.0 - Update plugin 文件解锁器 v1.0.1 - 2.7.1 - docs(system-manager): regenerate changelog based on git diff from v0.2.1 to v0.3.0 - Merge pull request #564 from LowProfile666/plugin/devbox - Add plugin ESClient v0.1.0 - docs: add REST console screenshot for PR checklist - 1.8.1 - Merge pull request #566 from LowProfile666/plugin/easynote - Merge pull request #565 from ArthurYang999/plugin/es-client - Add plugin 截图翻译 v0.8.0 - Merge pull request #563 from zhang00lei/plugin/ztools-file-unlocker - Update plugin 词匠 v1.5.0 - Merge pull request #569 from wlunan/plugin/prompt-forge - Update plugin 大古截图 v1.2.0 - Merge pull request #568 from beierweiwei/plugin/dagu-ocr - Update plugin 批量启动 v0.1.1 - Merge pull request #570 from ArthurYang999/plugin/batch-start - Add plugin SendGB 上传 v1.0.0 - 1.0.0 - Add plugin 极简剪贴板 v1.0.0 - Merge pull request #571 from xiaoxingOvO/plugin/x-clipboard - Merge pull request #573 from LowProfile666/plugin/bingpaper - Add plugin 截图翻译 v0.8.0 to marketplace - fix(snap-translate): declare win32 platform so marketplace builds Windows package - Merge pull request #572 from zhang00lei/plugin/sendgb-uploader - Merge pull request #567 from Taitres/plugin/snap-translate - Update plugin 提肛助手 v1.2.0 - Merge pull request #574 from LowProfile666/plugin/tiga - Update plugin jet plugin v1.1.0 - Merge pull request #576 from leqq00/plugin/jet-plugin - feat: v1.1.0 —— 秒贴快捷键、行尾可配置、设置面板重组与视觉打磨 - 2.7.2 - Merge pull request #577 from xiaoxingOvO/plugin/x-clipboard - Merge pull request #578 from LowProfile666/plugin/devbox - fix: macOS 启动项目改用 open 打开 .app,$USER_HOME$ 展开为绝对路径 - Merge pull request #579 from leqq00/plugin/jet-plugin - fix(windows): 修复列表空白并加固安装目录与启动命令发现 - Merge pull request #580 from leqq00/plugin/jet-plugin - Update plugin 极简剪贴板 v1.2.0 - Update plugin SendGB 上传下载 v1.0.1 - Merge pull request #581 from xiaoxingOvO/plugin/x-clipboard - Merge pull request #582 from zhang00lei/plugin/sendgb-uploader - Add plugin GitHub 星标管理 v1.0.0 - Update plugin 极简剪贴板 v1.2.1 - Update plugin git commit message v0.2.0 - Merge pull request #584 from xiaoxingOvO/plugin/x-clipboard - Merge pull request #583 from zhang00lei/plugin/github-stars - 1.2.0 - feat: release Base64 ZTools plugin v1.0.0 - 1.9.1 修复编辑器撤回失效与代码块跳出问题 - Update plugin 网页搜索 v1.0.1 - Merge pull request #585 from xyflii/plugin/git-commit-message - Merge pull request #587 from LowProfile666/plugin/quickterm - Merge pull request #589 from LowProfile666/plugin/easynote - Merge pull request #591 from Mutants-X/plugin/web-search - Merge pull request #588 from fuyanghulin/plugin/base64 - Update plugin 斗图表情包 v4.0.0 - Update plugin 批量命令执行 v1.0.1 - 1.2.0 - Update plugin 截图翻译 v0.9.0 - docs(snap-translate): complete CHANGELOG for v0.9.0 - 2.7.3 - Merge pull request #594 from LowProfile666/plugin/easyreminder - Update plugin 极简剪贴板 v1.3.0 - Merge pull request #598 from LowProfile666/plugin/devbox - Update plugin zashboard 面板 v3.0.0 - fix(ascii-tree): 修复分离独立窗口时尺寸无限碰撞问题; 修复浏览器环境下的复制&导出问题 - Update plugin Todos待办 v1.2.0 - Merge branch 'main' into plugin/todos - 1.0.1 - Merge pull request #597 from Taitres/plugin/snap-translate - 3.0.0 - Merge pull request #599 from xiaoxingOvO/plugin/x-clipboard - Merge pull request #602 from Code-Agitator/plugin/todos - Add plugin 股票管家 v1.0.0 - Merge pull request #603 from LowProfile666/plugin/easytable - Merge pull request #608 from LowProfile666/plugin/devbox - Add plugin Docker 镜像下载工具 v1.0.0 - Merge pull request #610 from zhang00lei/plugin/stock-ball - Merge pull request #607 from z-hanzhe/plugin/did-tool - fix(system-manager): keep dashboard view on generic entry and prevent automatic jump to diagnostics - Update plugin 股票管家 v1.0.1 - feat(system-manager): add default system-manager home feature and ensure direct entry to dashboard - Update plugin 极简剪贴板 v1.4.0 - Update plugin ZTools 提供商 v1.1.1 - Update plugin 时间戳工具 v1.0.2 - Update plugin 图片压缩 v1.0.2 - Merge pull request #620 from kaineooo/plugin/f-provider - Merge pull request #593 from diduweiwu/plugin/doutu - Merge pull request #595 from 1182977069/plugin/ssh-batch-exec - 3.0.1 - Add plugin CryptTool v1.1.0 - Add plugin 文件智能重命名 v1.0.0 - Add plugin 天气助手 v1.0.0 - Add plugin Windows 唤醒控制 v1.0.0 - Add plugin 字数统计 v1.0.1 - 1.0.3 - Update plugin 截图翻译 v1.0.0 - Update plugin 解除占用 v1.1.0 - Add plugin Y剪贴板 v1.0.0 - Merge pull request #635 from Taitres/plugin/unlock - Merge pull request #631 from zhang00lei/plugin/ztools-weather - Merge pull request #626 from LowProfile666/plugin/easytable - Add plugin SAZ 抓包解析 v0.2.4 - Merge pull request #636 from yanhaoxue/plugin/y-clipboard - Merge pull request #618 from xiaoxingOvO/plugin/x-clipboard - encode helper - feat: 新增音频提取插件 extract-audio v1.2.5 - Add plugin Scoop 包管理器 v1.0.0 - Update plugin Markdown 笔记 v0.1.2 - Update plugin 颜色助手 v1.1.0 - Merge pull request #616 from zhang00lei/plugin/stock-ball - chore(native-ocr): update src/lib/engineRerun.js for v1.1.0 - chore(native-ocr): update tests/engine-rerun.mjs for v1.1.0 - chore(native-ocr): update tests/table.mjs for v1.1.0 - chore(native-ocr): update CHANGELOG.md for v1.1.0 - chore(native-ocr): update README.md for v1.1.0 - chore(native-ocr): update bin/ocr-winrt.ps1 for v1.1.0 - chore(native-ocr): update bin/onnx_mfd_core.mjs for v1.1.0 - chore(native-ocr): update bin/onnx_mixed_merge.mjs for v1.1.0 - chore(native-ocr): update bin/onnx_mixed_server.mjs for v1.1.0 - chore(native-ocr): update bin/onnx_table_split.mjs for v1.1.0 - chore(native-ocr): update package.json for v1.1.0 - chore(native-ocr): update public/package.json for v1.1.0 - chore(native-ocr): update public/plugin.json for v1.1.0 - chore(native-ocr): update public/preload.js for v1.1.0 - chore(native-ocr): update src/App.vue for v1.1.0 - chore(native-ocr): update src/lib/mixedLayout.js for v1.1.0 - chore(native-ocr): update src/lib/tableModel.js for v1.1.0 - chore(native-ocr): update tests/mixed-layout.mjs for v1.1.0 - chore(native-ocr): update tests/run.mjs for v1.1.0 - chore(native-ocr): update vite.config.js for v1.1.0 - chore(native-ocr): remove .onnx-repro/package-lock.json for v1.1.0 - chore(native-ocr): remove .onnx-repro/package.json for v1.1.0 - chore(native-ocr): remove .onnx-repro/repro.mjs for v1.1.0 - chore(native-ocr): remove .onnx-repro/verify.mjs for v1.1.0 - chore(native-ocr): remove bin/onnx_ocr_backend.mjs for v1.1.0 - chore(native-ocr): remove src/styles/katex-fonts.css for v1.1.0 - Add plugin 快捷输入 v1.0.0 - Fix repeated shortcut entry for 快捷输入 v1.0.1 - Update 快捷输入 to v1.0.2 for review - Update plugin Y剪贴板 v1.0.19 - Merge pull request #622 from z-hanzhe/plugin/img-comp - Update plugin JSON 格式化 v1.0.1 - Merge pull request #621 from z-hanzhe/plugin/timestamp-tool - Update plugin 代码模板 v1.2.1 - Merge pull request #625 from LowProfile666/plugin/devbox - Merge pull request #630 from dufan1032/plugin/ztools-markdown-notes - Merge pull request #634 from Taitres/plugin/snap-translate - Merge pull request #642 from snwjas/plugin/color-helper - Merge pull request #644 from Samson1990-09/plugin/native-ocr - Merge pull request #646 from yanhaoxue/plugin/y-clipboard - Update plugin Markdown 笔记 v0.1.3 - Add plugin 自然语言定时提醒 v1.3.0 - Add plugin 歌词投屏 v0.4.0 - fix(system-manager): fix cpu monitor with real delta tick sampling, accurate uptime, and smooth baseline - Update plugin Y剪贴板 v1.0.21 - Add plugin AI视频画质修复 v1.0.0 - Merge pull request #641 from zhang00lei/plugin/ztools-scoop-manager - Merge pull request #643 from tom-fn/plugin/timer-reminder - Merge pull request #645 from Hiraly-wang/plugin/quick-input - Update plugin 股票管家 v1.0.2 - Update plugin 批量启动 v0.1.2 - Merge pull request #647 from fuyanghulin/plugin/json-formatter - Update plugin Scoop 包管理器 v1.0.1 - Merge pull request #650 from dufan1032/plugin/ztools-markdown-notes - Merge pull request #651 from yanhaoxue/plugin/y-clipboard - Merge pull request #653 from Particaly/plugin/lyriccast - Merge pull request #648 from LowProfile666/plugin/code-snippets - 1.3.1 - Update plugin 简单记录 v1.0.4 - Merge pull request #658 from LowProfile666/plugin/easyreminder - Merge pull request #659 from zhang00lei/plugin/stock-ball - Merge pull request #660 from ArthurYang999/plugin/batch-start - Merge pull request #662 from LowProfile666/plugin/easytable - Merge pull request #661 from zhang00lei/plugin/ztools-scoop-manager - Merge pull request #640 from akahoz94/plugin/extract-audio - Merge pull request #639 from lzq2357/main - Merge pull request #638 from lehuaner/plugin/saz-parser - fix: 修复发布包缺失 ssh2 依赖导致 preload 启动失败 - Merge pull request #663 from lhlucky0410/plugin/ssh-batch-exec - Add plugin V2EX 帖子浏览 v0.1.6 - Add plugin WebDAV 同步 v1.0.0 - Merge pull request #664 from Particaly/plugin/webdav-sync - Merge pull request #637 from XiewzHub/plugin/v2ex-browser - fix: add missing title for encode helper plugin - fix: preserve rebuilt plugin metadata in release manifests - Update plugin hooost v1.0.3 - Update plugin 科研小盒 v1.4.0: submission assistant and literature maps - Merge pull request #665 from Particaly/plugin/hooost - Merge pull request #666 from Asa12138/plugin/micro-tools-v1.4.0 - fix: make batch rename build on Node 20 and support macOS - feat: refresh batch rename icon and move file search - fix: package custom icon as png - Merge pull request #628 from yyxxd/plugin/batch-rename - Merge pull request #627 from Code-Agitator/plugin/crypt-tool - Merge pull request #633 from 404isfun/plugin/windows-awake - Update plugin WebDAV 同步 v1.1.0 - Merge pull request #668 from Particaly/plugin/webdav-sync - Add plugin 多引擎批量搜索 v2.0.0 - Merge pull request #669 from lijkop/plugin/multi-search - Add plugin 闪启 v1.0.0 - Add plugin Askills v1.0.1 - Add plugin Worldme音乐 v1.1.0 - chore(address-parser): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(format-converter): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(office-suite-workbench): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(pdf-office-workbench): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(system-manager): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(ztools-cc-switch): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(device-link): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - chore(video-enhancer): adopt @ztools-center/plugin-cli and format CHANGELOG for ztools publish - Update plugin 简单记录 v1.0.6 - 1.3.2 - Merge pull request #670 from lijkop/plugin/flashlaunch - Merge pull request #671 from WorldmeQC/plugin/worldme-music - Merge pull request #673 from LowProfile666/plugin/easytable - style: 升级全新 4K AI 玻璃拟物高清图标 - Merge pull request #674 from TheLastSheep/plugin/pasteboard-pro - Merge pull request #675 from LowProfile666/plugin/easyreminder - Update Askills to v1.0.2 with system fonts and smaller package - Update plugin WebDAV 同步 v1.1.1 - Merge pull request #676 from Particaly/plugin/webdav-sync - Update plugin ASCII-Tree v1.0.1 - docs: 按照 ztools-plugin-cli 规范格式化 CHANGELOG.md - ✨ 【环境备份插件开源发布】 feat(environment-vault): 导入环境备份恢复插件0.0.2 - ✅ 【环境备份插件开源发布】 test(environment-vault): 固化66项隔离回归测试 - 📝 【环境备份插件开源发布】 docs(environment-vault): 披露权限范围与Codex开发方式 - docs(address-parser): 按照 ztools-plugin-cli 规范格式化 CHANGELOG.md 并标注 commonjs - docs(format-converter): 按照 ztools-plugin-cli 规范格式化 CHANGELOG.md 并标注 commonjs - docs(office-suite-workbench): 按照 ztools-plugin-cli 规范格式化 CHANGELOG.md - Merge upstream/main and format CHANGELOG.md for ztools-plugin-cli - docs(system-manager): 按照 ztools-plugin-cli 规范格式化 CHANGELOG.md - Merge upstream/main and format CHANGELOG.md for ztools-plugin-cli - Merge upstream/main and format CHANGELOG.md for ztools-plugin-cli - Merge upstream/main into plugin/address-parser - Merge upstream/main into plugin/format-converter - Merge upstream/main into plugin/office-suite-workbench - Merge upstream/main into plugin/system-manager - Add plugin 网安 CTF 工具箱 v1.2.0 - Update plugin Worldme音乐 v1.1.1 - Update plugin Docker 镜像下载工具 v1.0.1 - Add plugin 演算本 v1.0.0 - Merge pull request #679 from WorldmeQC/plugin/worldme-music - Merge pull request #681 from z-hanzhe/plugin/did-tool - Merge pull request #654 from TheLastSheep/plugin/video-enhancer - Update plugin 解除占用 v1.2.0 - Update plugin Unity启动器 v1.0.4 - Release community-hub v1.0.0 - Update plugin CryptTool v1.2.0 - Update plugin V2EX 帖子浏览 v0.1.7 - Update micro-tools to v1.6.12: research English and AI course library - Update micro-tools to v1.6.13: wordbooks and learning hub - feat(web-quick-open): 功能迭代 - Merge branch 'main' of https://github.com/H0wAway/ZTools-plugins update - Merge pull request #672 from Candquarzy/plugin/askills - Merge pull request #678 from LightPolarisCN/plugin/ctf-toolbox - Merge pull request #683 from Code-Agitator/plugin/calc-pad - Merge pull request #685 from Taitres/plugin/unlock - Merge pull request #686 from TheLastSheep/plugin/pasteboard-pro - Merge pull request #689 from zhang00lei/plugin/community-hub - Merge pull request #690 from Code-Agitator/plugin/crypt-tool - Merge pull request #687 from zhang00lei/plugin/unity-launcher - Merge pull request #691 from XiewzHub/plugin/v2ex-browser - Add plugin CMark v1.1.0 - 1.0.1 - 更新 CMark:移除回收站改为真删、图片尺寸写入 Markdown、修复根级配置提交范围 - 修复动态指令(全局搜索)图标 404:icon 补扩展名并加启动校准 - Update plugin 股票管家 v1.0.4 - 笔记指令进入时直接打开对应笔记 - Update plugin 进程端口管理 v1.2.0 - feat: 新增劳务报酬计算器 v1.0.1 - docs: 补充界面截图 - 1.0.0 - 📝 【环境备份插件开源发布】 docs(environment-vault): 为变更日志版本标题补充日期 - 📝 【环境备份插件开源发布】 docs(environment-vault): 声明0.0.2试用状态及问题反馈方式 - 🐛 fix: 补全富文本图片地址以支持本地插件加载 - Update plugin 自然语言定时提醒 v1.5.1 - Update micro-tools to v1.7.0: research English web and material community - Merge pull request #677 from lifeek23/plugin/environment-vault-0.0.2 - Merge pull request #680 from LowProfile666/plugin/easynssm - Merge pull request #698 from Code-Agitator/plugin/process-manager - Merge pull request #699 from tom-fn/plugin/timer-reminder - fix(cmark): 市场包只提交运行时产物,避免 CI 把 node_modules 打进 zip - Update micro-tools to v1.7.6: domain covers and parseable changelog - Update micro-tools to v1.7.7: immersive practice and submission paths - Merge pull request #692 from Asa12138/plugin/micro-tools-v1.6.12 - Merge pull request #696 from LanccBy2016/plugin/cmark - Merge branch 'ZToolsCenter:main' into main - feat(web-quick-open): 新增批量获取网页图标功能 - Update plugin Mise 控制台 v0.1.0 - Add plugin 极速剪贴板 v1.0.25 - Remove plugin Y剪贴板 (y-clipboard): 已更名为极速剪贴板 (fast-clipboard) - Add plugin Mermaid 图表工作室 v1.0.0 - Update plugin Markdown 笔记 v0.1.4 - 1.4.0 - Initial commit - 1.0.0 - Update plugin GitHub 星标管理 v1.0.1 - chore(publish): 固化 Paste 1.4.0 测试断言修复快照 - Update plugin 大古截图 v1.2.1 - Update ncm-converter to v2.4.0: 修复 files 指令 schema + 右下角完成提示窗 - Merge pull request #693 from GIWTO/plugin/ztools-mise-manager - Merge pull request #697 from zhang00lei/plugin/stock-ball - Merge pull request #700 from Xhelyz/plugin/labor-pay-tax-calculator - Merge pull request #702 from XiewzHub/plugin/v2ex-browser - Merge pull request #704 from H0wAway/main - Merge pull request #705 from yanhaoxue/plugin/fast-clipboard - Merge pull request #707 from yang123155/plugin/mermaid-studio - Merge pull request #708 from dufan1032/plugin/ztools-markdown-notes - Merge pull request #709 from LowProfile666/plugin/easyreminder - Merge pull request #710 from ViktorMachine/plugin/ztool-vscode - Merge pull request #711 from LowProfile666/plugin/cafe-notice - Merge pull request #712 from zhang00lei/plugin/github-stars - test - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - feat(plugin): 新增轻影截图 snap-capture 插件 - chore: 移除内部交接文档(含本机路径,不适合公开仓库) - feat: 注册 snap-capture 插件到图像媒体分类 - Merge pull request #717 from TheLastSheep/plugin/pasteboard-pro - Merge pull request #718 from beierweiwei/plugin/dagu-ocr - Merge pull request #706 from yanhaoxue/remove/y-clipboard - Update plugin 定时提醒 v1.5.0 - Update plugin 简单记录 v1.0.7 - Update plugin 词匠 v1.5.1 - Update plugin 股票管家 v1.0.5 - Add plugin project-cost v1.0.0 - Update plugin 极速剪贴板 v1.0.26 - chore(native-ocr): update public/winrt-payload.cjs for v1.1.1 - chore(native-ocr): update tests/winrt-payload.mjs for v1.1.1 - chore(native-ocr): update CHANGELOG.md for v1.1.1 - chore(native-ocr): update bin/ocr-winrt.ps1 for v1.1.1 - chore(native-ocr): update package-lock.json for v1.1.1 - chore(native-ocr): update package.json for v1.1.1 - chore(native-ocr): update public/package.json for v1.1.1 - chore(native-ocr): update public/plugin.json for v1.1.1 - chore(native-ocr): update public/preload.js for v1.1.1 - Update plugin Paste剪切板 v1.4.0 - Update plugin 本地搜索Neo v1.2.1 - Add Workflowy plugin for ZTools. - Merge pull request #729 from TheLastSheep/plugin/pasteboard-pro - Update plugin 极速剪贴板 v1.0.27 - Update plugin 极速剪贴板 v1.0.28 - Update plugin 极速剪贴板 v1.0.29 - Update plugin 极速剪贴板 v1.0.30 - Update plugin 极速剪贴板 v1.0.31 - Update plugin 极速剪贴板 v1.0.32 - Update plugin 极速剪贴板 v1.0.32 - Merge pull request #721 from LowProfile666/plugin/easyreminder - Merge pull request #722 from LowProfile666/plugin/easytable - Merge pull request #723 from wlunan/plugin/prompt-forge - Merge pull request #724 from zhang00lei/plugin/stock-ball - Merge pull request #725 from Samson1990-09/plugin/project-cost - Merge pull request #726 from yanhaoxue/plugin/fast-clipboard - Merge pull request #728 from Samson1990-09/plugin/native-ocr - Merge pull request #730 from guopenghui/plugin/local-search-neo - Merge pull request #719 from akahoz94/plugin/ncm-converter-v2.4.0 - Merge pull request #701 from LowProfile666/plugin/easyenv - Merge pull request #667 from fetasty/main - Merge pull request #600 from Mutants-X/plugin/zashboard-panel - Merge pull request #632 from steveeyre/plugin/word-count - Merge pull request #496 from TheLastSheep/plugin/device-link - Merge pull request #495 from TheLastSheep/plugin/ztools-cc-switch-v1.54.0 - Merge pull request #493 from TheLastSheep/plugin/system-manager - Merge pull request #492 from TheLastSheep/plugin/pdf-office-workbench - Merge pull request #491 from TheLastSheep/plugin/office-suite-workbench - Merge pull request #490 from TheLastSheep/plugin/format-converter - Merge pull request #489 from TheLastSheep/plugin/address-parser - Merge branch 'main' of https://github.com/H0wAway/ZTools-plugins - feat(eb-quick-open): 分组功能优化 - Update plugin JSON 格式化 v1.0.2 - Merge pull request #732 from fuyanghulin/plugin/json-formatter - Merge pull request #731 from leekitleung/plugin/workflowy - feat(web-quick-open): 日志优化 - Merge branch 'ZToolsCenter:main' into main - Merge pull request #733 from H0wAway/main - Update 科研小盒 to v1.8.3 - Merge pull request #734 from Asa12138/plugin/micro-tools-v1.8.3 - feat: 支持移除插件 - feat: 待办事项插件 v1.0.0 首次发布 - docs: 添加插件截图 - docs: 补充亮色界面截图 - Update plugin 词匠 v1.6.0 - chore(plugin): 轻影截图 snap-capture 更新至 v1.11.1 - Merge pull request #735 from B0rnT0R0am/plugin/todo - Merge pull request #736 from wlunan/plugin/prompt-forge - fix(plugin): 修复 macOS 选区编辑器窗口边框,更新至 v1.11.2 - Merge pull request #720 from akahoz94/feat/snap-capture - Update plugin 词匠 v1.6.1 - Update plugin Paste剪切板 v1.4.1 - Merge pull request #737 from wlunan/plugin/prompt-forge - Merge pull request #739 from TheLastSheep/plugin/pasteboard-pro - fix(card): 卡片标题改用单行省略并支持 hover 渲染全文 - Add plugin LX Music v0.0.2 - fix(easynssm): 修正nssm application parameter - Merge pull request #740 from jiang66-so/plugin/lx-music-ztools - Merge pull request #741 from TheLastSheep/plugin/pasteboard-pro - Update plugin LX Music v0.1.2 - Update plugin 大古截图 v1.2.2 - Merge pull request #743 from jiang66-so/plugin/lx-music-ztools - Merge pull request #744 from beierweiwei/plugin/dagu-ocr - fix(easynssm): 修正版本号为 v1.0.2 - Merge branch 'ZToolsCenter:main' into fix/easynssm-application-parameter - Update plugin 批量启动 v0.1.3 - docs: add manage UI screenshot for v0.1.3 - Merge pull request #745 from ArthurYang999/plugin/batch-start - Merge pull request #742 from dvenlon/fix/easynssm-application-parameter - Add plugin 匯率換算 v1.0.0 - chore(cmark): 市场包更新到 1.2.4 - Update plugin 大古截图 v1.2.3 - 1.0.1 - Update plugin 网安 CTF 工具箱 v1.3.0 - Merge pull request #746 from kazma258/plugin/exchange-rates - Merge pull request #747 from LanccBy2016/plugin/cmark - Merge pull request #748 from beierweiwei/plugin/dagu-ocr - Merge pull request #749 from LowProfile666/plugin/cafe-notice - Add first-run disclaimer and simplify e2e suite - Merge pull request #751 from lzx8589561/plugin/ztools-video - remove the pre-release checklist from the readme - Replace home tab with inline topbar search - Merge pull request #753 from lzx8589561/plugin/ztools-video - Add plugin 程序坞 v0.1.8 - feat(history): 重复复制或粘贴时将对应记录置顶并保留分组顺序 - feat: update 程序坞 to v0.1.9 - feat: update 程序坞 to v0.1.10 - feat: update 程序坞 to v0.1.11 - Update 程序坞 to v0.1.12 - Update 程序坞 to v0.1.13 - Update 程序坞 to v0.1.14 - Merge pull request #754 from jiang66-so/plugin/ztools-dock - Merge pull request #752 from kazma258/fix/exchange-rates-readme - Merge pull request #756 from TheLastSheep/plugin/pasteboard-pro - Update plugin browser-bookmarks-history v2.5.0 - Merge pull request #757 from Mutants-X/plugin/browser-bookmarks-history - Merge pull request #750 from LightPolarisCN/plugin/ctf-toolbox - Update plugin 程序坞 v0.1.15 - Update 程序坞 to v0.1.16: plugin selector and automatic icons - Update 程序坞 to v0.1.17: stable hover opening layout - Update 程序坞 to v0.1.18: glass menus and entry cards - Update 程序坞 to v0.1.19: uploaded panel backgrounds - Update 程序坞 to v0.1.20: consent gates and permission management - Update 程序坞 to v0.1.21: icon dropdowns and thumbnail cache - Update plugin 词匠 v1.7.0 - Merge pull request #758 from jiang66-so/plugin/ztools-dock-0.1.15 - Merge pull request #759 from wlunan/plugin/prompt-forge - feat: release Mouse Quick 0.5.9 for ZTools on Windows - cyberchef-zh v1.0.4: CyberChef v11.5.0 全中文离线版 ZTools 插件 - Merge pull request #760 from jiang66-so/plugin/ztools-shukuaikuai - feat(live-markdown): 新增 Live Markdown 插件 v0.1.0 - Update plugin 鼠快快 v0.7.5 - feat: 百度翻译插件 v1.1.2 - Add plugin 小浏览器 v1.0.0 - fix: correct environment-vault author to lifeek - Add local-fsearch 0.0.2 submission draft with reviewed screenshots - Use external Everything tools and simplify the submission with high-DPI screenshots - Bundle official ES and simplify screenshot captions - Add plugin 进程管家 v1.0.0 - Update plugin Unity启动器 v1.0.4 - Merge pull request #763 from jiang66-so/plugin/ztools-shukuaikuai - Merge pull request #764 from yanhaoxue/plugin/baidu-translate - Merge pull request #765 from LightPolarisCN/plugin/mini-browser - Merge pull request #762 from TheLastSheep/plugin/live-markdown - Merge pull request #767 from lifeek23/draft/local-fsearch-0.0.2-lifeek - Merge pull request #769 from zhang00lei/plugin/unity-launcher - Merge pull request #761 from iFlyDiary/plugin/cyberchef-zh - Merge pull request #768 from XiewzHub/plugin/process-killer - Merge pull request #766 from lifeek23/fix/environment-vault-author-lifeek - chore(native-ocr): update bin/ocr-wechat-win.ps1 for v1.2.0 - chore(native-ocr): update public/onnx-diagnose.cjs for v1.2.0 - chore(native-ocr): update public/ps-ocr-payload.cjs for v1.2.0 - chore(native-ocr): update public/wechat-result.cjs for v1.2.0 - chore(native-ocr): update tests/onnx-diagnose.mjs for v1.2.0 - chore(native-ocr): update tests/ps-ocr-payload.mjs for v1.2.0 - chore(native-ocr): update tests/wechat-result.mjs for v1.2.0 - chore(native-ocr): update CHANGELOG.md for v1.2.0 - chore(native-ocr): update README.md for v1.2.0 - chore(native-ocr): update package-lock.json for v1.2.0 - chore(native-ocr): update package.json for v1.2.0 - chore(native-ocr): update public/package.json for v1.2.0 - chore(native-ocr): update public/plugin.json for v1.2.0 - chore(native-ocr): update public/preload.js for v1.2.0 - chore(native-ocr): update src/App.vue for v1.2.0 - chore(native-ocr): remove bin/ocr-winrt.ps1 for v1.2.0 - chore(native-ocr): remove public/winrt-payload.cjs for v1.2.0 - chore(native-ocr): remove tests/winrt-payload.mjs for v1.2.0 - Merge pull request #770 from Samson1990-09/plugin/native-ocr - fix(ide-open): repair packaged history and project navigation - fix(ide-open): open VS Code on macOS without the code command - fix(ide-open): simplify project row actions - fix(ide-open): open IntelliJ IDEA on macOS without the launcher - fix(ide-open): fill macOS app launch commands for IDE presets - Merge pull request #280 from SvenZhao/plugin/ide-open - Update plugin 自然语言定时提醒 v1.6.0 - Merge pull request #774 from tom-fn/plugin/timer-reminder - feat(json-editor): rebuild plugin with Vue 3 for v1.7.3 - CMark v1.2.5(源码) - Merge pull request #772 from LanccBy2016/plugin/cmark-v1.2.5 - Update plugin Todos待办 v1.3.0 - Merge pull request #775 from Code-Agitator/plugin/todos - fix(live-markdown): 拦截 WebDAV 同名文件互相覆盖 - chore(live-markdown): 发布 v0.1.1 - fix(image-batch-studio): 关闭保留元数据时不再导出原图 - chore(image-batch-studio): 发布 v0.1.4 并补 0.1.3 变更记录 --- plugins/live-markdown/CHANGELOG.md | 12 + plugins/live-markdown/package-lock.json | 4 +- plugins/live-markdown/package.json | 2 +- plugins/live-markdown/plugin.json | 2 +- .../preload/webdav-sync-ledger.cjs | 147 +++++ plugins/live-markdown/preload/webdav-sync.cjs | 562 +++++------------- .../preload/webdav-transport.cjs | 304 ++++++++++ plugins/live-markdown/scripts/verify-dist.mjs | 4 +- .../live-markdown/src/hooks/useWebdavSync.ts | 19 +- plugins/live-markdown/src/types/typora.ts | 37 +- .../tests/preload/webdav-conflict.test.cjs | 175 ++++++ 11 files changed, 851 insertions(+), 417 deletions(-) create mode 100644 plugins/live-markdown/preload/webdav-sync-ledger.cjs create mode 100644 plugins/live-markdown/preload/webdav-transport.cjs create mode 100644 plugins/live-markdown/tests/preload/webdav-conflict.test.cjs diff --git a/plugins/live-markdown/CHANGELOG.md b/plugins/live-markdown/CHANGELOG.md index c446a220b..e34419a98 100644 --- a/plugins/live-markdown/CHANGELOG.md +++ b/plugins/live-markdown/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 0.1.1 - 2026-11-25 + +### Fixed + +- 修复 WebDAV 同步时不同工作区的同名文件会映射到同一远端路径、互相覆盖的问题:本设备记录每个云端文件绑定的本地文件和上次同步的内容,上传或拉取前先核对;会覆盖未同步内容时按冲突跳过并提示原因。 +- 本地与云端在上次同步后都被修改时视为冲突,两侧都不写入;升级后首次同步时,内容不一致且没有同步记录的文件会被拦下,内容一致的文件直接建立绑定。 +- 保存后自动上传遇到同名冲突时也会提示,避免本地与云端悄悄分叉。 + +### Changed + +- 拆分 WebDAV 同步模块为传输层、同步记录与冲突判定、同步流程三部分;每次上传前先读取云端内容用于核对。 + ## 0.1.0 - 2026-11-17 ### 工作区多文件夹支持与默认工作区移除(2026-11-17) diff --git a/plugins/live-markdown/package-lock.json b/plugins/live-markdown/package-lock.json index 29df7f62f..fabfbdfe3 100644 --- a/plugins/live-markdown/package-lock.json +++ b/plugins/live-markdown/package-lock.json @@ -1,12 +1,12 @@ { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "license": "MIT", "dependencies": { "@codemirror/commands": "^6.11.1", diff --git a/plugins/live-markdown/package.json b/plugins/live-markdown/package.json index 616551de3..9fdd32149 100644 --- a/plugins/live-markdown/package.json +++ b/plugins/live-markdown/package.json @@ -1,6 +1,6 @@ { "name": "ztools-live-markdown", - "version": "0.1.0", + "version": "0.1.1", "private": true, "type": "module", "description": "High-performance live-preview Markdown editor built in React 19 & TypeScript for ZTools.", diff --git a/plugins/live-markdown/plugin.json b/plugins/live-markdown/plugin.json index 3ec161073..a5e56e5ef 100644 --- a/plugins/live-markdown/plugin.json +++ b/plugins/live-markdown/plugin.json @@ -3,7 +3,7 @@ "title": "Live Markdown", "description": "高性能沉浸式所见即所得 Markdown 编辑器:支持实时预览/源码模式切换、大纲与文件树、全局搜索、数学公式、Mermaid 图表、交互式表格、专注模式、打字机模式与 6 套经典排版主题", "author": "harris", - "version": "0.1.0", + "version": "0.1.1", "main": "dist/index.html", "preload": "preload/services.cjs", "logo": "logo.svg", diff --git a/plugins/live-markdown/preload/webdav-sync-ledger.cjs b/plugins/live-markdown/preload/webdav-sync-ledger.cjs new file mode 100644 index 000000000..269d6b3a5 --- /dev/null +++ b/plugins/live-markdown/preload/webdav-sync-ledger.cjs @@ -0,0 +1,147 @@ +"use strict"; + +// WebDAV 同步台账与冲突守卫。 +// +// 远端文件只按文件名寻址,不同工作区的同名文件会映射到同一个远端路径。 +// 台账按「服务器 + 远端目录 + 文件名」记录本设备上次同步时绑定的本地文件和内容哈希, +// 任何写入(上传覆盖云端、拉取覆盖本地)都必须证明被覆盖的一侧正是上次同步的版本, +// 否则视为冲突并跳过,绝不静默覆盖。 + +const crypto = require("node:crypto"); +const path = require("node:path"); + +const LEDGER_STORAGE_KEY = "live_markdown_webdav_sync_ledger_v1"; + +function hashContent(content) { + return crypto.createHash("sha256").update(String(content ?? ""), "utf8").digest("hex"); +} + +function normalizeLocalPath(filePath) { + if (!filePath || typeof filePath !== "string") return null; + const resolved = path.resolve(filePath); + return process.platform === "win32" ? resolved.toLowerCase() : resolved; +} + +function remoteKey(config, fileName) { + const server = String(config.serverUrl || "").trim().replace(/\/+$/, ""); + return `${server}|${config.remotePath}|${fileName}`; +} + +function resolveDefaultStorage() { + const ztools = typeof window !== "undefined" ? window.ztools : null; + if (ztools?.dbStorage && typeof ztools.dbStorage.getItem === "function" && typeof ztools.dbStorage.setItem === "function") { + return ztools.dbStorage; + } + if (typeof localStorage !== "undefined" && typeof localStorage.getItem === "function" && typeof localStorage.setItem === "function") { + return localStorage; + } + return null; +} + +function createMemoryStorage() { + const map = new Map(); + return { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => { + map.set(key, String(value)); + } + }; +} + +function createWebdavSyncLedger(storage) { + const store = storage || resolveDefaultStorage() || createMemoryStorage(); + + // 台账损坏时按“没有任何同步记录”处理:只会产生更多冲突提示,不会放行覆盖。 + function readAll() { + try { + const raw = store.getItem(LEDGER_STORAGE_KEY); + if (!raw) return {}; + const parsed = typeof raw === "string" ? JSON.parse(raw) : raw; + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } + } + + function writeAll(entries) { + store.setItem(LEDGER_STORAGE_KEY, JSON.stringify(entries)); + } + + return { + get(config, fileName) { + const entry = readAll()[remoteKey(config, fileName)]; + return entry && typeof entry === "object" ? entry : null; + }, + record(config, fileName, { localPath, contentHash }) { + const all = readAll(); + // 本地路径为空(未保存文档)表示“未绑定”:守卫只按内容哈希判定,之后另存为的文件可以正常接管。 + all[remoteKey(config, fileName)] = { + localPath: normalizeLocalPath(localPath), + contentHash, + syncedAt: Date.now() + }; + writeAll(all); + }, + forget(config, fileName) { + const all = readAll(); + delete all[remoteKey(config, fileName)]; + writeAll(all); + } + }; +} + +/** 拉取:云端内容将写入 localPath。localHash 为 null 表示本地文件不存在。 */ +function decidePullWrite({ binding, localPath, localHash, remoteHash }) { + if (localHash === null || localHash === remoteHash) return { allowed: true }; + const normalized = normalizeLocalPath(localPath); + if (binding && binding.localPath && binding.localPath !== normalized) { + return { allowed: false, reason: "bound-elsewhere" }; + } + if (binding && binding.localPath === normalized) { + return binding.contentHash === localHash + ? { allowed: true } + : { allowed: false, reason: "local-modified" }; + } + return { allowed: false, reason: "local-unknown" }; +} + +/** 上传:localPath 的内容将覆盖云端。remoteHash 为 null 表示云端文件不存在。 */ +function decidePushWrite({ binding, localPath, localHash, remoteHash }) { + if (remoteHash === null || remoteHash === localHash) return { allowed: true }; + if (!binding) return { allowed: false, reason: "unknown-remote" }; + const normalized = normalizeLocalPath(localPath); + if (binding.localPath && binding.localPath !== normalized) { + return { allowed: false, reason: "bound-elsewhere" }; + } + return binding.contentHash === remoteHash + ? { allowed: true } + : { allowed: false, reason: "remote-changed" }; +} + +function describeConflict(direction, fileName, reason) { + const action = direction === "push" ? "上传" : "拉取"; + switch (reason) { + case "bound-elsewhere": + return `《${fileName}》已与另一个本地文件同步(可能是其他工作区的同名文件),已跳过${action}以免互相覆盖。请重命名其中一个文件,或为该工作区使用独立的 WebDAV 远端目录。`; + case "remote-changed": + return `云端《${fileName}》在上次同步后已被其他设备或工作区修改,已跳过上传以免覆盖云端内容,请先核对差异。`; + case "unknown-remote": + return `云端已存在内容不同的《${fileName}》,且本设备没有它的同步记录,已跳过上传以免覆盖云端内容。确认以本地为准时,可先在 WebDAV 面板删除云端副本再同步。`; + case "local-modified": + return `本地《${fileName}》有尚未同步的修改,与云端内容不一致,已跳过拉取以免覆盖本地文件。`; + case "local-unknown": + default: + return `本地已存在内容不同的《${fileName}》,且本设备没有它的同步记录,已跳过${action}以免覆盖。确认以云端为准时,可先移走或重命名本地文件再拉取。`; + } +} + +module.exports = { + LEDGER_STORAGE_KEY, + hashContent, + normalizeLocalPath, + createWebdavSyncLedger, + createMemoryStorage, + decidePullWrite, + decidePushWrite, + describeConflict +}; diff --git a/plugins/live-markdown/preload/webdav-sync.cjs b/plugins/live-markdown/preload/webdav-sync.cjs index 1278dcf7b..81c43f5c3 100644 --- a/plugins/live-markdown/preload/webdav-sync.cjs +++ b/plugins/live-markdown/preload/webdav-sync.cjs @@ -1,303 +1,46 @@ "use strict"; +// WebDAV 同步编排层:连接测试、上传、拉取、删除与工作区同步。 +// 传输细节在 webdav-transport.cjs;所有覆盖写入(云端或本地)都先经过 webdav-sync-ledger.cjs 的冲突守卫。 + const fs = require("node:fs"); const path = require("node:path"); -const http = require("node:http"); -const https = require("node:https"); -const { URL } = require("node:url"); - -const { isMarkdownFile } = require("./fs-workspace.cjs"); - -function normalizeRemotePath(remotePath) { - const raw = String(remotePath || "/TyporaNotes/").trim(); - const collapsed = raw.replace(/\\/g, "/").replace(/\/+/g, "/"); - const withLeading = collapsed.startsWith("/") ? collapsed : `/${collapsed}`; - return withLeading.endsWith("/") ? withLeading : `${withLeading}/`; -} - -function normalizeWebdavConfig(config = {}) { - const serverUrl = String(config.serverUrl || "").trim(); - const username = String(config.username || "").trim(); - const password = String(config.password || ""); - const remotePath = normalizeRemotePath(config.remotePath); - const syncDirection = - config.syncDirection === "push" || config.syncDirection === "pull" - ? config.syncDirection - : "bidirectional"; - - return { - enabled: Boolean(config.enabled), - serverUrl, - username, - password, - remotePath, - autoSyncOnSave: config.autoSyncOnSave !== false, - syncDirection - }; -} - -function sanitizeDocFileName(fileName) { - const base = path.basename(String(fileName || "Untitled.md").trim() || "Untitled.md"); - const ext = path.extname(base).toLowerCase(); - if (!ext) { - return `${base}.md`; - } - return base; -} - -function isMarkdownFileName(fileName) { - return isMarkdownFile(String(fileName || "")); -} - -function buildAuthHeader(username, password) { - if (!username && !password) return null; - const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64"); - return `Basic ${token}`; -} - -function resolveWebdavUrl(serverUrl, remotePath, fileName = "") { - if (!serverUrl) { - throw new Error("WebDAV 服务器地址不能为空"); - } - let parsedBase; - try { - parsedBase = new URL(serverUrl); - } catch { - throw new Error(`无效的 WebDAV 服务器 URL: ${serverUrl}`); - } - if (parsedBase.protocol !== "http:" && parsedBase.protocol !== "https:") { - throw new Error("WebDAV 仅支持 http:// 或 https:// 协议"); - } - - const basePath = parsedBase.pathname.replace(/\/+$/, ""); - const relSegments = normalizeRemotePath(remotePath) - .split("/") - .filter(Boolean) - .map((seg) => encodeURIComponent(decodeURIComponent(seg))); - - let fullPathname = `${basePath}/${relSegments.join("/")}/`.replace(/\/+/g, "/"); - if (fileName) { - const safeFile = sanitizeDocFileName(fileName); - fullPathname = `${fullPathname}${encodeURIComponent(safeFile)}`; - } - - const target = new URL(parsedBase.toString()); - target.pathname = fullPathname; - return target; -} - -function sendWebdavRequest(targetUrl, options = {}, redirectCount = 0) { - const urlObj = targetUrl instanceof URL ? targetUrl : new URL(String(targetUrl)); - const client = urlObj.protocol === "https:" ? https : http; - const method = options.method || "GET"; - const timeoutMs = options.timeoutMs || 12000; - const maxRedirects = options.maxRedirects ?? 3; - const bodyBuffer = - options.body === undefined || options.body === null - ? null - : Buffer.isBuffer(options.body) - ? options.body - : Buffer.from(String(options.body), "utf8"); - - const headers = { - "User-Agent": "ZTools-Markdown-WebDAV/1.0", - ...(options.headers || {}) - }; - - if (bodyBuffer) { - headers["Content-Length"] = String(bodyBuffer.length); - } - - return new Promise((resolve, reject) => { - const req = client.request( - urlObj, - { - method, - headers, - timeout: timeoutMs - }, - (res) => { - const statusCode = res.statusCode || 0; - const locationHeader = res.headers?.location; - if ( - [301, 302, 307, 308].includes(statusCode) && - locationHeader && - redirectCount < maxRedirects - ) { - res.resume(); - try { - const redirectedUrl = new URL(locationHeader, urlObj); - if ( - redirectedUrl.protocol === "http:" || - redirectedUrl.protocol === "https:" - ) { - resolve( - sendWebdavRequest(redirectedUrl, options, redirectCount + 1) - ); - return; - } - } catch { - // Fall through and return raw response if redirect URL is malformed - } - } - const chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => { - const buffer = Buffer.concat(chunks); - resolve({ - statusCode, - statusMessage: res.statusMessage || "", - headers: res.headers || {}, - bodyBuffer: buffer, - bodyText: buffer.toString("utf8") - }); - }); - } - ); - - req.on("timeout", () => { - req.destroy(new Error(`WebDAV 请求超时 (${timeoutMs}ms)`)); - }); - - req.on("error", (err) => { - reject(err); - }); - - if (bodyBuffer && bodyBuffer.length > 0) { - req.write(bodyBuffer); - } - req.end(); - }); +const { + normalizeRemotePath, + normalizeWebdavConfig, + sanitizeDocFileName, + isMarkdownFileName, + buildAuthHeader, + resolveWebdavUrl, + sendWebdavRequest, + ensureRemoteCollection, + parsePropfindXml +} = require("./webdav-transport.cjs"); +const { + hashContent, + createWebdavSyncLedger, + decidePullWrite, + decidePushWrite, + describeConflict +} = require("./webdav-sync-ledger.cjs"); + +let defaultLedger = null; +function resolveLedger(options) { + if (options && options.ledger) return options.ledger; + if (!defaultLedger) defaultLedger = createWebdavSyncLedger(); + return defaultLedger; } -async function ensureRemoteCollection(rawConfig) { - const config = normalizeWebdavConfig(rawConfig); +function authHeaders(config) { const auth = buildAuthHeader(config.username, config.password); - const baseHeaders = auth ? { Authorization: auth } : {}; - - const segments = config.remotePath.split("/").filter(Boolean); - let cumulative = "/"; - for (const seg of segments) { - cumulative = `${cumulative}${seg}/`; - const colUrl = resolveWebdavUrl(config.serverUrl, cumulative); - const res = await sendWebdavRequest(colUrl, { - method: "MKCOL", - headers: baseHeaders - }); - // 201 Created, 405 Method Not Allowed (already exists), 200/204/207/301/302 are acceptable - if (res.statusCode === 401 || res.statusCode === 403) { - return { - ok: false, - status: res.statusCode, - message: `WebDAV 鉴权失败 (HTTP ${res.statusCode}),请检查账号或应用密码` - }; - } - } - return { ok: true, status: 201 }; -} - -function decodeXmlEntities(str) { - return String(str || "") - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") - .replace(/"/g, '"') - .replace(/'/g, "'"); -} - -function extractXmlTagText(xmlBlock, localTagName) { - const regex = new RegExp( - `<(?:[a-zA-Z0-9_-]+:)?${localTagName}\\b[^>]*>([\\s\\S]*?)<\\/(?:[a-zA-Z0-9_-]+:)?${localTagName}>`, - "i" - ); - const match = xmlBlock.match(regex); - return match ? decodeXmlEntities(match[1].trim()) : ""; -} - -function isCollectionResource(xmlBlock) { - const resTypeMatch = xmlBlock.match( - /<(?:[a-zA-Z0-9_-]+:)?resourcetype\b[^>]*>([\s\S]*?)<\/(?:[a-zA-Z0-9_-]+:)?resourcetype>/i - ); - if (!resTypeMatch) return false; - return /<(?:[a-zA-Z0-9_-]+:)?collection\b/i.test(resTypeMatch[1]); -} - -function parsePropfindXml(xmlText, collectionUrlPathname) { - const responseBlocks = - String(xmlText || "").match( - /<(?:[a-zA-Z0-9_-]+:)?response\b[^>]*>[\s\S]*?<\/(?:[a-zA-Z0-9_-]+:)?response>/gi - ) || []; - - const normalizedCollectionPath = decodeURIComponent( - String(collectionUrlPathname || "").replace(/\/+$/, "") - ); - - const files = []; - const seenNames = new Set(); - - for (const block of responseBlocks) { - const rawHref = extractXmlTagText(block, "href"); - if (!rawHref) continue; - - let hrefPathname = rawHref; - try { - if (/^https?:\/\//i.test(rawHref)) { - hrefPathname = new URL(rawHref).pathname; - } - } catch { - // keep rawHref - } - - const decodedHref = decodeURIComponent(hrefPathname); - const trimmedHref = decodedHref.replace(/\/+$/, ""); - - if (!trimmedHref || trimmedHref === normalizedCollectionPath) { - continue; - } - - if (isCollectionResource(block) || decodedHref.endsWith("/")) { - continue; - } - - const fileName = path.posix.basename(trimmedHref); - if (!fileName || !isMarkdownFileName(fileName) || seenNames.has(fileName)) { - continue; - } - - const sizeStr = extractXmlTagText(block, "getcontentlength"); - const lastModStr = extractXmlTagText(block, "getlastmodified"); - const etagStr = extractXmlTagText(block, "getetag").replace(/^"+|"+$/g, ""); - - const size = Number.isFinite(Number(sizeStr)) ? Number(sizeStr) : 0; - const parsedTime = lastModStr ? Date.parse(lastModStr) : NaN; - const hasValidMtime = Number.isFinite(parsedTime); - const mtimeMs = hasValidMtime ? parsedTime : 0; - - seenNames.add(fileName); - files.push({ - name: fileName, - href: rawHref, - size, - lastModified: lastModStr || "", - mtimeMs, - hasValidMtime, - etag: etagStr - }); - } - - files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name)); - return files; + return auth ? { Authorization: auth } : {}; } async function testWebdavConnection(rawConfig) { try { const config = normalizeWebdavConfig(rawConfig); const collectionUrl = resolveWebdavUrl(config.serverUrl, config.remotePath); - const auth = buildAuthHeader(config.username, config.password); - const headers = { - ...(auth ? { Authorization: auth } : {}) - }; const mkcolResult = await ensureRemoteCollection(config); if (!mkcolResult.ok) { @@ -318,7 +61,7 @@ async function testWebdavConnection(rawConfig) { const res = await sendWebdavRequest(collectionUrl, { method: "PROPFIND", headers: { - ...headers, + ...authHeaders(config), Depth: "1", "Content-Type": "application/xml; charset=utf-8" }, @@ -384,73 +127,110 @@ async function listWebdavFiles(rawConfig) { }; } -async function pushWebdavDocument(rawConfig, docName, content) { +/** 读取云端文档;不存在时返回 null。 */ +async function fetchRemoteDocument(config, safeName) { + const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); + const res = await sendWebdavRequest(targetUrl, { method: "GET", headers: authHeaders(config) }); + if (res.statusCode === 404 || res.statusCode === 410) return null; + if (res.statusCode < 200 || res.statusCode >= 300) { + throw new Error(`拉取云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); + } + const lastModHeader = res.headers["last-modified"]; + const parsedMtime = lastModHeader ? Date.parse(lastModHeader) : NaN; + return { + content: res.bodyText, + mtimeMs: Number.isFinite(parsedMtime) ? parsedMtime : Date.now() + }; +} + +function readLocalHash(filePath) { + if (!filePath || !fs.existsSync(filePath)) return null; + return hashContent(fs.readFileSync(filePath, "utf8")); +} + +function conflictResult(direction, safeName, reason) { + const message = describeConflict(direction, safeName, reason); + return { ok: false, conflict: true, reason, name: safeName, error: message, message }; +} + +async function pushWebdavDocument(rawConfig, docName, content, options = {}) { const config = normalizeWebdavConfig(rawConfig); + const ledger = resolveLedger(options); const safeName = sanitizeDocFileName(docName); const mkcolResult = await ensureRemoteCollection(config); if (!mkcolResult.ok) { throw new Error(mkcolResult.message); } - const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); const bodyStr = String(content ?? ""); - - const res = await sendWebdavRequest(targetUrl, { - method: "PUT", - headers: { - ...(auth ? { Authorization: auth } : {}), - "Content-Type": "text/markdown; charset=utf-8" - }, - body: bodyStr + const localHash = hashContent(bodyStr); + const localPath = typeof options.localPath === "string" && options.localPath ? options.localPath : null; + const remote = await fetchRemoteDocument(config, safeName); + const remoteHash = remote ? hashContent(remote.content) : null; + const decision = decidePushWrite({ + binding: ledger.get(config, safeName), + localPath, + localHash, + remoteHash }); + if (!decision.allowed) { + return { ...conflictResult("push", safeName, decision.reason), syncedAt: Date.now() }; + } - if (res.statusCode < 200 || res.statusCode >= 300) { - throw new Error( - `上传 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); + if (remoteHash !== localHash) { + const res = await sendWebdavRequest(targetUrl, { + method: "PUT", + headers: { ...authHeaders(config), "Content-Type": "text/markdown; charset=utf-8" }, + body: bodyStr + }); + if (res.statusCode < 200 || res.statusCode >= 300) { + throw new Error(`上传 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); + } } + ledger.record(config, safeName, { localPath, contentHash: localHash }); return { ok: true, name: safeName, remoteUrl: targetUrl.toString(), - status: res.statusCode, + status: 201, size: Buffer.byteLength(bodyStr, "utf8"), syncedAt: Date.now() }; } -async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = null) { +async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = null, options = {}) { const config = normalizeWebdavConfig(rawConfig); + const ledger = resolveLedger(options); const safeName = sanitizeDocFileName(remoteFileName); - const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); - - const res = await sendWebdavRequest(targetUrl, { - method: "GET", - headers: { - ...(auth ? { Authorization: auth } : {}) - } - }); - - if (res.statusCode < 200 || res.statusCode >= 300) { - throw new Error( - `拉取云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + const remote = await fetchRemoteDocument(config, safeName); + if (!remote) { + throw new Error(`拉取云端文档 ${safeName} 失败: HTTP 404 Not Found`); } - - const content = res.bodyText; - const lastModHeader = res.headers["last-modified"]; - const parsedMtime = lastModHeader ? Date.parse(lastModHeader) : NaN; - const mtimeMs = Number.isFinite(parsedMtime) ? parsedMtime : Date.now(); + const { content, mtimeMs } = remote; + const remoteHash = hashContent(content); let savedPath = null; let savedDir = ""; if (localTargetDir && typeof localTargetDir === "string" && fs.existsSync(localTargetDir)) { savedDir = path.resolve(localTargetDir); - savedPath = path.join(savedDir, safeName); - fs.writeFileSync(savedPath, content, "utf8"); + const targetPath = path.join(savedDir, safeName); + const localHash = readLocalHash(targetPath); + const decision = decidePullWrite({ + binding: ledger.get(config, safeName), + localPath: targetPath, + localHash, + remoteHash + }); + if (!decision.allowed) { + return { ...conflictResult("pull", safeName, decision.reason), path: null, dir: savedDir, syncedAt: Date.now() }; + } + if (localHash !== remoteHash) { + fs.writeFileSync(targetPath, content, "utf8"); + } + savedPath = targetPath; + ledger.record(config, safeName, { localPath: targetPath, contentHash: remoteHash }); } return { @@ -465,51 +245,44 @@ async function pullWebdavDocument(rawConfig, remoteFileName, localTargetDir = nu }; } -async function deleteWebdavDocument(rawConfig, remoteFileName) { +async function deleteWebdavDocument(rawConfig, remoteFileName, options = {}) { const config = normalizeWebdavConfig(rawConfig); const safeName = sanitizeDocFileName(remoteFileName); const targetUrl = resolveWebdavUrl(config.serverUrl, config.remotePath, safeName); - const auth = buildAuthHeader(config.username, config.password); - const res = await sendWebdavRequest(targetUrl, { - method: "DELETE", - headers: { - ...(auth ? { Authorization: auth } : {}) - } - }); + const res = await sendWebdavRequest(targetUrl, { method: "DELETE", headers: authHeaders(config) }); - if ( - res.statusCode !== 404 && - (res.statusCode < 200 || res.statusCode >= 300) - ) { - throw new Error( - `删除云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}` - ); + if (res.statusCode !== 404 && (res.statusCode < 200 || res.statusCode >= 300)) { + throw new Error(`删除云端文档 ${safeName} 失败: HTTP ${res.statusCode} ${res.statusMessage}`); } + resolveLedger(options).forget(config, safeName); - return { - ok: true, - name: safeName, - status: res.statusCode - }; + return { ok: true, name: safeName, status: res.statusCode }; +} + +function collectLocalMarkdown(localDir) { + const localMap = new Map(); + if (!localDir) return localMap; + for (const entry of fs.readdirSync(localDir, { withFileTypes: true })) { + if (!entry.isFile() || entry.name.startsWith(".")) continue; + if (!isMarkdownFileName(entry.name)) continue; + const fullPath = path.join(localDir, entry.name); + const stat = fs.statSync(fullPath); + localMap.set(entry.name, { name: entry.name, path: fullPath, content: null, mtimeMs: stat.mtimeMs, size: stat.size }); + } + return localMap; } async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const config = normalizeWebdavConfig(rawConfig); - const direction = - options.direction || config.syncDirection || "bidirectional"; + const ledgerOptions = { ledger: resolveLedger(options) }; + const direction = options.direction || config.syncDirection || "bidirectional"; const localDir = - options.localDir && - typeof options.localDir === "string" && - fs.existsSync(options.localDir) + options.localDir && typeof options.localDir === "string" && fs.existsSync(options.localDir) ? path.resolve(options.localDir) : null; const activeDoc = - options.activeDoc && - typeof options.activeDoc === "object" && - options.activeDoc.name - ? options.activeDoc - : null; + options.activeDoc && typeof options.activeDoc === "object" && options.activeDoc.name ? options.activeDoc : null; const initialList = await listWebdavFiles(config); if (!initialList.ok) { @@ -520,6 +293,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { downloaded: [], downloadedPaths: [], skipped: [], + conflicts: [], remoteFiles: [], syncedAt: Date.now(), message: initialList.message @@ -531,32 +305,18 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const downloaded = []; const downloadedPaths = []; const skipped = []; + const conflicts = []; + const conflictNames = new Set(); + const noteConflict = (result, dir) => { + conflictNames.add(result.name); + conflicts.push({ name: result.name, direction: dir, reason: result.reason, message: result.message }); + }; - // 1. Collect local markdown file metadata without reading file contents upfront - const localMap = new Map(); - if (localDir) { - const entries = fs.readdirSync(localDir, { withFileTypes: true }); - for (const entry of entries) { - if (!entry.isFile() || entry.name.startsWith(".")) continue; - if (!isMarkdownFileName(entry.name)) continue; - const fullPath = path.join(localDir, entry.name); - const stat = fs.statSync(fullPath); - localMap.set(entry.name, { - name: entry.name, - path: fullPath, - content: null, - mtimeMs: stat.mtimeMs, - size: stat.size - }); - } - } + // 1. 收集本地 Markdown 元数据,不预读内容 + const localMap = collectLocalMarkdown(localDir); - // Also include activeDoc if it's not already in localMap and direction allows push - if ( - activeDoc && - (direction === "push" || direction === "bidirectional") && - !localMap.has(sanitizeDocFileName(activeDoc.name)) - ) { + // 当前文档不在工作区根目录时也参与上传 + if (activeDoc && (direction === "push" || direction === "bidirectional") && !localMap.has(sanitizeDocFileName(activeDoc.name))) { const safeActiveName = sanitizeDocFileName(activeDoc.name); const activeContent = String(activeDoc.content ?? ""); localMap.set(safeActiveName, { @@ -568,7 +328,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { }); } - // 2. Push phase (local -> remote) + // 2. 上传阶段(本地 -> 云端) if (direction === "push" || direction === "bidirectional") { for (const [name, localFile] of localMap.entries()) { const remoteFile = remoteMap.get(name); @@ -576,40 +336,36 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const shouldPush = direction === "push" || !remoteFile || - (remoteHasMtime - ? localFile.mtimeMs >= remoteFile.mtimeMs - 1000 - : localFile.size !== remoteFile.size); - - if (shouldPush) { - const contentToPush = - localFile.content !== null - ? localFile.content - : fs.readFileSync(localFile.path, "utf8"); - await pushWebdavDocument(config, name, contentToPush); - uploaded.push(name); - } else { + (remoteHasMtime ? localFile.mtimeMs >= remoteFile.mtimeMs - 1000 : localFile.size !== remoteFile.size); + + if (!shouldPush) { skipped.push(name); + continue; } + const contentToPush = localFile.content !== null ? localFile.content : fs.readFileSync(localFile.path, "utf8"); + const pushed = await pushWebdavDocument(config, name, contentToPush, { ...ledgerOptions, localPath: localFile.path }); + if (pushed.ok) uploaded.push(name); + else noteConflict(pushed, "push"); } } - // 3. Pull phase (remote -> localDir) + // 3. 拉取阶段(云端 -> localDir) if ((direction === "pull" || direction === "bidirectional") && localDir) { for (const [name, remoteFile] of remoteMap.entries()) { - if (uploaded.includes(name)) continue; + if (uploaded.includes(name) || conflictNames.has(name)) continue; const localFile = localMap.get(name); const remoteHasMtime = Boolean(remoteFile.mtimeMs > 0); const shouldPull = - direction === "pull" || - !localFile || - (remoteHasMtime && remoteFile.mtimeMs > localFile.mtimeMs + 1000); + direction === "pull" || !localFile || (remoteHasMtime && remoteFile.mtimeMs > localFile.mtimeMs + 1000); if (shouldPull) { - const pulled = await pullWebdavDocument(config, name, localDir); - downloaded.push(name); - if (pulled.path) { - downloadedPaths.push(pulled.path); + const pulled = await pullWebdavDocument(config, name, localDir, ledgerOptions); + if (!pulled.ok) { + noteConflict(pulled, "pull"); + continue; } + downloaded.push(name); + if (pulled.path) downloadedPaths.push(pulled.path); } else if (!skipped.includes(name)) { skipped.push(name); } @@ -618,6 +374,7 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { const refreshed = await listWebdavFiles(config); const remoteFiles = refreshed.ok ? refreshed.files : initialList.files; + const conflictNote = conflicts.length > 0 ? `,${conflicts.length} 篇同名冲突已跳过` : ""; return { ok: true, @@ -626,9 +383,10 @@ async function syncWorkspaceWithWebdav(rawConfig, options = {}) { downloaded, downloadedPaths, skipped, + conflicts, remoteFiles, syncedAt: Date.now(), - message: `同步完成:上传 ${uploaded.length} 篇,下载 ${downloaded.length} 篇(云端共 ${remoteFiles.length} 篇)` + message: `同步完成:上传 ${uploaded.length} 篇,下载 ${downloaded.length} 篇${conflictNote}(云端共 ${remoteFiles.length} 篇)` }; } diff --git a/plugins/live-markdown/preload/webdav-transport.cjs b/plugins/live-markdown/preload/webdav-transport.cjs new file mode 100644 index 000000000..22741cc68 --- /dev/null +++ b/plugins/live-markdown/preload/webdav-transport.cjs @@ -0,0 +1,304 @@ +"use strict"; + +// WebDAV 传输层:URL 解析、鉴权、HTTP 请求、MKCOL 与 PROPFIND 解析。不涉及本地文件写入与冲突判定。 + +const path = require("node:path"); +const http = require("node:http"); +const https = require("node:https"); +const { URL } = require("node:url"); + +const { isMarkdownFile } = require("./fs-workspace.cjs"); + +function normalizeRemotePath(remotePath) { + const raw = String(remotePath || "/TyporaNotes/").trim(); + const collapsed = raw.replace(/\\/g, "/").replace(/\/+/g, "/"); + const withLeading = collapsed.startsWith("/") ? collapsed : `/${collapsed}`; + return withLeading.endsWith("/") ? withLeading : `${withLeading}/`; +} + +function normalizeWebdavConfig(config = {}) { + const serverUrl = String(config.serverUrl || "").trim(); + const username = String(config.username || "").trim(); + const password = String(config.password || ""); + const remotePath = normalizeRemotePath(config.remotePath); + const syncDirection = + config.syncDirection === "push" || config.syncDirection === "pull" + ? config.syncDirection + : "bidirectional"; + + return { + enabled: Boolean(config.enabled), + serverUrl, + username, + password, + remotePath, + autoSyncOnSave: config.autoSyncOnSave !== false, + syncDirection + }; +} + +function sanitizeDocFileName(fileName) { + const base = path.basename(String(fileName || "Untitled.md").trim() || "Untitled.md"); + const ext = path.extname(base).toLowerCase(); + if (!ext) { + return `${base}.md`; + } + return base; +} + +function isMarkdownFileName(fileName) { + return isMarkdownFile(String(fileName || "")); +} + +function buildAuthHeader(username, password) { + if (!username && !password) return null; + const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64"); + return `Basic ${token}`; +} + +function resolveWebdavUrl(serverUrl, remotePath, fileName = "") { + if (!serverUrl) { + throw new Error("WebDAV 服务器地址不能为空"); + } + let parsedBase; + try { + parsedBase = new URL(serverUrl); + } catch { + throw new Error(`无效的 WebDAV 服务器 URL: ${serverUrl}`); + } + if (parsedBase.protocol !== "http:" && parsedBase.protocol !== "https:") { + throw new Error("WebDAV 仅支持 http:// 或 https:// 协议"); + } + + const basePath = parsedBase.pathname.replace(/\/+$/, ""); + const relSegments = normalizeRemotePath(remotePath) + .split("/") + .filter(Boolean) + .map((seg) => encodeURIComponent(decodeURIComponent(seg))); + + let fullPathname = `${basePath}/${relSegments.join("/")}/`.replace(/\/+/g, "/"); + if (fileName) { + const safeFile = sanitizeDocFileName(fileName); + fullPathname = `${fullPathname}${encodeURIComponent(safeFile)}`; + } + + const target = new URL(parsedBase.toString()); + target.pathname = fullPathname; + return target; +} + +function sendWebdavRequest(targetUrl, options = {}, redirectCount = 0) { + const urlObj = targetUrl instanceof URL ? targetUrl : new URL(String(targetUrl)); + const client = urlObj.protocol === "https:" ? https : http; + const method = options.method || "GET"; + const timeoutMs = options.timeoutMs || 12000; + const maxRedirects = options.maxRedirects ?? 3; + const bodyBuffer = + options.body === undefined || options.body === null + ? null + : Buffer.isBuffer(options.body) + ? options.body + : Buffer.from(String(options.body), "utf8"); + + const headers = { + "User-Agent": "ZTools-Markdown-WebDAV/1.0", + ...(options.headers || {}) + }; + + if (bodyBuffer) { + headers["Content-Length"] = String(bodyBuffer.length); + } + + return new Promise((resolve, reject) => { + const req = client.request( + urlObj, + { + method, + headers, + timeout: timeoutMs + }, + (res) => { + const statusCode = res.statusCode || 0; + const locationHeader = res.headers?.location; + if ( + [301, 302, 307, 308].includes(statusCode) && + locationHeader && + redirectCount < maxRedirects + ) { + res.resume(); + try { + const redirectedUrl = new URL(locationHeader, urlObj); + if ( + redirectedUrl.protocol === "http:" || + redirectedUrl.protocol === "https:" + ) { + resolve( + sendWebdavRequest(redirectedUrl, options, redirectCount + 1) + ); + return; + } + } catch { + // Fall through and return raw response if redirect URL is malformed + } + } + + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + const buffer = Buffer.concat(chunks); + resolve({ + statusCode, + statusMessage: res.statusMessage || "", + headers: res.headers || {}, + bodyBuffer: buffer, + bodyText: buffer.toString("utf8") + }); + }); + } + ); + + req.on("timeout", () => { + req.destroy(new Error(`WebDAV 请求超时 (${timeoutMs}ms)`)); + }); + + req.on("error", (err) => { + reject(err); + }); + + if (bodyBuffer && bodyBuffer.length > 0) { + req.write(bodyBuffer); + } + req.end(); + }); +} + +async function ensureRemoteCollection(rawConfig) { + const config = normalizeWebdavConfig(rawConfig); + const auth = buildAuthHeader(config.username, config.password); + const baseHeaders = auth ? { Authorization: auth } : {}; + + const segments = config.remotePath.split("/").filter(Boolean); + let cumulative = "/"; + for (const seg of segments) { + cumulative = `${cumulative}${seg}/`; + const colUrl = resolveWebdavUrl(config.serverUrl, cumulative); + const res = await sendWebdavRequest(colUrl, { + method: "MKCOL", + headers: baseHeaders + }); + // 201 Created, 405 Method Not Allowed (already exists), 200/204/207/301/302 are acceptable + if (res.statusCode === 401 || res.statusCode === 403) { + return { + ok: false, + status: res.statusCode, + message: `WebDAV 鉴权失败 (HTTP ${res.statusCode}),请检查账号或应用密码` + }; + } + } + return { ok: true, status: 201 }; +} + +function decodeXmlEntities(str) { + return String(str || "") + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, '"') + .replace(/'/g, "'"); +} + +function extractXmlTagText(xmlBlock, localTagName) { + const regex = new RegExp( + `<(?:[a-zA-Z0-9_-]+:)?${localTagName}\\b[^>]*>([\\s\\S]*?)<\\/(?:[a-zA-Z0-9_-]+:)?${localTagName}>`, + "i" + ); + const match = xmlBlock.match(regex); + return match ? decodeXmlEntities(match[1].trim()) : ""; +} + +function isCollectionResource(xmlBlock) { + const resTypeMatch = xmlBlock.match( + /<(?:[a-zA-Z0-9_-]+:)?resourcetype\b[^>]*>([\s\S]*?)<\/(?:[a-zA-Z0-9_-]+:)?resourcetype>/i + ); + if (!resTypeMatch) return false; + return /<(?:[a-zA-Z0-9_-]+:)?collection\b/i.test(resTypeMatch[1]); +} + +function parsePropfindXml(xmlText, collectionUrlPathname) { + const responseBlocks = + String(xmlText || "").match( + /<(?:[a-zA-Z0-9_-]+:)?response\b[^>]*>[\s\S]*?<\/(?:[a-zA-Z0-9_-]+:)?response>/gi + ) || []; + + const normalizedCollectionPath = decodeURIComponent( + String(collectionUrlPathname || "").replace(/\/+$/, "") + ); + + const files = []; + const seenNames = new Set(); + + for (const block of responseBlocks) { + const rawHref = extractXmlTagText(block, "href"); + if (!rawHref) continue; + + let hrefPathname = rawHref; + try { + if (/^https?:\/\//i.test(rawHref)) { + hrefPathname = new URL(rawHref).pathname; + } + } catch { + // keep rawHref + } + + const decodedHref = decodeURIComponent(hrefPathname); + const trimmedHref = decodedHref.replace(/\/+$/, ""); + + if (!trimmedHref || trimmedHref === normalizedCollectionPath) { + continue; + } + + if (isCollectionResource(block) || decodedHref.endsWith("/")) { + continue; + } + + const fileName = path.posix.basename(trimmedHref); + if (!fileName || !isMarkdownFileName(fileName) || seenNames.has(fileName)) { + continue; + } + + const sizeStr = extractXmlTagText(block, "getcontentlength"); + const lastModStr = extractXmlTagText(block, "getlastmodified"); + const etagStr = extractXmlTagText(block, "getetag").replace(/^"+|"+$/g, ""); + + const size = Number.isFinite(Number(sizeStr)) ? Number(sizeStr) : 0; + const parsedTime = lastModStr ? Date.parse(lastModStr) : NaN; + const hasValidMtime = Number.isFinite(parsedTime); + const mtimeMs = hasValidMtime ? parsedTime : 0; + + seenNames.add(fileName); + files.push({ + name: fileName, + href: rawHref, + size, + lastModified: lastModStr || "", + mtimeMs, + hasValidMtime, + etag: etagStr + }); + } + + files.sort((a, b) => b.mtimeMs - a.mtimeMs || a.name.localeCompare(b.name)); + return files; +} + +module.exports = { + normalizeRemotePath, + normalizeWebdavConfig, + sanitizeDocFileName, + isMarkdownFileName, + buildAuthHeader, + resolveWebdavUrl, + sendWebdavRequest, + ensureRemoteCollection, + parsePropfindXml +}; diff --git a/plugins/live-markdown/scripts/verify-dist.mjs b/plugins/live-markdown/scripts/verify-dist.mjs index 0073d99f8..00c42d2e6 100644 --- a/plugins/live-markdown/scripts/verify-dist.mjs +++ b/plugins/live-markdown/scripts/verify-dist.mjs @@ -20,7 +20,9 @@ const requiredFiles = [ "preload/services.cjs", "preload/fs-workspace.cjs", "preload/exporter.cjs", - "preload/webdav-sync.cjs" + "preload/webdav-sync.cjs", + "preload/webdav-transport.cjs", + "preload/webdav-sync-ledger.cjs" ]; for (const relativePath of requiredFiles) { diff --git a/plugins/live-markdown/src/hooks/useWebdavSync.ts b/plugins/live-markdown/src/hooks/useWebdavSync.ts index 3137f4ecc..e8b685e16 100644 --- a/plugins/live-markdown/src/hooks/useWebdavSync.ts +++ b/plugins/live-markdown/src/hooks/useWebdavSync.ts @@ -146,7 +146,8 @@ export function useWebdavSync({ const res = await bridge.pushWebdavDocument( webdavConfig, doc.name || "Untitled.md", - doc.content + doc.content, + { localPath: doc.path } ); if (res.ok) { setWebdavSyncState("success"); @@ -159,7 +160,8 @@ export function useWebdavSync({ setWebdavSyncState("error"); const errMsg = res.error || "WebDAV 上传失败"; setWebdavStatusMessage(errMsg); - if (!silent) showToast(errMsg); + // 同名冲突即使在保存后静默同步时也要告知用户,否则云端与本地会悄悄分叉。 + if (!silent || res.conflict) showToast(errMsg); } } catch (err) { const msg = err instanceof Error ? err.message : String(err); @@ -172,6 +174,7 @@ export function useWebdavSync({ bridge, doc.content, doc.name, + doc.path, handleOpenWebdavSettings, handleRefreshWebdavFiles, showToast, @@ -196,7 +199,7 @@ export function useWebdavSync({ path: res.path, name: res.name, dir: res.dir || targetLocalDir || doc.dir, - content: res.content, + content: res.content ?? "", isDirty: false, mtimeMs: res.mtimeMs || Date.now() }); @@ -315,6 +318,16 @@ export function useWebdavSync({ } } + const conflicts = Array.isArray(res.conflicts) ? res.conflicts : []; + if (conflicts.length > 0) { + const detail = + conflicts.length === 1 + ? conflicts[0].message + : `${res.message}。冲突文件:${conflicts.map((c) => c.name).join("、")}`; + setWebdavStatusMessage(detail); + showToast(detail); + return; + } showToast(res.message); } else { setWebdavSyncState("error"); diff --git a/plugins/live-markdown/src/types/typora.ts b/plugins/live-markdown/src/types/typora.ts index db2a25192..167ec4114 100644 --- a/plugins/live-markdown/src/types/typora.ts +++ b/plugins/live-markdown/src/types/typora.ts @@ -203,26 +203,46 @@ export interface WebdavListResult { syncedAt: number; } +/** 同名冲突原因:写入会覆盖本设备未同步过的内容时,同步引擎拒绝写入。 */ +export type WebdavConflictReason = + | "bound-elsewhere" + | "remote-changed" + | "unknown-remote" + | "local-modified" + | "local-unknown"; + +export interface WebdavConflict { + name: string; + direction: "push" | "pull"; + reason: WebdavConflictReason; + message: string; +} + export interface WebdavPushResult { ok: boolean; name: string; - remoteUrl: string; - status: number; - size: number; + remoteUrl?: string; + status?: number; + size?: number; syncedAt: number; error?: string; + conflict?: boolean; + reason?: WebdavConflictReason; } export interface WebdavPullResult { ok: boolean; name: string; - content: string; + /** 冲突被拦截时不返回内容。 */ + content?: string; path: string | null; dir: string; - size: number; - mtimeMs: number; + size?: number; + mtimeMs?: number; syncedAt: number; error?: string; + conflict?: boolean; + reason?: WebdavConflictReason; } export interface WebdavSyncResult { @@ -232,6 +252,8 @@ export interface WebdavSyncResult { downloaded: string[]; downloadedPaths?: string[]; skipped: string[]; + /** 因同名冲突被拦截、未写入任何一侧的文件。 */ + conflicts?: WebdavConflict[]; remoteFiles: WebdavRemoteFile[]; syncedAt: number; message: string; @@ -423,7 +445,8 @@ export interface TyporaBridgeApi { pushWebdavDocument?: ( config: WebdavConfig, docName: string, - content: string + content: string, + options?: { localPath?: string | null } ) => Promise; pullWebdavDocument?: ( config: WebdavConfig, diff --git a/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs b/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs new file mode 100644 index 000000000..2419131f5 --- /dev/null +++ b/plugins/live-markdown/tests/preload/webdav-conflict.test.cjs @@ -0,0 +1,175 @@ +"use strict"; + +// 回归:不同工作区的同名文件共用一个 WebDAV 远端目录时,同步不得静默覆盖任何一侧。 + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const webdavApi = require("../../preload/webdav-sync.cjs"); +const { + LEDGER_STORAGE_KEY, + createWebdavSyncLedger, + createMemoryStorage, + decidePullWrite, + decidePushWrite, + hashContent +} = require("../../preload/webdav-sync-ledger.cjs"); +const { createE2EMockWebdavServer } = require("../e2e/mock-webdav.cjs"); + +const REMOTE_NOTE = "/dav/TyporaNotes/notes.md"; + +async function withServer(run) { + const { server, files } = createE2EMockWebdavServer(); + files.clear(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const config = { + enabled: true, + serverUrl: `http://127.0.0.1:${server.address().port}/dav/`, + username: "typora_e2e", + password: "pass_123", + remotePath: "/TyporaNotes/", + autoSyncOnSave: true, + syncDirection: "bidirectional" + }; + const root = fs.mkdtempSync(path.join(os.tmpdir(), "lm-webdav-conflict-")); + const wsA = path.join(root, "workspace-a"); + const wsB = path.join(root, "workspace-b"); + fs.mkdirSync(wsA); + fs.mkdirSync(wsB); + const ledger = createWebdavSyncLedger(createMemoryStorage()); + try { + await run({ config, files, wsA, wsB, ledger }); + } finally { + await new Promise((resolve) => server.close(resolve)); + fs.rmSync(root, { recursive: true, force: true }); + } +} + +function setRemote(files, content) { + files.set(REMOTE_NOTE, { content, mtimeMs: Date.now() + 60_000, etag: `etag-${Date.now()}` }); +} + +test("pulling into another workspace never overwrites its same-named file", async () => { + await withServer(async ({ config, files, wsA, wsB, ledger }) => { + fs.writeFileSync(path.join(wsA, "notes.md"), "# A\n", "utf8"); + fs.writeFileSync(path.join(wsB, "notes.md"), "# B\n", "utf8"); + + const syncA = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + assert.deepEqual(syncA.uploaded, ["notes.md"]); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + + const syncB = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsB, direction: "pull", ledger }); + assert.equal(syncB.ok, true); + assert.deepEqual(syncB.downloaded, []); + assert.equal(syncB.conflicts.length, 1); + assert.equal(syncB.conflicts[0].reason, "bound-elsewhere"); + assert.equal(fs.readFileSync(path.join(wsB, "notes.md"), "utf8"), "# B\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(pulled.ok, false); + assert.equal(pulled.conflict, true); + assert.equal(pulled.path, null); + assert.equal(fs.readFileSync(path.join(wsB, "notes.md"), "utf8"), "# B\n"); + }); +}); + +test("pushing from another workspace never overwrites the remote copy", async () => { + await withServer(async ({ config, files, wsA, wsB, ledger }) => { + fs.writeFileSync(path.join(wsA, "notes.md"), "# A\n", "utf8"); + fs.writeFileSync(path.join(wsB, "notes.md"), "# B\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + const syncB = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsB, direction: "push", ledger }); + assert.deepEqual(syncB.uploaded, []); + assert.equal(syncB.conflicts[0].reason, "bound-elsewhere"); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + + // 未保存的同名新文档(没有本地路径)同样不能覆盖已绑定的云端文件。 + const unsaved = await webdavApi.pushWebdavDocument(config, "notes.md", "# draft\n", { ledger }); + assert.equal(unsaved.ok, false); + assert.equal(unsaved.reason, "bound-elsewhere"); + assert.equal(files.get(REMOTE_NOTE).content, "# A\n"); + }); +}); + +test("the bound workspace still syncs normally in both directions", async () => { + await withServer(async ({ config, files, wsA, ledger }) => { + const noteA = path.join(wsA, "notes.md"); + fs.writeFileSync(noteA, "# A\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + // 其他设备修改了云端,本地未改:允许拉取覆盖。 + setRemote(files, "# A from phone\n"); + const pulled = await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "pull", ledger }); + assert.deepEqual(pulled.downloaded, ["notes.md"]); + assert.equal(fs.readFileSync(noteA, "utf8"), "# A from phone\n"); + + // 本地修改、云端未改:允许上传覆盖。 + fs.writeFileSync(noteA, "# A edited\n", "utf8"); + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# A edited\n", { ledger, localPath: noteA }); + assert.equal(pushed.ok, true); + assert.equal(files.get(REMOTE_NOTE).content, "# A edited\n"); + }); +}); + +test("both sides changed since the last sync is a conflict in either direction", async () => { + await withServer(async ({ config, files, wsA, ledger }) => { + const noteA = path.join(wsA, "notes.md"); + fs.writeFileSync(noteA, "# base\n", "utf8"); + await webdavApi.syncWorkspaceWithWebdav(config, { localDir: wsA, direction: "push", ledger }); + + fs.writeFileSync(noteA, "# local edit\n", "utf8"); + setRemote(files, "# remote edit\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsA, { ledger }); + assert.equal(pulled.reason, "local-modified"); + assert.equal(fs.readFileSync(noteA, "utf8"), "# local edit\n"); + + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# local edit\n", { ledger, localPath: noteA }); + assert.equal(pushed.reason, "remote-changed"); + assert.equal(files.get(REMOTE_NOTE).content, "# remote edit\n"); + }); +}); + +test("without a ledger entry, differing content on either side is never overwritten", async () => { + await withServer(async ({ config, files, wsB, ledger }) => { + const noteB = path.join(wsB, "notes.md"); + fs.writeFileSync(noteB, "# legacy local\n", "utf8"); + setRemote(files, "# legacy remote\n"); + + const pulled = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(pulled.reason, "local-unknown"); + assert.equal(fs.readFileSync(noteB, "utf8"), "# legacy local\n"); + + const pushed = await webdavApi.pushWebdavDocument(config, "notes.md", "# legacy local\n", { ledger, localPath: noteB }); + assert.equal(pushed.reason, "unknown-remote"); + assert.equal(files.get(REMOTE_NOTE).content, "# legacy remote\n"); + + // 内容一致时直接建立绑定,不视为冲突。 + fs.writeFileSync(noteB, "# legacy remote\n", "utf8"); + const adopted = await webdavApi.pullWebdavDocument(config, "notes.md", wsB, { ledger }); + assert.equal(adopted.ok, true); + assert.equal(adopted.path, noteB); + }); +}); + +test("a corrupt ledger fails closed", () => { + const storage = createMemoryStorage(); + storage.setItem(LEDGER_STORAGE_KEY, "{not json"); + const ledger = createWebdavSyncLedger(storage); + const config = { serverUrl: "https://dav.example", remotePath: "/TyporaNotes/" }; + assert.equal(ledger.get(config, "notes.md"), null); + const decision = decidePullWrite({ + binding: null, + localPath: "/tmp/notes.md", + localHash: hashContent("local"), + remoteHash: hashContent("remote") + }); + assert.equal(decision.allowed, false); + assert.equal( + decidePushWrite({ binding: null, localPath: "/tmp/notes.md", localHash: hashContent("a"), remoteHash: hashContent("b") }).allowed, + false + ); +});