示例工程 32-deep-links-file-association
32-deep-links-file-association/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertFileReq, assertUrlReq, CH, } from "../shared/ipc";
import { parseDeepLink } from "../shared/deep-link";
import { parseWorkFile, validateWorkPath } from "../shared/work-file";
app.setName("Deep Link Lab");
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData = isSmoke || isShots
? path.join(os.tmpdir(), `deep-link-${isSmoke ? "smoke" : "shots"}-${process.pid}`)
: "";
if (tempData)
app.setPath("userData", tempData);
let win = null;
let lastLink = null;
let lastFile = null;
let lastError = "";
let events = [];
let samplePath = "";
const singleInstance = app.requestSingleInstanceLock();
if (!singleInstance) {
app.quit();
}
function sampleFile() {
const file = path.join(app.getPath("userData"), "welcome.xwrt");
fsSync.mkdirSync(path.dirname(file), { recursive: true });
fsSync.writeFileSync(file, `${JSON.stringify({
title: "欢迎使用 Deep Link 工作台",
body: "这是通过文件关联打开的示例文件。\n扩展名 .xwrt,内容为 JSON;读取上限 64KB。",
})}\n`, "utf8");
return file;
}
function addEvent(source, text) {
events = [{ at: Date.now(), source, text }, ...events].slice(0, 30);
}
function focusWindow() {
if (!win || win.isDestroyed())
return;
win.show();
win.focus();
}
function handleUrl(raw, source) {
const parsed = parseDeepLink(raw);
if (!parsed.ok) {
lastLink = null;
lastError = parsed.reason;
addEvent(source, `拒绝链接:${parsed.reason}`);
focusWindow();
broadcast();
return;
}
lastError = "";
if (parsed.kind === "open") {
lastLink = {
ok: true,
kind: "open",
label: parsed.doc,
detail: parsed.line ? `${parsed.doc} · 第 ${parsed.line} 行` : parsed.doc,
};
addEvent(source, `打开文档:${lastLink.detail}`);
}
else {
lastLink = {
ok: true,
kind: "search",
label: parsed.query,
detail: `搜索:${parsed.query}`,
};
addEvent(source, lastLink.detail);
}
focusWindow();
broadcast();
}
function handleFile(filePath, source) {
if (!validateWorkPath(filePath)) {
lastFile = {
ok: false,
path: filePath,
title: "",
body: "",
size: 0,
error: "BAD_EXTENSION",
};
lastError = "BAD_EXTENSION";
addEvent(source, "拒绝文件:扩展名不是 .xwrt");
broadcast();
return;
}
try {
const stat = fsSync.statSync(filePath);
if (!stat.isFile() || stat.size > 64 * 1024) {
throw new Error("BAD_SIZE");
}
const text = fsSync.readFileSync(filePath, "utf8");
const parsed = parseWorkFile(text);
if (!parsed)
throw new Error("BAD_CONTENT");
lastFile = {
ok: true,
path: filePath,
title: parsed.title,
body: parsed.body,
size: stat.size,
error: "",
};
lastError = "";
addEvent(source, `打开文件:${parsed.title}`);
}
catch (error) {
const code = error instanceof Error && error.message === "BAD_CONTENT"
? "BAD_CONTENT"
: error instanceof Error && error.message === "BAD_SIZE"
? "BAD_SIZE"
: "READ_FAILED";
lastFile = {
ok: false,
path: filePath,
title: "",
body: "",
size: 0,
error: code,
};
lastError = code;
addEvent(source, `文件失败:${code}`);
}
focusWindow();
broadcast();
}
function urlFromArgv(argv) {
return argv.find((arg) => arg.startsWith("xwrt://")) ?? null;
}
function snapshot() {
return {
platform: process.platform,
packaged: app.isPackaged,
protocolRegistered: app.isPackaged && app.isDefaultProtocolClient("xwrt"),
singleInstance: singleInstance,
samplePath,
lastLink,
lastFile,
lastError,
events: [...events],
};
}
function broadcast() {
const state = snapshot();
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed())
window.webContents.send(CH.changed, state);
}
}
function resolvePreload() {
const candidates = [
path.join(__dirname, "preload.cjs"),
path.join(__dirname, "../preload/index.cjs"),
path.join(__dirname, "preload.js"),
];
return (candidates.find((candidate) => fsSync.existsSync(candidate)) ??
candidates[0] ??
"");
}
function createWindow() {
const window = new BrowserWindow({
width: 1100,
height: 860,
show: false,
title: "Deep Link 与文件关联工作台",
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
window.once("ready-to-show", () => window.show());
window.webContents.once("did-finish-load", () => {
if (!window.isDestroyed() && !window.isVisible())
window.show();
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
}
else {
void window.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
win = window;
return window;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(window, code) {
let lastErrorValue = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code));
}
catch (error) {
lastErrorValue = error;
await delay(200);
}
}
throw lastErrorValue instanceof Error
? lastErrorValue
: new Error(String(lastErrorValue));
}
async function waitForRenderer(window) {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed())
return;
try {
const ready = await evalRenderer(window, "typeof window.__smoke === 'function'");
if (ready)
return;
}
catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
async function runSmoke(window) {
try {
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
const result = await evalRenderer(window, "window.__smoke()");
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.validDoc === "flutter/ch01" &&
result.validLine.includes("12") &&
result.searchQuery === "virtual list" &&
result.rejectedReason === "BAD_SCHEME" &&
result.secondSource === "second-instance" &&
result.fileTitle.includes("欢迎") &&
result.fileSize > 0 &&
result.missingError === "READ_FAILED" &&
result.badExtension === "BAD_EXTENSION" &&
result.eventCount > 0 &&
fsSync.existsSync(result.samplePath) &&
singleInstance === true,
...result,
})}\n`);
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`);
app.exit(1);
}
}
async function capture(window, dir, file) {
const image = await window.webContents.capturePage();
if (image.isEmpty())
throw new Error(`empty capture: ${file}`);
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, file), png);
fsSync.writeFileSync(path.join(dir, "raw", file), png);
}
async function runShots(window) {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/32-deep-links-file-association");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("link")`);
await delay(300);
await capture(window, dir, "32-01-deep-link.png");
await evalRenderer(window, `window.__prepareShots("reject")`);
await delay(300);
await capture(window, dir, "32-02-reject.png");
await evalRenderer(window, `window.__prepareShots("file")`);
await delay(300);
await capture(window, dir, "32-03-file.png");
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`);
app.exit(1);
}
}
ipcMain.handle(CH.get, () => snapshot());
ipcMain.handle(CH.simulateUrl, (_event, raw) => {
try {
assertUrlReq(raw);
handleUrl(raw.url, "simulate");
return snapshot();
}
catch {
throw new Error("LINKS_SIMULATE_URL_FAILED");
}
});
ipcMain.handle(CH.simulateFile, (_event, raw) => {
try {
assertFileReq(raw);
handleFile(raw.path, "simulate");
return snapshot();
}
catch {
throw new Error("LINKS_SIMULATE_FILE_FAILED");
}
});
ipcMain.handle(CH.simulateSecond, (_event, raw) => {
try {
assertUrlReq(raw);
addEvent("second-instance", `第二实例参数:${raw.url}`);
handleUrl(raw.url, "second-instance");
return snapshot();
}
catch {
throw new Error("LINKS_SIMULATE_SECOND_FAILED");
}
});
ipcMain.handle(CH.clear, () => {
lastLink = null;
lastFile = null;
lastError = "";
events = [];
addEvent("system", "已清空事件与结果");
broadcast();
return snapshot();
});
app.on("open-url", (event, url) => {
event.preventDefault();
handleUrl(url, "open-url");
});
app.on("open-file", (event, filePath) => {
event.preventDefault();
handleFile(filePath, "open-file");
});
app.on("second-instance", (_event, argv) => {
const url = urlFromArgv(argv);
if (url) {
addEvent("second-instance", "第二实例转发链接");
handleUrl(url, "second-instance");
}
else {
focusWindow();
addEvent("second-instance", "第二实例已转发到当前窗口");
broadcast();
}
});
app.whenReady().then(() => {
samplePath = sampleFile();
if (app.isPackaged) {
app.setAsDefaultProtocolClient("xwrt");
}
else {
addEvent("system", "开发态不注册系统协议,使用模拟入口");
}
const initialUrl = urlFromArgv(process.argv);
if (initialUrl)
handleUrl(initialUrl, "open-url");
const window = createWindow();
broadcast();
if (isSmoke) {
void runSmoke(window);
}
else if (isShots) {
void runShots(window);
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
else {
focusWindow();
}
});
});
app.on("will-quit", () => {
if (tempData) {
try {
fsSync.rmSync(tempData, { recursive: true, force: true });
}
catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (!isSmoke && !isShots && process.platform !== "darwin")
app.quit();
});
//# sourceMappingURL=index.js.map