Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Improve document import and export with remote kernels https://github.com/siyuan-note/siyuan/issues/19952

Daniel33744eee5a36
diff --git a/app/electron/main.js b/app/electron/main.js
index 4e3aecfdf0..fc0380672a 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -44,6 +44,8 @@ const gNet = require("net");
const childProcess = require("child_process");
const remote = require("@electron/remote/main");
const {probeRemoteKernelAuthentication} = require("./remoteKernelAuth");
+const {saveRemoteExport} = require("./remoteExport");
+const remoteExportSenders = new WeakSet();
const {createConnectionManager, getRemoteSession} = require("./connectionManager");
const {connectionArgs, readConnections, closeConnectionWindows} = require("./connectionStore");
const {
@@ -3169,6 +3171,33 @@ app.whenReady().then(() => {
return getKernelConnection(getWindowKernelTarget(event.sender.id));
}
const remoteSender = getWindowKernelTarget(event.sender.id)?.mode === "remote";
+ if (data.cmd === "saveRemoteExport") {
+ if (!remoteSender || !initializedWindowIds.has(event.sender.id) ||
+ event.senderFrame !== event.sender.mainFrame || remoteExportSenders.has(event.sender)) {
+ return {status: "error"};
+ }
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ remoteExportSenders.add(event.sender);
+ event.sender.once("destroyed", abort);
+ try {
+ return await saveRemoteExport({
+ uri: data.uri,
+ origin: getWindowKernelTarget(event.sender.id).origin,
+ choosePath: (defaultPath) => dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), {
+ defaultPath, properties: ["showOverwriteConfirmation"],
+ }),
+ fetch: (url, options) => event.sender.session.fetch(url, options),
+ signal: controller.signal,
+ });
+ } catch (error) {
+ writeLog("save remote export failed: " + error.message);
+ return {status: "error"};
+ } finally {
+ event.sender.removeListener("destroyed", abort);
+ remoteExportSenders.delete(event.sender);
+ }
+ }
if (remoteSender && ["beginRichClipboard", "completeRichClipboard", "cancelRichClipboard", "clipboardRead", "clipboardReadFiles"]
.includes(data.cmd)) {
writeLog("ignored local file clipboard processing in remote kernel mode");
diff --git a/app/electron/remoteExport.js b/app/electron/remoteExport.js
new file mode 100644
index 0000000000..8465dd2134
--- /dev/null
+++ b/app/electron/remoteExport.js
@@ -0,0 +1,69 @@
+const fs = require("node:fs");
+const path = require("node:path");
+const {randomUUID} = require("node:crypto");
+const {Readable} = require("node:stream");
+const {pipeline} = require("node:stream/promises");
+
+const resolveRemoteExportURL = (uri, origin) => {
+ if (typeof uri !== "string" || uri.includes("\\")) {
+ throw new Error("Invalid export URL");
+ }
+ const url = new URL(uri, origin + "/");
+ if (url.origin !== origin || url.username || url.password || url.search || url.hash ||
+ !url.pathname.startsWith("/export/") || url.pathname.startsWith("/export/temp/")) {
+ throw new Error("Invalid export URL");
+ }
+ const segments = url.pathname.split("/").slice(2).map(segment => {
+ let decoded = segment;
+ for (let count = 0; count < 8; count++) {
+ if (!decoded || decoded === "." || decoded === ".." || /[\\/]/.test(decoded) ||
+ Array.from(decoded).some(character => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) {
+ throw new Error("Invalid export path");
+ }
+ let next;
+ try {
+ next = decodeURIComponent(decoded);
+ } catch (error) {
+ return decoded;
+ }
+ if (next === decoded) {
+ return decoded;
+ }
+ decoded = next;
+ }
+ throw new Error("Invalid export encoding");
+ });
+ if (segments[0] === "temp") {
+ throw new Error("Invalid export path");
+ }
+ // 文件名仅作为保存对话框的建议值,不接受服务器提供的本机目录。
+ const name = segments[segments.length - 1].replace(/[<>:"|?*]/g, "_");
+ return {url: url.href, name};
+};
+
+const saveRemoteExport = async ({uri, origin, choosePath, fetch, signal}) => {
+ const {url, name} = resolveRemoteExportURL(uri, origin);
+ const result = await choosePath(name);
+ if (result.canceled || !result.filePath) {
+ return {status: "canceled"};
+ }
+ // 使用当前连接的会话下载附件,不跟随登录页或其他重定向。
+ const response = await fetch(url, {
+ credentials: "include", redirect: "manual", bypassCustomProtocolHandlers: true, signal,
+ });
+ if (!response.ok || !response.body || !/^attachment(?:;|$)/i.test(response.headers.get("content-disposition") || "")) {
+ await response.body?.cancel();
+ throw new Error("Export download failed");
+ }
+ const temporaryPath = path.join(path.dirname(result.filePath), ".siyuan-export-" + randomUUID() + ".tmp");
+ try {
+ // 下载完成后再替换目标,失败时保留用户已有的文件。
+ await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(temporaryPath, {flags: "wx", mode: 0o600}), {signal});
+ await fs.promises.rename(temporaryPath, result.filePath);
+ } finally {
+ await fs.promises.rm(temporaryPath, {force: true});
+ }
+ return {status: "success", name: path.basename(result.filePath)};
+};
+
+module.exports = {resolveRemoteExportURL, saveRemoteExport};
diff --git a/app/electron/remoteExport.test.js b/app/electron/remoteExport.test.js
new file mode 100644
index 0000000000..3cb53928e3
--- /dev/null
+++ b/app/electron/remoteExport.test.js
@@ -0,0 +1,78 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const os = require("node:os");
+const path = require("node:path");
+const {test} = require("node:test");
+const {resolveRemoteExportURL, saveRemoteExport} = require("./remoteExport");
+
+const origin = "https://notes.example.com";
+
+test("remote downloads accept only export attachments from the current kernel", () => {
+ assert.deepEqual(resolveRemoteExportURL("/export/notes%20archive.zip", origin), {
+ url: origin + "/export/notes%20archive.zip", name: "notes archive.zip",
+ });
+ assert.equal(resolveRemoteExportURL("/export/100%25.zip", origin).name, "100%.zip");
+ for (const uri of ["https://other.example.com/export/a.zip", "//other.example.com/export/a.zip",
+ "file:///export/a.zip", "/api/file/getFile", "/export/temp/a.html", "/export/%74emp/a.html",
+ "/export/a%2fb.zip", "/export/%252e%252e/a.zip", "/export/a%00.zip", "/export/a.zip?download=true",
+ "https://[email protected]/export/a.zip", "/export/", "/export/a\\b.zip"]) {
+ assert.throws(() => resolveRemoteExportURL(uri, origin), undefined, uri);
+ }
+});
+
+test("canceling the save picker does not start a request", async () => {
+ const result = await saveRemoteExport({uri: "/export/a.zip", origin,
+ choosePath: async () => ({canceled: true}),
+ fetch: () => assert.fail("Unexpected request"),
+ });
+ assert.deepEqual(result, {status: "canceled"});
+});
+
+test("downloads stream with the authenticated session and replace the chosen file only on completion", async t => {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "siyuan-remote-export-"));
+ t.after(() => fs.rm(directory, {recursive: true, force: true}));
+ const filePath = path.join(directory, "chosen.zip");
+ await fs.writeFile(filePath, "previous");
+ const result = await saveRemoteExport({uri: "/export/source.zip", origin,
+ choosePath: async name => {
+ assert.equal(name, "source.zip");
+ return {filePath};
+ },
+ fetch: async (url, options) => {
+ assert.equal(url, origin + "/export/source.zip");
+ assert.equal(options.credentials, "include");
+ assert.equal(options.redirect, "manual");
+ assert.equal(options.bypassCustomProtocolHandlers, true);
+ assert.equal(await fs.readFile(filePath, "utf8"), "previous");
+ return new Response("downloaded", {headers: {"Content-Disposition": "attachment; filename=ignored.zip"}});
+ },
+ });
+ assert.deepEqual(result, {status: "success", name: "chosen.zip"});
+ assert.equal(await fs.readFile(filePath, "utf8"), "downloaded");
+ assert.deepEqual(await fs.readdir(directory), ["chosen.zip"]);
+});
+
+test("authentication errors, redirects, interrupted streams and aborts preserve the destination", async t => {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "siyuan-remote-export-"));
+ t.after(() => fs.rm(directory, {recursive: true, force: true}));
+ const filePath = path.join(directory, "chosen.zip");
+ const controller = new AbortController();
+ controller.abort();
+ for (const scenario of [
+ {response: () => new Response("login", {status: 403})},
+ {response: () => new Response(null, {status: 302, headers: {Location: "/check-auth"}})},
+ {response: () => new Response("login", {headers: {"Content-Type": "text/html"}})},
+ {response: () => new Response(new ReadableStream({start(stream) {
+ stream.enqueue(new Uint8Array([1, 2, 3]));
+ stream.error(new Error("connection lost"));
+ }}), {headers: {"Content-Disposition": "attachment"}})},
+ {response: () => new Response("data", {headers: {"Content-Disposition": "attachment"}}), signal: controller.signal},
+ ]) {
+ await fs.writeFile(filePath, "previous");
+ await assert.rejects(saveRemoteExport({uri: "/export/a.zip", origin,
+ choosePath: async () => ({filePath}), fetch: async () => scenario.response(), signal: scenario.signal,
+ }));
+ assert.equal(await fs.readFile(filePath, "utf8"), "previous");
+ assert.deepEqual(await fs.readdir(directory), ["chosen.zip"]);
+ }
+});
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy
index 01667f2c31..f2c382c3af 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy
@@ -6,7 +6,7 @@
"id": "20260903150000-s4hctea",
"title": "Connect to a Remote Kernel",
"type": "doc",
- "updated": "20260914195107"
+ "updated": "20260929104853"
},
"Children": [
{"ID": "20260903150000-mz3r596", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-mz3r596", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Overview"}]},
@@ -26,15 +26,17 @@
{"ID": "20260908082237-vrsfycm", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-vrsfycm", "updated": "20260908110648"}, "Children": [{"Type": "NodeText", "Data": "For command-line use, completely exit the desktop client and start it with "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port] --trust-remote-extensions"}, {"Type": "NodeText", "Data": ". This command-line option trusts only the server specified for this launch. It does not change saved GUI trust settings or get added automatically to launch-at-login arguments. Command-line startup does not read GUI trust settings. Starting another instance does not change the running instance’s trust state. To revoke trust, completely exit and start again without this option."}]},
{"ID": "20260908082237-czd7cy0", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-czd7cy0", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "Once enabled, plugins, theme scripts, icon scripts, and JavaScript code snippets from the remote workspace execute in the local desktop environment. They can use Node.js to read and write local files and execute programs. Use this option only if you trust the server and the extension code it supplies, including future updates."}]},
{"ID": "20260908082237-9eymwn3", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-9eymwn3", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "This option enables plugins, Bazaar, custom themes, icons, fonts, and code snippets. The bundled frontend, themes, and icons still come from the client. Widgets and the other remote-mode restrictions remain unchanged. Plugin code runs on the client while the workspace is on the server. Plugins that depend on local workspace paths, native modules, or external programs may require adaptation; compatibility with every desktop plugin is not guaranteed."}]},
- {"ID": "20260903150000-knpctlf", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-knpctlf", "updated": "20260914195107"}, "Children": [{"Type": "NodeText", "Data": "Limitations"}]},
+ {"ID": "20260929104853-9rh86m3", "Type": "NodeHeading", "Properties": {"id": "20260929104853-9rh86m3", "updated": "20260929104853"}, "Children": [{"Type": "NodeText", "Data": "Document import and export"}], "HeadingLevel": 2},
+ {"ID": "20260929104853-69ytgab", "Type": "NodeParagraph", "Properties": {"id": "20260929104853-69ytgab", "updated": "20260929104853"}, "Children": [{"Type": "NodeText", "Data": "Remote mode supports importing SiYuan .sy.zip and Markdown ZIP archives, and exporting documents as SiYuan .sy.zip, Markdown ZIP, images, and HTML ZIP archives. Select an archive on this device to upload it to the remote kernel. Exported files are downloaded through the current connection and saved to a location you choose on this device. Use the import and export menus in the document tree; the new-notebook dialog and data migration dialog also provide archive import."}]},
+ {"ID": "20260903150000-knpctlf", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-knpctlf", "updated": "20260929104853"}, "Children": [{"Type": "NodeText", "Data": "Limitations"}]},
{"ID": "20260903150000-lazpxpz", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-lazpxpz", "updated": "20260903205342"}, "Children": [{"Type": "NodeText", "Data": "Remote mode does not support the following features. Local mode is not affected:"}]},
{
"ID": "20260903150000-x3th06t",
"Type": "NodeList",
"ListData": {},
- "Properties": {"id": "20260903150000-x3th06t", "updated": "20260914195107"},
+ "Properties": {"id": "20260903150000-x3th06t", "updated": "20260929104853"},
"Children": [
- {"ID": "20260903150000-b45enwi", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-b45enwi", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-gbt9mdf", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-gbt9mdf", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Import and export"}]}]},
+ {"ID": "20260903150000-b45enwi", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-b45enwi", "updated": "20260929104853"}, "Children": [{"ID": "20260903150000-gbt9mdf", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-gbt9mdf", "updated": "20260929104853"}, "Children": [{"Type": "NodeText", "Data": "Direct import of Markdown files or folders and Obsidian vaults; Word and PDF export; full data, configuration, and backup import and export"}]}]},
{"ID": "20260903150000-mzhpk4r", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-mzhpk4r", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-88q1701", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-88q1701", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "File clipboard operations"}]}]},
{"ID": "20260903150000-5amb0yu", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-5amb0yu", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-j9eobwv", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-j9eobwv", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Operations that depend on a client-local path or a server absolute path, such as showing a file in the file manager or dragging in or opening a file by path; normal asset uploads through a file picker remain available"}]}]},
{"ID": "20260903150000-hxh4cr0", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-hxh4cr0", "updated": "20260908082237"}, "Children": [{"ID": "20260903150000-1f4zzal", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-1f4zzal", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "Desktop plugins, Bazaar, and custom appearance are disabled by default; the trust option described above enables remote plugins, Bazaar, custom themes, icons, fonts, and code snippets, while widgets remain unavailable"}]}]},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy
index 3319b2acb6..21eff21c43 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy
@@ -6,7 +6,7 @@
"id": "20260903150000-u4065fm",
"title": "连接远程内核",
"type": "doc",
- "updated": "20260914193156"
+ "updated": "20260929104942"
},
"Children": [
{
@@ -116,13 +116,42 @@
{"ID": "20260908082237-t1800dj", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-t1800dj", "updated": "20260908110648"}, "Children": [{"Type": "NodeText", "Data": "使用命令行时,完全退出桌面客户端后,可使用参数 "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port] --trust-remote-extensions"}, {"Type": "NodeText", "Data": " 启动。该命令行参数仅信任本次指定的服务器,不会修改图形界面保存的信任设置,也不会自动加入开机启动参数。命令行启动不会读取图形界面的信任设置。运行中的实例不会因再次启动而改变信任状态;如需撤销,请完全退出后去掉该参数重新启动。"}]},
{"ID": "20260908082237-6wn2z6e", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-6wn2z6e", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "开启后,远程工作空间中的插件、主题脚本、图标脚本和 JavaScript 代码片段会在本机桌面环境中执行,能够通过 Node.js 读写本机文件和执行程序。请仅在信任服务器及其提供的扩展代码(包括后续更新)时使用。"}]},
{"ID": "20260908082237-cfxcjm5", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-cfxcjm5", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "该选项开放插件、集市、自定义主题、图标、字体和代码片段。内置前端、主题和图标仍由客户端提供,小部件及其他远程模式限制保持不变。插件代码在客户端运行,工作空间位于服务器;依赖本地工作空间路径、原生模块或外部程序的插件可能需要适配,不能保证所有桌面插件都兼容。"}]},
+ {
+ "ID": "20260929104942-ctap3kj",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260929104942-ctap3kj",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "文档导入导出"
+ }
+ ],
+ "HeadingLevel": 2
+ },
+ {
+ "ID": "20260929104942-65vcmn0",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929104942-65vcmn0",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "远程模式支持导入 SiYuan .sy.zip 和 Markdown ZIP 压缩包,以及将文档导出为 SiYuan .sy.zip、Markdown ZIP、图片和 HTML ZIP 压缩包。选择本机压缩包后,文件会上传到远程内核;导出文件通过当前连接下载,并保存到你在本机选择的位置。可以使用文档树中的导入导出菜单,新建笔记本和数据迁移对话框也提供压缩包导入入口。"
+ }
+ ]
+ },
{
"ID": "20260903150000-bh8cy8d",
"Type": "NodeHeading",
"HeadingLevel": 2,
"Properties": {
"id": "20260903150000-bh8cy8d",
- "updated": "20260914193156"
+ "updated": "20260929104942"
},
"Children": [
{
@@ -151,7 +180,7 @@
"ListData": {},
"Properties": {
"id": "20260903150000-kvy0i58",
- "updated": "20260914193156"
+ "updated": "20260929104942"
},
"Children": [
{
@@ -163,7 +192,7 @@
},
"Properties": {
"id": "20260903150000-1g1xw92",
- "updated": "20260903150000"
+ "updated": "20260929104942"
},
"Children": [
{
@@ -171,12 +200,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260903150000-zljclps",
- "updated": "20260903150000"
+ "updated": "20260929104942"
},
"Children": [
{
"Type": "NodeText",
- "Data": "导入和导出"
+ "Data": "直接导入 Markdown 文件或文件夹、Obsidian 库;导出 Word 和 PDF;完整数据、配置和备份的导入导出"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy
index 3f4e95ff8d..722d8f9111 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy
@@ -6,7 +6,7 @@
"id": "20260903150000-3qa6edk",
"title": "連線至遠端內核",
"type": "doc",
- "updated": "20260914195107"
+ "updated": "20260929104942"
},
"Children": [
{"ID": "20260903150000-jrf9aw4", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-jrf9aw4", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概述"}]},
@@ -26,15 +26,85 @@
{"ID": "20260908082237-rkm8fy4", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-rkm8fy4", "updated": "20260908110648"}, "Children": [{"Type": "NodeText", "Data": "使用命令列時,完全結束桌面用戶端後,可使用參數 "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port] --trust-remote-extensions"}, {"Type": "NodeText", "Data": " 啟動。此命令列參數僅信任本次指定的伺服器,不會修改圖形介面儲存的信任設定,也不會自動加入開機啟動參數。命令列啟動不會讀取圖形介面的信任設定。執行中的實例不會因再次啟動而改變信任狀態;如需撤銷,請完全結束後移除此參數重新啟動。"}]},
{"ID": "20260908082237-q1w5tx8", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-q1w5tx8", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "啟用後,遠端工作空間中的外掛程式、佈景主題指令碼、圖示指令碼和 JavaScript 程式碼片段會在本機桌面環境中執行,能夠透過 Node.js 讀寫本機檔案和執行程式。請僅在信任伺服器及其提供的擴充程式碼(包括後續更新)時使用。"}]},
{"ID": "20260908082237-hz1tyvi", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-hz1tyvi", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "此選項開放外掛程式、集市、自訂佈景主題、圖示、字型和程式碼片段。內建前端、佈景主題和圖示仍由用戶端提供,小工具及其他遠端模式限制維持不變。外掛程式碼在用戶端執行,工作空間位於伺服器;依賴本機工作空間路徑、原生模組或外部程式的外掛程式可能需要調整,無法保證所有桌面外掛程式都相容。"}]},
- {"ID": "20260903150000-uleg2f1", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-uleg2f1", "updated": "20260914195107"}, "Children": [{"Type": "NodeText", "Data": "功能限制"}]},
+ {
+ "ID": "20260929104942-6kzfymp",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260929104942-6kzfymp",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "文件匯入匯出"
+ }
+ ],
+ "HeadingLevel": 2
+ },
+ {
+ "ID": "20260929104942-lg6he5t",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929104942-lg6he5t",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "遠端模式支援匯入 SiYuan .sy.zip 和 Markdown ZIP 壓縮檔,以及將文件匯出為 SiYuan .sy.zip、Markdown ZIP、圖片和 HTML ZIP 壓縮檔。選擇本機壓縮檔後,檔案會上傳至遠端核心;匯出檔案透過目前的連線下載,並儲存至你在本機選擇的位置。可以使用文件樹中的匯入匯出選單,新增筆記本和資料遷移對話框也提供壓縮檔匯入入口。"
+ }
+ ]
+ },
+ {
+ "ID": "20260903150000-uleg2f1",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260903150000-uleg2f1",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "功能限制"
+ }
+ ]
+ },
{"ID": "20260903150000-ovlxdje", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-ovlxdje", "updated": "20260903205342"}, "Children": [{"Type": "NodeText", "Data": "遠端模式不支援以下功能,本機模式不受影響:"}]},
{
"ID": "20260903150000-lw8m6qj",
"Type": "NodeList",
"ListData": {},
- "Properties": {"id": "20260903150000-lw8m6qj", "updated": "20260914195107"},
+ "Properties": {"id": "20260903150000-lw8m6qj", "updated": "20260929104942"},
"Children": [
- {"ID": "20260903150000-iaab0bj", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-iaab0bj", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-rj4jvo4", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-rj4jvo4", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "匯入和匯出"}]}]},
+ {
+ "ID": "20260903150000-iaab0bj",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260903150000-iaab0bj",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "ID": "20260903150000-rj4jvo4",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260903150000-rj4jvo4",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "直接匯入 Markdown 檔案或資料夾、Obsidian 儲存庫;匯出 Word 和 PDF;完整資料、設定和備份的匯入匯出"
+ }
+ ]
+ }
+ ]
+ },
{"ID": "20260903150000-o4d17am", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-o4d17am", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-uqpqmld", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-uqpqmld", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "檔案剪貼簿操作"}]}]},
{"ID": "20260903150000-7489c2g", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-7489c2g", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-gopw68q", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-gopw68q", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "依賴用戶端本機路徑或伺服器絕對路徑的操作,例如在檔案管理器中顯示,以及透過路徑拖入或開啟檔案;透過檔案選擇器進行一般資源上傳仍可使用"}]}]},
{"ID": "20260903150000-yn3mxw7", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-yn3mxw7", "updated": "20260908082237"}, "Children": [{"ID": "20260903150000-m8ot8ql", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-m8ot8ql", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "預設不支援桌面端外掛程式、集市和自訂外觀;可透過上述信任參數啟用遠端外掛程式、集市、自訂佈景主題、圖示、字型和程式碼片段,小工具仍不可用"}]}]},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy
index 1266fcf401..d99d875a23 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy
@@ -6,7 +6,7 @@
"id": "20260903150000-hpfmx4t",
"title": "リモートカーネルへの接続",
"type": "doc",
- "updated": "20260914195107"
+ "updated": "20260929104942"
},
"Children": [
{"ID": "20260903150000-ekjy0ld", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-ekjy0ld", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概要"}]},
@@ -26,15 +26,85 @@
{"ID": "20260908082237-qepobrf", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-qepobrf", "updated": "20260908110648"}, "Children": [{"Type": "NodeText", "Data": "コマンドラインを使う場合は、デスクトップクライアントを完全に終了してから、"}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port] --trust-remote-extensions"}, {"Type": "NodeText", "Data": " を指定して起動します。このコマンドラインオプションは今回指定したサーバーのみを信頼し、画面で保存した信頼設定を変更せず、ログイン時の自動起動引数にも自動では追加されません。コマンドライン起動では画面の信頼設定を読み取りません。別のインスタンスを起動しても、実行中のインスタンスの信頼状態は変わりません。信頼を取り消すには、完全に終了してからこのオプションを外して起動してください。"}]},
{"ID": "20260908082237-843e8r9", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-843e8r9", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "有効にすると、リモートワークスペースのプラグイン、テーマスクリプト、アイコンスクリプト、JavaScript コードスニペットがローカルのデスクトップ環境で実行されます。これらは Node.js を使ってローカルファイルの読み書きやプログラムの実行ができます。サーバーと、今後の更新を含めてサーバーが提供する拡張機能のコードを信頼できる場合にのみ使用してください。"}]},
{"ID": "20260908082237-jlqabtc", "Type": "NodeParagraph", "Properties": {"id": "20260908082237-jlqabtc", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "このオプションはプラグイン、マーケットプレイス、カスタムテーマ、アイコン、フォント、コードスニペットを有効にします。内蔵のフロントエンド、テーマ、アイコンは引き続きクライアントから読み込みます。ウィジェットおよびその他のリモートモードの制限は変わりません。プラグインのコードはクライアントで実行され、ワークスペースはサーバーにあります。ローカルのワークスペースパス、ネイティブモジュール、外部プログラムに依存するプラグインには対応作業が必要な場合があり、すべてのデスクトッププラグインとの互換性は保証されません。"}]},
- {"ID": "20260903150000-uo7ekyt", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-uo7ekyt", "updated": "20260914195107"}, "Children": [{"Type": "NodeText", "Data": "機能制限"}]},
+ {
+ "ID": "20260929104942-2f8mr79",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260929104942-2f8mr79",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ドキュメントのインポートとエクスポート"
+ }
+ ],
+ "HeadingLevel": 2
+ },
+ {
+ "ID": "20260929104942-srep5wb",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260929104942-srep5wb",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "リモートモードでは、SiYuan .sy.zip と Markdown ZIP のインポート、およびドキュメントの SiYuan .sy.zip、Markdown ZIP、画像、HTML ZIP へのエクスポートに対応しています。このデバイスで圧縮ファイルを選択すると、リモートカーネルにアップロードされます。エクスポートしたファイルは現在の接続を通じてダウンロードされ、このデバイスで選択した場所に保存されます。ドキュメントツリーのインポートとエクスポートのメニューを利用できます。ノートブックの新規作成とデータ移行のダイアログからも圧縮ファイルをインポートできます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260903150000-uo7ekyt",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260903150000-uo7ekyt",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "機能制限"
+ }
+ ]
+ },
{"ID": "20260903150000-zbe0bfm", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-zbe0bfm", "updated": "20260903205342"}, "Children": [{"Type": "NodeText", "Data": "リモートモードでは、次の機能を利用できません。ローカルモードには影響しません。"}]},
{
"ID": "20260903150000-8orlk9f",
"Type": "NodeList",
"ListData": {},
- "Properties": {"id": "20260903150000-8orlk9f", "updated": "20260914195107"},
+ "Properties": {"id": "20260903150000-8orlk9f", "updated": "20260929104942"},
"Children": [
- {"ID": "20260903150000-b5xb7ub", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-b5xb7ub", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-t5961l9", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-t5961l9", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "インポートとエクスポート"}]}]},
+ {
+ "ID": "20260903150000-b5xb7ub",
+ "Type": "NodeListItem",
+ "ListData": {
+ "BulletChar": 42,
+ "Marker": "Kg=="
+ },
+ "Properties": {
+ "id": "20260903150000-b5xb7ub",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "ID": "20260903150000-t5961l9",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260903150000-t5961l9",
+ "updated": "20260929104942"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Markdown ファイルやフォルダー、Obsidian 保管庫の直接インポート、Word と PDF のエクスポート、全データ・設定・バックアップのインポートとエクスポート"
+ }
+ ]
+ }
+ ]
+ },
{"ID": "20260903150000-xoz3jw0", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-xoz3jw0", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-rme1xbh", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-rme1xbh", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "ファイルのクリップボード操作"}]}]},
{"ID": "20260903150000-3s8fcw7", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-3s8fcw7", "updated": "20260903150000"}, "Children": [{"ID": "20260903150000-p1m4g9q", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-p1m4g9q", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "クライアントのローカルパスまたはサーバーの絶対パスに依存する操作(ファイルマネージャーでの表示や、パスを使ったファイルのドラッグ&ドロップまたはオープンなど)。ファイル選択ダイアログからの通常のアセットアップロードは引き続き利用できます"}]}]},
{"ID": "20260903150000-j3snjto", "Type": "NodeListItem", "ListData": {"BulletChar": 42, "Marker": "Kg=="}, "Properties": {"id": "20260903150000-j3snjto", "updated": "20260908082237"}, "Children": [{"ID": "20260903150000-adyybel", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-adyybel", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "デスクトッププラグイン、マーケットプレイス、カスタム外観は既定では無効です。上記の信頼オプションでリモートのプラグイン、マーケットプレイス、カスタムテーマ、アイコン、フォント、コードスニペットを有効にできますが、ウィジェットは引き続き利用できません"}]}]},
diff --git a/app/src/config/index.ts b/app/src/config/index.ts
index 2a282df843..b3c1c2ec98 100644
--- a/app/src/config/index.ts
+++ b/app/src/config/index.ts
@@ -110,7 +110,7 @@ export const openSetting = (app: App, tab?: TSettingTab) => {
if (tab === "bazaar" && !isBazaarAvailable()) {
return;
}
- if (tab === "export" && !getHostCapabilities().importExport) {
+ if (tab === "export" && !getHostCapabilities().documentImportExport) {
return;
}
/// #if MOBILE
diff --git a/app/src/config/setting/tabs.ts b/app/src/config/setting/tabs.ts
index 50699e472c..2202325ce1 100644
--- a/app/src/config/setting/tabs.ts
+++ b/app/src/config/setting/tabs.ts
@@ -88,7 +88,7 @@ const settingTabs = {
id: "export",
icon: "iconUpload",
title: () => window.siyuan.languages.export,
- hidden: () => !getHostCapabilities().importExport,
+ hidden: () => !getHostCapabilities().documentImportExport,
defaultSave: exportConfigApi.patch,
}, registerExportTab),
search: setting.tab({
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index e684be52be..70303c8b37 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -2195,7 +2195,7 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
}
}).element);
}
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({
id: "importNotebook",
icon: "iconDownload",
diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.ts
index 411a580951..fd0d031007 100644
--- a/app/src/menus/commonMenuItem.ts
+++ b/app/src/menus/commonMenuItem.ts
@@ -584,7 +584,7 @@ export const copySubMenu = (ids: string[], accelerator = true, focusElement?: El
};
export const exportMd = (id: string) => {
- if (window.siyuan.isPublish || !getHostCapabilities().importExport) {
+ if (window.siyuan.isPublish || !getHostCapabilities().documentImportExport) {
return;
}
return new MenuItem({
@@ -594,6 +594,7 @@ export const exportMd = (id: string) => {
icon: "iconUpload",
submenu: [{
id: "exportTemplate",
+ ignore: !getHostCapabilities().importExport,
label: window.siyuan.languages.template,
iconClass: "ft__error",
icon: "iconMarkdown",
@@ -727,6 +728,7 @@ ${databaseOptions}`,
/// #if !BROWSER
{
id: "exportPDF",
+ ignore: !getHostCapabilities().importExport,
label: "PDF",
icon: "iconPDF",
click: () => {
@@ -749,6 +751,7 @@ ${databaseOptions}`,
}
}, {
id: "exportWord",
+ ignore: !getHostCapabilities().importExport,
label: "Word .docx",
icon: "iconDocx",
click: () => {
@@ -756,6 +759,7 @@ ${databaseOptions}`,
}
}, {
id: "exportMore",
+ ignore: !getHostCapabilities().importExport,
label: window.siyuan.languages.more,
icon: "iconMore",
type: "submenu",
@@ -874,7 +878,7 @@ ${databaseOptions}`,
id: "exportPDF",
label: window.siyuan.languages.print,
icon: "iconPDF",
- ignore: !isInMobileApp(),
+ ignore: !isInMobileApp() || !getHostCapabilities().importExport,
click: () => {
const msgId = showMessage(window.siyuan.languages.exporting);
const localData = window.siyuan.storage[Constants.LOCAL_EXPORTPDF];
diff --git a/app/src/menus/dataMigration.ts b/app/src/menus/dataMigration.ts
index f59f8bd121..c1654d93b4 100644
--- a/app/src/menus/dataMigration.ts
+++ b/app/src/menus/dataMigration.ts
@@ -78,7 +78,7 @@ const exportData = async () => {
};
export const openDataMigration = (options: IDataMigrationOptions = {}) => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
const mode = options.mode || "manage";
@@ -90,7 +90,7 @@ export const openDataMigration = (options: IDataMigrationOptions = {}) => {
`<option value="${item.id}"${item.id === selectedNotebookID ? " selected" : ""}>${escapeHtml(item.name)}</option>`).join("");
let nativeImportHTML = "";
/// #if !BROWSER
- nativeImportHTML = `<button class="b3-list-item fn__block" data-type="markdown-file"${notebooks.length === 0 ? " disabled" : ""}>
+ nativeImportHTML = getHostCapabilities().localFileSystem ? `<button class="b3-list-item fn__block" data-type="markdown-file"${notebooks.length === 0 ? " disabled" : ""}>
<svg class="b3-list-item__graphic"><use xlink:href="#iconMarkdown"></use></svg>
<span class="b3-list-item__text">Markdown ${window.siyuan.languages.doc}</span>
</button>
@@ -101,7 +101,7 @@ export const openDataMigration = (options: IDataMigrationOptions = {}) => {
<button class="b3-list-item fn__block" data-type="obsidian">
<svg class="b3-list-item__graphic"><use xlink:href="#iconObsidian"></use></svg>
<span class="b3-list-item__text">Obsidian Vault</span>
-</button>`;
+</button>` : "";
/// #endif
const dialog = new Dialog({
title: window.siyuan.languages.dataMigration,
@@ -114,14 +114,14 @@ export const openDataMigration = (options: IDataMigrationOptions = {}) => {
<span class="b3-list-item__text">SiYuan .sy.zip</span>
<input class="b3-form__upload" data-type="siyuan" type="file" accept="application/zip">
</label>
- <div class="b3-list-item b3-list-item--warning fn__flex-wrap data-migration__item">
+ ${getHostCapabilities().importExport ? `<div class="b3-list-item b3-list-item--warning fn__flex-wrap data-migration__item">
<svg class="b3-list-item__graphic"><use xlink:href="#iconDatabase"></use></svg>
<span class="b3-list-item__text">Data.zip</span>
<span class="data-migration__actions">
${getImportButton("data", "application/zip")}
${getExportButton("export-data", mode)}
</span>
- </div>
+ </div>` : ""}
</div>
<div class="fn__hr"></div>
<div class="b3-label__text">${window.siyuan.languages.importFromMoreApps}</div>
@@ -135,7 +135,7 @@ export const openDataMigration = (options: IDataMigrationOptions = {}) => {
${nativeImportHTML}
</div>
<div class="fn__hr"></div>
- <div class="b3-label__text">${window.siyuan.languages.settingsAndSync}</div>
+ ${getHostCapabilities().importExport ? `<div class="b3-label__text">${window.siyuan.languages.settingsAndSync}</div>
<div class="fn__hr"></div>
<div class="b3-list b3-list--background">
<div class="b3-list-item fn__flex-wrap data-migration__item">
@@ -169,7 +169,7 @@ export const openDataMigration = (options: IDataMigrationOptions = {}) => {
${hasRepoKey ? `<button class="b3-button b3-button--outline" data-action="copy-key"><svg><use xlink:href="#iconCopy"></use></svg>${window.siyuan.languages.copy}</button>` : `<button class="b3-button b3-button--outline" data-action="import-key"><svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.import}</button>`}
</span>
</div>`}
- </div>
+ </div>` : ""}
</div>`,
width: "560px",
});
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 2547ce0046..81917710db 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -183,7 +183,7 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
}
}).element);
}
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
const ignoreExport = notebookIds.some((notebookId) => isEncryptedBox(notebookId));
window.siyuan.menus.menu.append(new MenuItem({
id: "separator_2",
@@ -363,12 +363,12 @@ const initMultiMenu = (selectItemElements: NodeListOf<HTMLElement>, app: App) =>
icon: "iconRiffCard",
submenu: riffCardMenu,
}).element);
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
}
}
openEditorTab(app, blockIDs);
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({
id: "export",
label: window.siyuan.languages.export,
@@ -645,7 +645,7 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {
}
}).element);
}
- if (getHostCapabilities().localFileSystem || getHostCapabilities().importExport) {
+ if (getHostCapabilities().localFileSystem || getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
}
/// #if !BROWSER
@@ -662,7 +662,7 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {
/// #endif
genImportMenu(notebookId, "/");
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({
id: "export",
label: window.siyuan.languages.export,
@@ -1062,7 +1062,7 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, l
};
export const genImportMenu = (notebookId: string, pathString: string) => {
- if (window.siyuan.config.readonly || !getHostCapabilities().importExport) {
+ if (window.siyuan.config.readonly || !getHostCapabilities().documentImportExport) {
return;
}
const reloadDocTree = () => {
@@ -1082,6 +1082,7 @@ export const genImportMenu = (notebookId: string, pathString: string) => {
const importstdmd = (label: string, isDoc?: boolean) => {
return {
id: isDoc ? "importMarkdownDoc" : "importMarkdownFolder",
+ ignore: !getHostCapabilities().localFileSystem,
icon: isDoc ? "iconMarkdown" : "iconFolder",
label,
click: async () => {
diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.ts
index 7af6500148..8ff3dccf43 100644
--- a/app/src/menus/workspace.ts
+++ b/app/src/menus/workspace.ts
@@ -432,7 +432,7 @@ export const workspaceMenu = async (app: App, rect: DOMRect) => {
openHistory(app);
}
}).element);
- if (!window.siyuan.config.readonly && getHostCapabilities().importExport) {
+ if (!window.siyuan.config.readonly && getHostCapabilities().documentImportExport) {
window.siyuan.menus.menu.append(new MenuItem({
id: "dataMigration",
label: window.siyuan.languages.dataMigration,
diff --git a/app/src/onboarding/index.ts b/app/src/onboarding/index.ts
index 42e6112083..31761c4c27 100644
--- a/app/src/onboarding/index.ts
+++ b/app/src/onboarding/index.ts
@@ -107,7 +107,7 @@ const renderOnboarding = (app: App) => {
</button>
<div class="onboarding__title">&#x1F389; ${window.siyuan.languages.onboardingWelcome}</div>
<div class="onboarding__desc">${window.siyuan.languages.onboardingDescription}</div>
-${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outline fn__block" data-type="import">
+${getHostCapabilities().documentImportExport ? `<button class="b3-button b3-button--outline fn__block" data-type="import">
<svg><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.importExistingData}
</button>` : ""}
<button class="b3-button b3-button--outline fn__block" data-type="sync">
@@ -126,7 +126,7 @@ ${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outl
dismissOnboarding();
break;
case "import":
- if (getHostCapabilities().importExport) {
+ if (getHostCapabilities().documentImportExport) {
openDataMigration({
mode: "onboarding",
notebookID: window.siyuan.config.onboarding.notebookID,
diff --git a/app/src/protyle/export/exportMd.ts b/app/src/protyle/export/exportMd.ts
index 0ca31f7ccf..ae63592f23 100644
--- a/app/src/protyle/export/exportMd.ts
+++ b/app/src/protyle/export/exportMd.ts
@@ -144,7 +144,7 @@ interface IExportMdOptionsPayload {
// exportMarkdownZip 为 Markdown .zip 导出入口:弹参数对话框,确认后按文档、文档集合或笔记本集合调用对应 API。
// 单文档时先查询文档信息,若无子文档/关联文档则隐藏对应配置项,减少干扰。
export const exportMarkdownZip = async(options: IExportMdOptions) => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
let showSubDocs = true;
diff --git a/app/src/protyle/export/index.ts b/app/src/protyle/export/index.ts
index 2987cd7ceb..d14fe1dd3e 100644
--- a/app/src/protyle/export/index.ts
+++ b/app/src/protyle/export/index.ts
@@ -12,7 +12,7 @@ import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {Dialog} from "../../dialog";
import {replaceLocalPath} from "../../editor/rename";
import {getScreenWidth, isInMobileApp, saveExportFile, setStorageVal} from "../util/compatibility";
-import {getFrontend} from "../../util/functions";
+import {getFrontend, isBrowser} from "../../util/functions";
import {isEncryptedBox} from "../../util/pathName";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {getLastExportPath, setLastExportPath} from "./path";
@@ -49,30 +49,28 @@ const getIconScript = (servePath: string) => {
};
export const saveExport = (option: IExportOptions) => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
- /// #if BROWSER
- if (["html", "htmlmd"].includes(option.type)) {
+ if ((isBrowser() || getHostCapabilities().remoteKernel) && ["html", "htmlmd"].includes(option.type)) {
const startExport = () => {
- const msgId = showMessage(window.siyuan.languages.exporting, -1);
- // 浏览器环境:先调用 API 生成资源文件,再在前端生成完整的 HTML
- const onExportHTML = async (exportResponse: APICallbackResponse<APIPOSTRoutes["/api/export/exportHTML"]["response"]>) => {
- const html = await onExport(exportResponse, undefined, "", option);
- fetchPost("/api/export/exportBrowserHTML", {
- folder: exportResponse.data.folder,
- html: html,
- name: exportResponse.data.name
- }, zipResponse => {
- // 与导出 .sy.zip/markdown.zip/图片一致,统一走 saveExportFile,以便移动端原生 App 调用 JSAndroid.saveExportFile 等接口保存到本地
- saveExportFile(zipResponse.data.zip, msgId);
- });
- };
- if (option.type === "htmlmd") {
- fetchPost("/api/export/exportMdHTML", {id: option.id, savePath: ""}, onExportHTML);
- } else {
- fetchPost("/api/export/exportHTML", {id: option.id, pdf: false, merge: true, savePath: ""}, onExportHTML);
- }
+ const msgId = showMessage(window.siyuan.languages.exporting, -1);
+ // 浏览器和远程连接先生成资源与完整 HTML,再下载服务器打包的导出物。
+ const onExportHTML = async (exportResponse: APICallbackResponse<APIPOSTRoutes["/api/export/exportHTML"]["response"]>) => {
+ const html = await onExport(exportResponse, undefined, "", option);
+ fetchPost("/api/export/exportBrowserHTML", {
+ folder: exportResponse.data.folder,
+ html: html,
+ name: exportResponse.data.name
+ }, zipResponse => {
+ saveExportFile(zipResponse.data.zip, msgId);
+ });
+ };
+ if (option.type === "htmlmd") {
+ fetchPost("/api/export/exportMdHTML", {id: option.id, savePath: ""}, onExportHTML);
+ } else {
+ fetchPost("/api/export/exportHTML", {id: option.id, pdf: false, merge: true, savePath: ""}, onExportHTML);
+ }
};
fetchPost("/api/block/getBlockInfo", {id: option.id}, (response) => {
if (response.code === 0 && isEncryptedBox(response.data.box)) {
@@ -83,7 +81,10 @@ export const saveExport = (option: IExportOptions) => {
});
return;
}
- /// #else
+ if (!getHostCapabilities().importExport) {
+ return;
+ }
+ /// #if !BROWSER
if (option.type === "pdf") {
if (window.siyuan.config.appearance.mode === 1) {
confirmDialog(window.siyuan.languages.pdfTip, window.siyuan.languages.pdfConfirm, () => {
diff --git a/app/src/protyle/export/util.ts b/app/src/protyle/export/util.ts
index a820343a1d..20d2dc27ab 100644
--- a/app/src/protyle/export/util.ts
+++ b/app/src/protyle/export/util.ts
@@ -14,7 +14,7 @@ import {highlightRender, lineNumberRender} from "../render/highlightRender";
import {processRender} from "../util/processCode";
import {isInAndroid, isIPad, isIPhone, isSafari, saveExportFile, setStorageVal} from "../util/compatibility";
import {useShell} from "../../util/pathName";
-import {getHostCapabilities} from "../../util/hostCapabilities";
+import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";
import {copyPNGByLink, writePNGBlob} from "../../menus/util";
// WebKit/Chromium 会拒绝宽度或高度超过此限制的 canvas,导致生成空白图像。
@@ -37,7 +37,7 @@ export const afterExport = (exportPath: string, msgId: string) => {
};
export const exportImage = (id: string, copyOnly = false) => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
const exportDialog = new Dialog({
@@ -120,7 +120,7 @@ export const exportImage = (id: string, copyOnly = false) => {
if (objectElement) {
const res = await fetch(objectElement.getAttribute("data"));
const response = await res.text();
- objectElement.insertAdjacentHTML("beforebegin", response as string);
+ objectElement.insertAdjacentHTML("beforebegin", sanitizeKernelHTML(response));
objectElement.remove();
}
}
@@ -282,7 +282,7 @@ export const exportImage = (id: string, copyOnly = false) => {
watermarkPreviewElement.innerHTML = "";
if (watermarkElement.checked) {
if (window.siyuan.config.export.imageWatermarkDesc) {
- watermarkPreviewElement.innerHTML = window.siyuan.config.export.imageWatermarkDesc;
+ watermarkPreviewElement.innerHTML = sanitizeKernelHTML(window.siyuan.config.export.imageWatermarkDesc);
} else if (window.siyuan.config.export.imageWatermarkStr) {
if (window.siyuan.config.export.imageWatermarkStr.startsWith("http")) {
watermarkPreviewElement.setAttribute("style", `background-image: url(${window.siyuan.config.export.imageWatermarkStr});background-repeat: repeat;position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: var(--b3-border-radius-b);`);
@@ -290,7 +290,7 @@ export const exportImage = (id: string, copyOnly = false) => {
await addScript(`${Constants.PROTYLE_CDN}/js/html-to-image.min.js?v=1.11.13`, "protyleHtml2image");
const width = Math.max(exportDialog.element.querySelector(".export-img").clientWidth / 3, 150);
watermarkPreviewElement.setAttribute("style", `width: ${width}px;height: ${width}px;display: flex;justify-content: center;align-items: center;color: var(--b3-border-color);font-size: 14px;`);
- watermarkPreviewElement.innerHTML = `<div style="transform: rotate(-45deg)">${window.siyuan.config.export.imageWatermarkStr}</div>`;
+ watermarkPreviewElement.innerHTML = sanitizeKernelHTML(`<div style="transform: rotate(-45deg)">${window.siyuan.config.export.imageWatermarkStr}</div>`);
const canvas = await window.htmlToImage.toCanvas(watermarkPreviewElement);
watermarkPreviewElement.innerHTML = "";
watermarkPreviewElement.setAttribute("style", `background-image: url(${canvas.toDataURL("image/png")});background-repeat: repeat;position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: var(--b3-border-radius-b);`);
@@ -304,9 +304,12 @@ export const exportImage = (id: string, copyOnly = false) => {
if (revision !== previewRevision) {
return;
}
- previewElement.innerHTML = response.data.content;
+ previewElement.innerHTML = sanitizeKernelHTML(response.data.content);
previewElement.setAttribute("data-doc-type", response.data.type || "NodeDocument");
Object.keys(response.data.attrs).forEach(key => {
+ if (getHostCapabilities().remoteKernel && !key.startsWith("custom-") && key !== "style") {
+ return;
+ }
previewElement.setAttribute(key, response.data.attrs[key]);
});
await renderExportJSEmbeds(previewElement, {
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index ff3c456d77..af607c61d1 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -3544,7 +3544,7 @@ export class Gutter {
id: "copyAsPNG",
iconHTML: "",
label: window.siyuan.languages.copyAsPNG,
- ignore: !getHostCapabilities().importExport,
+ ignore: !getHostCapabilities().documentImportExport,
click() {
exportImage(id, true);
}
diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.ts
index 8996ecda59..9e2dcae949 100644
--- a/app/src/protyle/header/openTitleMenu.ts
+++ b/app/src/protyle/header/openTitleMenu.ts
@@ -61,7 +61,7 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: stri
id: "copyAsPNG",
iconHTML: "",
label: window.siyuan.languages.copyAsPNG,
- ignore: !getHostCapabilities().importExport,
+ ignore: !getHostCapabilities().documentImportExport,
click() {
exportImage(protyle.block.showAll ? protyle.block.id : protyle.block.rootID, true);
}
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index e747c9bfb5..264e5269b0 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -1570,8 +1570,8 @@ export class Toolbar {
<span class="fn__space${protyle.disabled ? " fn__none" : ""}"></span>
<button data-type="after" class="block__icon block__icon--show b3-tooltips b3-tooltips__n${protyle.disabled ? " fn__none" : ""}" aria-label="${window.siyuan.languages.insertAfter}"><svg><use xlink:href="#iconAfter"></use></svg></button>
<span class="fn__space${protyle.disabled ? " fn__none" : ""}"></span>
- <button data-type="export" class="block__icon block__icon--show b3-tooltips b3-tooltips__n${getHostCapabilities().importExport ? "" : " fn__none"}" aria-label="${window.siyuan.languages.export} ${window.siyuan.languages.image}"><svg><use xlink:href="#iconImage"></use></svg></button>
- <span class="fn__space${getHostCapabilities().importExport ? "" : " fn__none"}"></span>
+ <button data-type="export" class="block__icon block__icon--show b3-tooltips b3-tooltips__n${getHostCapabilities().documentImportExport ? "" : " fn__none"}" aria-label="${window.siyuan.languages.export} ${window.siyuan.languages.image}"><svg><use xlink:href="#iconImage"></use></svg></button>
+ <span class="fn__space${getHostCapabilities().documentImportExport ? "" : " fn__none"}"></span>
<button data-type="pin" class="block__icon block__icon--show b3-tooltips b3-tooltips__n" aria-label="${window.siyuan.languages.pin}"><svg><use xlink:href="#iconPin"></use></svg></button>
<span class="fn__space"></span>
<button data-type="close" class="block__icon block__icon--show b3-tooltips b3-tooltips__n" aria-label="${window.siyuan.languages.close}"><svg><use xlink:href="#iconClose"></use></svg></button>
@@ -1689,7 +1689,7 @@ export class Toolbar {
}
});
const exportImg = () => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
const msgId = showMessage(window.siyuan.languages.exporting, 0);
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index e9665e77c1..c0e7824121 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -63,7 +63,7 @@ export const isPhablet = () => {
};
export const saveExportFile = async (uri: string, msgId?: string): Promise<TSaveExportFileResult> => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
if (msgId) {
hideMessage(msgId);
}
@@ -73,6 +73,23 @@ export const saveExportFile = async (uri: string, msgId?: string): Promise<TSave
return {status: "error"};
}
/// #if !BROWSER
+ if (getHostCapabilities().remoteKernel) {
+ let result: TSaveExportFileResult;
+ try {
+ result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "saveRemoteExport", uri});
+ } catch (error) {
+ result = {status: "error"};
+ }
+ if (msgId) {
+ hideMessage(msgId);
+ }
+ if (result.status === "success") {
+ showMessage(window.siyuan.languages.exported);
+ } else if (result.status === "error") {
+ showMessage(window.siyuan.languages.exportFileSaveFailed, 0, "error");
+ }
+ return result;
+ }
let saveErrorMsgId: string | undefined;
try {
const resolved = new URL(uri, `${location.origin}/`);
diff --git a/app/src/util/hostCapabilities.test.ts b/app/src/util/hostCapabilities.test.ts
index c3fd5225a6..d5a60ac81f 100644
--- a/app/src/util/hostCapabilities.test.ts
+++ b/app/src/util/hostCapabilities.test.ts
@@ -11,6 +11,14 @@ describe("trusted remote extension capabilities", () => {
trustRemoteExtensions: true,
};
+ it("allows document transfers without granting local paths or full data migration", () => {
+ const capabilities = resolveHostCapabilities(true, undefined, connection.kernelOrigin);
+ assert.equal(capabilities.documentImportExport, true);
+ assert.equal(capabilities.importExport, false);
+ assert.equal(capabilities.localFileSystem, false);
+ assert.equal(capabilities.ownsKernel, false);
+ });
+
it("only enables plugins and appearance for the matching host connection", () => {
const restricted = resolveHostCapabilities(true, undefined, connection.kernelOrigin);
assert.equal(restricted.plugins, false);
diff --git a/app/src/util/hostCapabilities.ts b/app/src/util/hostCapabilities.ts
index 0a9f929f51..3a4024821d 100644
--- a/app/src/util/hostCapabilities.ts
+++ b/app/src/util/hostCapabilities.ts
@@ -11,6 +11,7 @@ export type THostCapabilities = {
ownsKernel: boolean;
localFileSystem: boolean;
importExport: boolean;
+ documentImportExport: boolean;
plugins: boolean;
workspaces: boolean;
customAppearance: boolean;
@@ -58,6 +59,7 @@ export const resolveHostCapabilities = (remoteKernel: boolean, connection: TKern
ownsKernel,
localFileSystem: !remoteKernel,
importExport: !remoteKernel,
+ documentImportExport: true,
plugins: !remoteKernel || trustedExtensions,
workspaces: !remoteKernel,
customAppearance: !remoteKernel || trustedExtensions,
diff --git a/app/src/util/mount.ts b/app/src/util/mount.ts
index 7cb21010f3..8d05bb52a5 100644
--- a/app/src/util/mount.ts
+++ b/app/src/util/mount.ts
@@ -115,7 +115,7 @@ export const mountHelp = () => {
};
export const importNotebook = (file: File) => {
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
const formData = new ContractFormData({file});
@@ -131,7 +131,7 @@ export const newNotebook = () => {
<div class="b3-list-item fn__pointer" data-type="import-obsidian" role="button" tabindex="0"><svg class="b3-list-item__graphic"><use xlink:href="#iconObsidian"></use></svg><span class="b3-list-item__text">Obsidian Vault</span></div>`;
}
/// #endif
- const importHTML = getHostCapabilities().importExport ? `<div class="fn__hr"></div>
+ const importHTML = getHostCapabilities().documentImportExport ? `<div class="fn__hr"></div>
<div class="b3-label__text fn__pointer fn__flex" style="align-items: center;gap: 4px" data-type="toggle-import" role="button" tabindex="0" aria-expanded="false"><svg class="b3-list-item__arrow" style="display: block;flex: none;height: 14px;width: 14px" data-type="import-arrow"><use xlink:href="#iconRight"></use></svg><span style="line-height: 20px">${window.siyuan.languages.importFromMoreApps}</span></div>
<div class="b3-list--background fn__none" data-type="import-options" style="padding-top: 8px">
<label class="b3-list-item fn__pointer" data-type="import-sy"><svg class="b3-list-item__graphic"><use xlink:href="#iconSiYuan"></use></svg><span class="b3-list-item__text">SiYuan .sy.zip</span><input class="b3-form__upload" type="file" accept="application/zip"></label>
@@ -171,7 +171,7 @@ export const newNotebook = () => {
});
dialog.destroy();
});
- if (!getHostCapabilities().importExport) {
+ if (!getHostCapabilities().documentImportExport) {
return;
}
const createNotebookForImport = (fallbackName: string, callback: (notebookID: string) => void) => {
@@ -231,6 +231,9 @@ export const newNotebook = () => {
});
});
/// #if !BROWSER
+ if (!getHostCapabilities().localFileSystem) {
+ return;
+ }
const importMarkdown = async (isFile: boolean) => {
const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
cmd: "showOpenDialog",
diff --git a/app/tests/remoteDocumentTransfer.test.js b/app/tests/remoteDocumentTransfer.test.js
new file mode 100644
index 0000000000..d0ea3244d1
--- /dev/null
+++ b/app/tests/remoteDocumentTransfer.test.js
@@ -0,0 +1,186 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const {transpileModule, ModuleKind, ScriptTarget} = require("typescript");
+const {parse} = require("ifdef-loader/preprocessor");
+
+const createEnvironment = ({browser = false, mobile = false, remote = true} = {}) => {
+ const menus = [];
+ const requests = [];
+ const saved = [];
+ const messages = [];
+ const hidden = [];
+ const capabilities = {remoteKernel: remote, documentImportExport: true, importExport: !remote, localFileSystem: !remote};
+ const window = {navigator: {userAgent: "Desktop"}, location: {origin: "https://notes.example.com"}, siyuan: {
+ languages: new Proxy({}, {get: (_, key) => String(key)}), notebooks: [], storage: {},
+ menus: {menu: {append: menu => menus.push(menu)}},
+ config: {readonly: false, repo: {}, system: {container: "std"}, appearance: {mode: 0, themeLight: "daylight", themeDark: "midnight"}, editor: {}, export: {}},
+ }};
+ const dependencies = {
+ "util/hostCapabilities": {getHostCapabilities: () => capabilities},
+ "util/functions": {isBrowser: () => browser, isMobile: () => mobile, getFrontend: () => "desktop"},
+ "util/pathName": {isEncryptedBox: () => false},
+ "util/assets": {getThemeMode: () => 0, setInlineStyle: async () => ""},
+ "constants": {Constants: {SIYUAN_GET: "siyuan-get", HELP_PATH: {}}},
+ "menus/Menu": {MenuItem: class {constructor(options) {this.element = options;}}},
+ "dialog/message": {showMessage: (...args) => {messages.push(args); return "message";}, hideMessage: id => hidden.push(id)},
+ "dialog/confirmDialog": {confirmDialog: (_title, _text, callback) => callback()},
+ "util/fetch": {fetchPost: (...args) => requests.push(args), fetchSyncPost: async () => ({code: 0, data: []})},
+ "protyle/util/compatibility": {
+ saveExportFile: uri => saved.push(uri), isInMobileApp: () => mobile, getScreenWidth: () => 800,
+ },
+ "electron": {ipcRenderer: {invoke: async (_channel, data) => {
+ assert.equal(data.cmd, "saveRemoteExport");
+ saved.push(data.uri);
+ return {status: "success"};
+ }}},
+ };
+ const load = name => {
+ const source = fs.readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8");
+ const code = transpileModule(parse(source, {BROWSER: browser, MOBILE: mobile}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText;
+ const exports = {};
+ runInNewContext(code, {
+ exports, window, navigator: window.navigator, location: window.location, console, URL, Map, FormData,
+ document: {querySelectorAll: () => []},
+ fetch: () => assert.fail("Unexpected kernel file-copy request"),
+ require: relative => {
+ const id = relative.startsWith(".") ? path.posix.normalize(path.posix.join(path.posix.dirname(name), relative)) : relative;
+ return dependencies[id] || {};
+ },
+ });
+ return exports;
+ };
+ dependencies["util/contractFormData"] = load("util/contractFormData");
+ return {load, window, dependencies, capabilities, menus, requests, saved, messages, hidden};
+};
+
+test("remote document menus expose archive transfers, images and HTML without local-only operations", () => {
+ const env = createEnvironment();
+ const menu = env.load("menus/commonMenuItem").exportMd("doc");
+ assert.deepEqual(Array.from(menu.submenu.filter(item => !item.ignore), item => item.id), [
+ "exportSiYuanZip", "exportMarkdown", "exportImage", "exportHTML_SiYuan", "exportHTML_Markdown",
+ ]);
+ env.load("menus/navigation").genImportMenu("notebook", "/doc.sy");
+ const items = env.menus[0].submenu.filter(item => !item.ignore);
+ assert.deepEqual(Array.from(items, item => item.id), ["importSiYuanZip", "importMarkdownZip"]);
+ const file = new File(["archive"], "notes.zip", {type: "application/zip"});
+ items.forEach(item => {
+ let change;
+ item.bind({querySelector: () => ({addEventListener: (_type, callback) => {change = callback;}})});
+ change({target: {files: [file]}});
+ });
+ assert.deepEqual(env.requests.map(request => request[0]), ["/api/import/importSY", "/api/import/importZipMd"]);
+ env.requests.forEach(([, form]) => {
+ assert.equal(form.get("file"), file);
+ assert.equal(form.get("notebook"), "notebook");
+ assert.equal(form.get("toPath"), "/doc.sy");
+ assert.equal(form.has("localPath"), false);
+ });
+ env.window.siyuan.config.readonly = true;
+ env.load("menus/navigation").genImportMenu("notebook", "/");
+ assert.equal(env.menus.length, 1);
+});
+
+test("local desktop and mobile retain their document export choices", () => {
+ for (const options of [{remote: false}, {remote: false, browser: true, mobile: true}]) {
+ const env = createEnvironment(options);
+ const items = env.load("menus/commonMenuItem").exportMd("doc").submenu.filter(item => !item.ignore);
+ assert.ok(items.some(item => item.id === "exportPDF"));
+ assert.ok(items.some(item => item.id === "exportTemplate"));
+ assert.equal(items.some(item => item.id === "exportWord"), !options.mobile);
+ }
+});
+
+test("remote saves use IPC and preserve canceled/error outcomes without kernel path copying", async () => {
+ const env = createEnvironment();
+ const {saveExportFile} = env.load("protyle/util/compatibility");
+ for (const status of ["success", "canceled", "error"]) {
+ env.dependencies.electron.ipcRenderer.invoke = async (_channel, data) => {
+ assert.equal(data.cmd, "saveRemoteExport");
+ assert.equal(data.uri, "/export/doc.zip");
+ return {status};
+ };
+ const result = await saveExportFile("/export/doc.zip", "progress");
+ assert.equal(result.status, status);
+ }
+ assert.deepEqual(env.hidden, ["progress", "progress", "progress"]);
+ assert.deepEqual(env.messages.map(message => message[0]), ["exported", "exportFileSaveFailed"]);
+});
+
+test("browser and native mobile continue to save through their own download handlers", async () => {
+ const browser = createEnvironment({remote: false, browser: true});
+ browser.window.open = uri => browser.saved.push(uri);
+ assert.equal((await browser.load("protyle/util/compatibility").saveExportFile("/export/doc.zip")).status, "success");
+ assert.deepEqual(browser.saved, ["https://notes.example.com/export/doc.zip?download=true"]);
+ const mobile = createEnvironment({remote: false, browser: true, mobile: true});
+ mobile.window.siyuan.config.system.container = "android";
+ mobile.window.JSAndroid = {saveExportFile: uri => mobile.saved.push(uri)};
+ assert.equal((await mobile.load("protyle/util/compatibility").saveExportFile("/export/doc.zip")).status, "success");
+ assert.deepEqual(mobile.saved, ["/export/doc.zip"]);
+});
+
+test("remote notebook and migration dialogs offer archive uploads without binding local file controls", () => {
+ const env = createEnvironment();
+ const contents = [];
+ env.dependencies.dialog = {Dialog: class {
+ constructor(options) {
+ contents.push(options.content);
+ this.element = {
+ setAttribute() {}, addEventListener() {},
+ querySelector: selector => {
+ const attribute = selector.match(/\[([^\]]+)\]/)?.[1];
+ if (!attribute || !options.content.includes(attribute)) {
+ return null;
+ }
+ return {value: "", addEventListener() {}, querySelector: () => ({})};
+ },
+ };
+ }
+ bindInput() {}
+ }};
+ env.load("util/mount").newNotebook();
+ env.load("menus/dataMigration").openDataMigration();
+ assert.equal(contents.length, 2);
+ for (const content of contents) {
+ assert.ok(content.includes("SiYuan .sy.zip"));
+ assert.ok(content.includes("Markdown .zip"));
+ assert.ok(!content.includes("Obsidian"));
+ assert.ok(!content.includes("Data.zip"));
+ assert.ok(!content.includes('data-type="conf"'));
+ assert.ok(!content.includes('data-type="markdown-file"'));
+ }
+});
+
+test("remote and browser HTML exports package server artifacts without sending a local save path", async () => {
+ for (const browser of [false, true]) {
+ for (const type of ["html", "htmlmd"]) {
+ const env = createEnvironment({browser, remote: !browser});
+ let completed;
+ const complete = new Promise(resolve => {completed = resolve;});
+ env.dependencies["util/fetch"].fetchPost = async (url, payload, callback) => {
+ env.requests.push([url, payload]);
+ if (url === "/api/block/getBlockInfo") {
+ callback({code: 0, data: {box: "notebook"}});
+ } else if (url === "/api/export/exportBrowserHTML") {
+ assert.equal(payload.folder, "artifact");
+ assert.ok(payload.html.includes("Document content"));
+ callback({code: 0, data: {zip: "/export/doc.zip"}});
+ completed();
+ } else {
+ assert.equal(payload.savePath, "");
+ await callback({code: 0, data: {folder: "artifact", name: "Document", content: "Document content"}});
+ }
+ };
+ const {saveExport} = env.load("protyle/export/index");
+ saveExport({type, id: "doc"});
+ await complete;
+ assert.deepEqual(env.requests.map(request => request[0]), ["/api/block/getBlockInfo",
+ type === "html" ? "/api/export/exportHTML" : "/api/export/exportMdHTML", "/api/export/exportBrowserHTML"]);
+ assert.deepEqual(env.saved, ["/export/doc.zip"]);
+ }
+ }
+});