creditdaddy 1.8.1 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * 开机自启(托盘菜单项)— 移植自 10Router cli/src/cli/tray/autostart.js(AGPL-3.0 同族)。
3
+ * Windows=启动目录 VBS(隐藏窗口直启 node);macOS=LaunchAgent plist;Linux=XDG autostart .desktop。
4
+ * 不依赖 npm bin -g(npm 9 已移除),cli.js 路径按 __dirname 反推。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import { execSync } from 'node:child_process';
10
+
11
+ const APP_NAME = 'creditdaddy';
12
+ const APP_LABEL = 'com.creditdaddy.autostart';
13
+
14
+ /** 解析本包 cli.js 绝对路径:显式参数 → process.argv[1] → __dirname 反推(全局装布局无关) */
15
+ function getCliJsPath(cliPath) {
16
+ if (cliPath) {
17
+ const resolved = path.resolve(cliPath);
18
+ if (fs.existsSync(resolved)) return resolved;
19
+ }
20
+ if (process.argv[1]) {
21
+ const resolved = path.resolve(process.argv[1]);
22
+ if (path.basename(resolved) === 'creditdaddy.js' && fs.existsSync(resolved)) {
23
+ return resolved;
24
+ }
25
+ }
26
+ // autostart.js 在 <pkg>/src/tray/ 下,cli.js 在 <pkg>/bin/ 下
27
+ const computed = path.resolve(__dirname, '..', '..', 'bin', 'creditdaddy.js');
28
+ if (fs.existsSync(computed)) return computed;
29
+ return null;
30
+ }
31
+
32
+ function enableAutoStart(cliPath) {
33
+ const platform = process.platform;
34
+ if (!['darwin', 'win32', 'linux'].includes(platform)) return false;
35
+ if (platform === 'linux' && !process.env.DISPLAY) return false;
36
+ try {
37
+ if (platform === 'darwin') return enableMacOS(cliPath);
38
+ if (platform === 'win32') return enableWindows(cliPath);
39
+ if (platform === 'linux') return enableLinux(cliPath);
40
+ } catch (err) { /* 自启是可选能力,静默失败 */ }
41
+ return false;
42
+ }
43
+
44
+ function disableAutoStart() {
45
+ const platform = process.platform;
46
+ try {
47
+ if (platform === 'darwin') return disableMacOS();
48
+ if (platform === 'win32') return disableWindows();
49
+ if (platform === 'linux') return disableLinux();
50
+ } catch (e) {}
51
+ return false;
52
+ }
53
+
54
+ /** macOS 需 plist 文件 + launchd 注册同时在才如实报告(launchd 处于失败态时不撒谎) */
55
+ function isAutoStartEnabled() {
56
+ const platform = process.platform;
57
+ try {
58
+ if (platform === 'darwin') {
59
+ const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${APP_LABEL}.plist`);
60
+ if (!fs.existsSync(plistPath)) return false;
61
+ try {
62
+ execSync(`launchctl list ${APP_LABEL}`, { stdio: ['ignore', 'ignore', 'ignore'], timeout: 3000 });
63
+ return true;
64
+ } catch (e) {
65
+ return false;
66
+ }
67
+ } else if (platform === 'win32') {
68
+ const startupPath = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `${APP_NAME}.vbs`);
69
+ return fs.existsSync(startupPath);
70
+ } else if (platform === 'linux') {
71
+ const desktopPath = path.join(os.homedir(), '.config', 'autostart', `${APP_NAME}.desktop`);
72
+ return fs.existsSync(desktopPath);
73
+ }
74
+ } catch (e) {}
75
+ return false;
76
+ }
77
+
78
+ /**
79
+ * 当前 Node 进程是否就是 launchd 管理的那个 agent 实例——
80
+ * `launchctl unload` 对 Aqua 域 agent 发 SIGTERM,若托盘点击者自己就是被管理的进程,
81
+ * unload 会杀掉执行点击的进程(图标消失而非菜单翻转)。enable/disable 侧避开。
82
+ */
83
+ function isAgentSelfMacOS() {
84
+ try {
85
+ const output = execSync(`launchctl list ${APP_LABEL}`, {
86
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000,
87
+ });
88
+ const match = output.match(/"PID"\s*=\s*(\d+)/);
89
+ return !!(match && parseInt(match[1], 10) === process.pid);
90
+ } catch (e) {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ function enableMacOS(cliPath) {
96
+ const launchAgentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
97
+ const plistPath = path.join(launchAgentsDir, `${APP_LABEL}.plist`);
98
+ if (!fs.existsSync(launchAgentsDir)) {
99
+ fs.mkdirSync(launchAgentsDir, { recursive: true });
100
+ }
101
+ const nodePath = process.execPath;
102
+ const script = getCliJsPath(cliPath);
103
+ if (!script) return false;
104
+ // node + cli.js 直启(绝对路径、无 shell wrapper)——zsh -l 依赖用户 rc 文件,脆弱
105
+ const launchPath = `${path.dirname(nodePath)}:/usr/local/bin:/usr/bin:/bin`;
106
+ const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
107
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
108
+ <plist version="1.0">
109
+ <dict>
110
+ <key>Label</key>
111
+ <string>${APP_LABEL}</string>
112
+ <key>ProgramArguments</key>
113
+ <array>
114
+ <string>${nodePath}</string>
115
+ <string>${script}</string>
116
+ <string>daemon</string>
117
+ <string>--tray</string>
118
+ </array>
119
+ <key>EnvironmentVariables</key>
120
+ <dict>
121
+ <key>PATH</key>
122
+ <string>${launchPath}</string>
123
+ </dict>
124
+ <key>RunAtLoad</key>
125
+ <true/>
126
+ <key>KeepAlive</key>
127
+ <false/>
128
+ <key>StandardOutPath</key>
129
+ <string>/tmp/creditdaddy.log</string>
130
+ <key>StandardErrorPath</key>
131
+ <string>/tmp/creditdaddy.error.log</string>
132
+ </dict>
133
+ </plist>`;
134
+ fs.writeFileSync(plistPath, plistContent);
135
+ if (isAgentSelfMacOS()) return true; // 不杀自己:plist 已更新,下次登录生效
136
+ try { execSync(`launchctl unload "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
137
+ try { execSync(`launchctl load -w "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
138
+ return true;
139
+ }
140
+
141
+ function disableMacOS() {
142
+ const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${APP_LABEL}.plist`);
143
+ if (!isAgentSelfMacOS()) {
144
+ try { execSync(`launchctl unload "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
145
+ }
146
+ if (fs.existsSync(plistPath)) fs.unlinkSync(plistPath);
147
+ return true;
148
+ }
149
+
150
+ function enableWindows(cliPath) {
151
+ const startupDir = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
152
+ const vbsPath = path.join(startupDir, `${APP_NAME}.vbs`);
153
+ if (!fs.existsSync(startupDir)) return false;
154
+ const nodePath = process.execPath;
155
+ const script = getCliJsPath(cliPath);
156
+ if (!script) return false;
157
+ // node + cli.js 直启、隐藏窗口(不绕 .cmd 查找——npm prefix 路径不可靠)
158
+ const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
159
+ WshShell.Run """${nodePath}"" ""${script}"" daemon --tray", 0, False
160
+ `;
161
+ fs.writeFileSync(vbsPath, vbsContent);
162
+ return true;
163
+ }
164
+
165
+ function disableWindows() {
166
+ const vbsPath = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `${APP_NAME}.vbs`);
167
+ if (fs.existsSync(vbsPath)) fs.unlinkSync(vbsPath);
168
+ return true;
169
+ }
170
+
171
+ function enableLinux(cliPath) {
172
+ const autostartDir = path.join(os.homedir(), '.config', 'autostart');
173
+ const desktopPath = path.join(autostartDir, `${APP_NAME}.desktop`);
174
+ if (!fs.existsSync(autostartDir)) {
175
+ try { fs.mkdirSync(autostartDir, { recursive: true }); } catch (e) { return false; }
176
+ }
177
+ const nodePath = process.execPath;
178
+ const script = getCliJsPath(cliPath);
179
+ if (!script) return false;
180
+ const desktopContent = `[Desktop Entry]
181
+ Type=Application
182
+ Name=CreditDaddy
183
+ Comment=CreditDaddy daemon
184
+ Exec=${nodePath} ${script} daemon --tray
185
+ Hidden=false
186
+ NoDisplay=false
187
+ X-GNOME-Autostart-enabled=true
188
+ `;
189
+ fs.writeFileSync(desktopPath, desktopContent);
190
+ return true;
191
+ }
192
+
193
+ function disableLinux() {
194
+ const desktopPath = path.join(os.homedir(), '.config', 'autostart', `${APP_NAME}.desktop`);
195
+ if (fs.existsSync(desktopPath)) fs.unlinkSync(desktopPath);
196
+ return true;
197
+ }
198
+
199
+ export { enableAutoStart, disableAutoStart, isAutoStartEnabled };
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,249 @@
1
+ /**
2
+ * CLI 托盘 — 移植自 10Router cli/src/cli/tray/tray.js(AGPL-3.0 同族,双向移植免许可记账)。
3
+ *
4
+ * Windows:PowerShell NotifyIcon(零二进制、杀软友好);macOS/Linux:懒装 systray2
5
+ * (装进用户数据目录 runtime/node_modules,npm 包本体不携带签名二进制——杀软误报防线,
6
+ * 见 trayRuntime.js)。菜单:打开面板 / 立即领取 / 开机自启开关 / 退出。
7
+ *
8
+ * CD 适配差异(对照 10R 原版):
9
+ * - 「立即领取」替代 10R 无此项:托盘直达 checkin-all(CD 的核心动作)
10
+ * - i18n 走 src/i18n.js 的 t()(面板四语词典同一出处),不单独建 tray.json
11
+ * - 面板地址 = daemon 实际绑定端口(daemon 起来后回填,端口冲突自动 +1 的口径一致)
12
+ */
13
+ import { exec } from 'node:child_process';
14
+ import { createRequire } from 'node:module';
15
+ const nodeRequire = createRequire(import.meta.url);
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+
19
+ let trayInstance = null;
20
+ let isWinTray = false;
21
+
22
+ /** 托盘图标:单色模板图(macOS 菜单栏随明暗着色)→ 品牌 PNG 回落 */
23
+ function getIconBase64() {
24
+ const platform = process.platform;
25
+ const iconFile = platform === 'darwin' ? 'icon-template.png' : 'icon-brand.png';
26
+ try {
27
+ const iconPath = path.join(__dirname, iconFile);
28
+ if (fs.existsSync(iconPath)) {
29
+ return fs.readFileSync(iconPath).toString('base64');
30
+ }
31
+ } catch (e) {}
32
+ // 回落:1×1 透明 PNG(systray 无图不注册)
33
+ return 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAHpJREFUOE9jYBgFgwEwMjIy/Gdg+P8fyP4PxP8ZGBgEcBnGyMjIsICBgSEAhyH/gfgBUNN8XJoZsdkCVL8Ah+b/QPwbqvkBMvk/AwMDAzYX/GdgYAhAN+A/SICRWAMYGfFEJSMjzriEiwDR/xmIa2RkZCSqnZERb3QCAAo3KxzxbKe1AAAAAElFTkSuQmCC';
34
+ }
35
+
36
+ function isTraySupported() {
37
+ const platform = process.platform;
38
+ if (!['darwin', 'win32', 'linux'].includes(platform)) return false;
39
+ if (platform === 'linux' && !process.env.DISPLAY) return false;
40
+ return true;
41
+ }
42
+
43
+ /**
44
+ * 初始化托盘。options: { port, onQuit, onOpenPanel, onClaimAll }
45
+ * daemon 未就绪时仍可先挂图标(端口回填靠 setTooltip/updateItem)。
46
+ */
47
+ function initTray(options) {
48
+ if (!isTraySupported()) return null;
49
+ if (process.platform === 'win32') return initWindowsTray(options);
50
+ return initUnixTray(options);
51
+ }
52
+
53
+ async function buildMenuItems(port, autostartEnabled) {
54
+ // i18n 延迟取——词典可能随面板切换语言,菜单项构建时取当前值
55
+ const { t } = await import('../i18n.js');
56
+ return [
57
+ { title: t('托盘:CreditDaddy(端口 {port})', { port: port || '…' }), tooltip: t('服务运行中'), enabled: false },
58
+ { title: t('打开面板'), tooltip: t('在浏览器中打开'), enabled: true },
59
+ { title: t('立即领取全部'), tooltip: t('对所有账号跑一轮签到与活动领取'), enabled: true },
60
+ { title: autostartEnabled ? t('✓ 已开启开机自启') : t('开启开机自启'), tooltip: t('系统启动时自动运行'), enabled: true },
61
+ { title: t('退出'), tooltip: t('停止守护进程并退出'), enabled: true },
62
+ ];
63
+ }
64
+
65
+ const MENU_INDEX = { STATUS: 0, PANEL: 1, CLAIM: 2, AUTOSTART: 3, QUIT: 4 };
66
+
67
+ async function getAutostartEnabled() {
68
+ try {
69
+ const { isAutoStartEnabled } = await import('./autostart.js');
70
+ return isAutoStartEnabled();
71
+ } catch (e) {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ async function handleClick(index, options, onAutostartToggle) {
77
+ const { onQuit, onOpenPanel, onClaimAll, port } = options;
78
+ const { t } = await import('../i18n.js');
79
+ if (index === MENU_INDEX.PANEL) {
80
+ if (onOpenPanel) onOpenPanel();
81
+ else openBrowser(`http://127.0.0.1:${port || 47860}`);
82
+ } else if (index === MENU_INDEX.CLAIM) {
83
+ if (onClaimAll) onClaimAll();
84
+ } else if (index === MENU_INDEX.AUTOSTART) {
85
+ const enabled = getAutostartEnabled();
86
+ try {
87
+ const { enableAutoStart, disableAutoStart } = await import('./autostart.js');
88
+ if (enabled) disableAutoStart();
89
+ else enableAutoStart();
90
+ onAutostartToggle(!enabled);
91
+ } catch (e) {}
92
+ } else if (index === MENU_INDEX.QUIT) {
93
+ console.log(t('\n正在停止 CreditDaddy…'));
94
+ if (onQuit) onQuit();
95
+ killTray();
96
+ setTimeout(() => process.exit(0), 500);
97
+ }
98
+ }
99
+
100
+ async function initWindowsTray(options) {
101
+ try {
102
+ const { initWinTray, winTrayIconPath } = await import('./trayWin.js');
103
+ const { t } = await import('../i18n.js');
104
+ const iconPath = winTrayIconPath();
105
+ const autostartEnabled = await getAutostartEnabled();
106
+ const items = await buildMenuItems(options.port, autostartEnabled);
107
+ trayInstance = initWinTray({
108
+ iconPath,
109
+ tooltip: t('CreditDaddy - 端口 {port}', { port: options.port || '…' }),
110
+ items,
111
+ onClick: (index) => {
112
+ handleClick(index, options, async (newEnabled) => {
113
+ const { t: tt } = await import('../i18n.js');
114
+ trayInstance.updateItem(MENU_INDEX.AUTOSTART, newEnabled ? tt('✓ 已开启开机自启') : tt('开启开机自启'), true);
115
+ });
116
+ },
117
+ });
118
+ isWinTray = true;
119
+ return trayInstance;
120
+ } catch (err) {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ /** macOS/Linux:懒装 systray2(trayRuntime 负责),装不上时托盘静默降级(无图标但 daemon 照常) */
126
+ async function resolveSystray() {
127
+ let runtimeDir = null;
128
+ try {
129
+ const { getRuntimeNodeModules } = await import('./trayRuntime.js');
130
+ runtimeDir = getRuntimeNodeModules();
131
+ } catch (e) {}
132
+ const candidates = [];
133
+ if (runtimeDir) {
134
+ candidates.push(path.join(runtimeDir, 'systray2'), path.join(runtimeDir, 'systray'));
135
+ }
136
+ candidates.push('systray2', 'systray');
137
+ for (const spec of candidates) {
138
+ try {
139
+ const mod = nodeRequire(spec);
140
+ if (mod && (mod.default || mod)) return { mod: mod.default || mod, isV2: String(spec).endsWith('systray2') };
141
+ } catch (e) {}
142
+ }
143
+ return null;
144
+ }
145
+
146
+ async function chmodTrayBin(pkgName) {
147
+ // systray2 的 Go 二进制偶发落盘没带 +x(macOS 实测),spawn 时 EACCES 静默失败难排查
148
+ try {
149
+ const { getRuntimeNodeModules } = await import('./trayRuntime.js');
150
+ const binName = process.platform === 'darwin' ? 'tray_darwin_release' : 'tray_linux_release';
151
+ const candidates = [
152
+ path.join(getRuntimeNodeModules(), pkgName, 'traybin', binName),
153
+ ];
154
+ for (const p of candidates) {
155
+ if (fs.existsSync(p)) fs.chmodSync(p, 0o755);
156
+ }
157
+ } catch (e) {}
158
+ }
159
+
160
+ async function initUnixTray(options) {
161
+ try {
162
+ const resolved = await resolveSystray();
163
+ if (!resolved) return null;
164
+ const { mod: SysTray, isV2 } = resolved;
165
+ const { t } = await import('../i18n.js');
166
+ await chmodTrayBin(isV2 ? 'systray2' : 'systray');
167
+
168
+ const autostartEnabled = await getAutostartEnabled();
169
+ const items = await buildMenuItems(options.port, autostartEnabled);
170
+ const menu = {
171
+ icon: getIconBase64(),
172
+ // macOS:模板模式——icon-template.png 的 alpha 通道即图形,菜单栏随明暗着色;
173
+ // 彩色品牌图的 alpha 是实心方块不能做模板。Linux 面板无模板惯例 → 用彩色图。
174
+ isTemplateIcon: process.platform === 'darwin',
175
+ title: '',
176
+ tooltip: t('CreditDaddy - 端口 {port}', { port: options.port || '…' }),
177
+ items,
178
+ };
179
+ trayInstance = new SysTray({ menu, debug: false, copyDir: true });
180
+ isWinTray = false;
181
+ trayInstance.onClick((action) => {
182
+ handleClick(action.seq_id, options, (newEnabled) => {
183
+ trayInstance.sendAction({
184
+ type: 'update-item',
185
+ item: { title: newEnabled ? t('✓ 已开启开机自启') : t('开启开机自启'), tooltip: t('系统启动时自动运行'), enabled: true },
186
+ seq_id: MENU_INDEX.AUTOSTART,
187
+ });
188
+ });
189
+ });
190
+ if (isV2 && typeof trayInstance.ready === 'function') {
191
+ trayInstance.ready().catch(() => {});
192
+ }
193
+ return trayInstance;
194
+ } catch (err) {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /** 停托盘,等子进程完全退出(macOS 不释放 NSStatusItem 会留幽灵图标、重挂注册不上) */
200
+ function killTray() {
201
+ const instance = trayInstance;
202
+ const wasWin = isWinTray;
203
+ trayInstance = null;
204
+ if (!instance) return Promise.resolve();
205
+
206
+ if (wasWin) {
207
+ try { instance.kill(); } catch (e) {}
208
+ return Promise.resolve();
209
+ }
210
+
211
+ let proc = null;
212
+ try {
213
+ proc = instance._process || (typeof instance.process === 'function' ? instance.process() : null);
214
+ } catch (e) {}
215
+
216
+ const gracefulQuit = () => { try { instance.kill(true); } catch (e) {} };
217
+ const closeIpc = () => { try { instance.kill(false); } catch (e) {} };
218
+
219
+ if (!proc || !proc.pid) {
220
+ gracefulQuit();
221
+ closeIpc();
222
+ return Promise.resolve();
223
+ }
224
+
225
+ return new Promise((resolve) => {
226
+ let done = false;
227
+ const finish = () => { if (done) return; done = true; closeIpc(); resolve(); };
228
+ proc.once('exit', finish);
229
+ gracefulQuit();
230
+ setTimeout(() => { try { process.kill(proc.pid, 0); proc.kill('SIGTERM'); } catch (e) {} }, 800);
231
+ setTimeout(() => { try { process.kill(proc.pid, 0); proc.kill('SIGKILL'); } catch (e) {} }, 1600);
232
+ const deadline = Date.now() + 3000;
233
+ const poll = setInterval(() => {
234
+ try { process.kill(proc.pid, 0); } catch { clearInterval(poll); finish(); return; }
235
+ if (Date.now() > deadline) { clearInterval(poll); finish(); }
236
+ }, 50);
237
+ });
238
+ }
239
+
240
+ function openBrowser(url) {
241
+ const platform = process.platform;
242
+ let cmd;
243
+ if (platform === 'darwin') cmd = `open "${url}"`;
244
+ else if (platform === 'win32') cmd = `start "" "${url}"`;
245
+ else cmd = `xdg-open "${url}"`;
246
+ exec(cmd);
247
+ }
248
+
249
+ export { initTray, killTray, isTraySupported, MENU_INDEX };
@@ -0,0 +1,130 @@
1
+ # 10Router tray icon for Windows using NotifyIcon
2
+ # IPC: stdin JSON commands, stdout JSON events
3
+ param([string]$IconPath, [string]$Tooltip)
4
+
5
+ $ErrorActionPreference = "Stop"
6
+
7
+ Add-Type @"
8
+ using System;
9
+ using System.Runtime.InteropServices;
10
+
11
+ public static class WinDpiAwareness {
12
+ public static IntPtr PerMonitorAwareV2 { get { return new IntPtr(-4); } }
13
+ public static IntPtr PerMonitorAware { get { return new IntPtr(-3); } }
14
+
15
+ [DllImport("user32.dll")]
16
+ public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
17
+
18
+ [DllImport("user32.dll")]
19
+ public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr value);
20
+
21
+ [DllImport("shcore.dll")]
22
+ public static extern int SetProcessDpiAwareness(int value);
23
+
24
+ [DllImport("user32.dll")]
25
+ public static extern bool SetProcessDPIAware();
26
+ }
27
+ "@
28
+
29
+ function Enable-HighDpiAwareness {
30
+ $contexts = @(
31
+ [WinDpiAwareness]::PerMonitorAwareV2,
32
+ [WinDpiAwareness]::PerMonitorAware
33
+ )
34
+
35
+ foreach ($context in $contexts) {
36
+ try {
37
+ if ([WinDpiAwareness]::SetProcessDpiAwarenessContext($context)) { break }
38
+ } catch {}
39
+ }
40
+
41
+ try { [WinDpiAwareness]::SetProcessDpiAwareness(2) | Out-Null } catch {}
42
+ try { [WinDpiAwareness]::SetProcessDPIAware() | Out-Null } catch {}
43
+
44
+ foreach ($context in $contexts) {
45
+ try {
46
+ $previous = [WinDpiAwareness]::SetThreadDpiAwarenessContext($context)
47
+ if ($previous -ne [IntPtr]::Zero) { break }
48
+ } catch {}
49
+ }
50
+ }
51
+
52
+ Enable-HighDpiAwareness
53
+
54
+ Add-Type -AssemblyName System.Windows.Forms
55
+ Add-Type -AssemblyName System.Drawing
56
+
57
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
58
+ [Console]::InputEncoding = [System.Text.Encoding]::UTF8
59
+ $OutputEncoding = [System.Text.Encoding]::UTF8
60
+
61
+ [System.Windows.Forms.Application]::EnableVisualStyles()
62
+ [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false)
63
+
64
+ $script:notifyIcon = New-Object System.Windows.Forms.NotifyIcon
65
+ $script:notifyIcon.Icon = New-Object System.Drawing.Icon($IconPath)
66
+ $script:notifyIcon.Text = $Tooltip
67
+ $script:notifyIcon.Visible = $true
68
+
69
+ $script:menu = New-Object System.Windows.Forms.ContextMenuStrip
70
+ $script:notifyIcon.ContextMenuStrip = $script:menu
71
+ $script:items = @()
72
+
73
+ function Write-Event($obj) {
74
+ $json = $obj | ConvertTo-Json -Compress
75
+ [Console]::Out.WriteLine($json)
76
+ [Console]::Out.Flush()
77
+ }
78
+
79
+ function Add-MenuItem($index, $title, $enabled) {
80
+ $item = New-Object System.Windows.Forms.ToolStripMenuItem
81
+ $item.Text = $title
82
+ $item.Enabled = $enabled
83
+ $idx = $index
84
+ $item.Add_Click({ Write-Event @{ type = "click"; index = $idx } }.GetNewClosure())
85
+ $script:menu.Items.Add($item) | Out-Null
86
+ $script:items += $item
87
+ }
88
+
89
+ function Update-MenuItem($index, $title, $enabled) {
90
+ if ($index -lt $script:items.Count) {
91
+ $script:items[$index].Text = $title
92
+ $script:items[$index].Enabled = $enabled
93
+ }
94
+ }
95
+
96
+ function Set-Tooltip($text) {
97
+ # NotifyIcon.Text max 63 chars
98
+ if ($text.Length -gt 63) { $text = $text.Substring(0, 63) }
99
+ $script:notifyIcon.Text = $text
100
+ }
101
+
102
+ # Background reader thread polls stdin via timer on UI thread
103
+ $script:timer = New-Object System.Windows.Forms.Timer
104
+ $script:timer.Interval = 100
105
+ $script:timer.Add_Tick({
106
+ try {
107
+ while ([Console]::In.Peek() -ne -1) {
108
+ $line = [Console]::In.ReadLine()
109
+ if ([string]::IsNullOrWhiteSpace($line)) { continue }
110
+ $cmd = $line | ConvertFrom-Json
111
+ switch ($cmd.action) {
112
+ "add-item" { Add-MenuItem $cmd.index $cmd.title $cmd.enabled }
113
+ "update-item" { Update-MenuItem $cmd.index $cmd.title $cmd.enabled }
114
+ "set-tooltip" { Set-Tooltip $cmd.text }
115
+ "ready" { Write-Event @{ type = "ready" } }
116
+ "kill" {
117
+ $script:notifyIcon.Visible = $false
118
+ $script:notifyIcon.Dispose()
119
+ [System.Windows.Forms.Application]::Exit()
120
+ }
121
+ }
122
+ }
123
+ } catch {
124
+ Write-Event @{ type = "error"; message = $_.Exception.Message }
125
+ }
126
+ })
127
+ $script:timer.Start()
128
+
129
+ Write-Event @{ type = "started" }
130
+ [System.Windows.Forms.Application]::Run()
@@ -0,0 +1,90 @@
1
+ /**
2
+ * systray2 运行时懒装 — 移植自 10Router cli/hooks/trayRuntime.js(AGPL-3.0 同族)。
3
+ *
4
+ * npm 发布包不携带签名 Go 二进制(杀软误报防线):macOS/Linux 的托盘二进制
5
+ * 首次使用时按需 npm install 进用户数据目录 runtime/node_modules。Windows 不需要
6
+ * (PowerShell 方案零二进制)。
7
+ */
8
+ import { spawnSync } from 'node:child_process';
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ const SYSTRAY_PKG = 'systray2';
13
+ const SYSTRAY_VERSION = '2.1.4';
14
+ const LEGACY_SYSTRAY_PKG = 'systray';
15
+
16
+ function getRuntimeDir() {
17
+ // <数据目录>/runtime —— 与账号库同盘同权限纪律;store.js 的 dataDir 惰性求值
18
+ try {
19
+ const { dataDir } = require('../store.js');
20
+ return path.join(dataDir(), 'runtime');
21
+ } catch (e) {
22
+ // store 不可用(极端)退回 os.homedir()
23
+ return path.join(require('node:os').homedir(), '.creditdaddy', 'runtime');
24
+ }
25
+ }
26
+
27
+ function getRuntimeNodeModules() {
28
+ return path.join(getRuntimeDir(), 'node_modules');
29
+ }
30
+
31
+ function hasSystray() {
32
+ return fs.existsSync(path.join(getRuntimeNodeModules(), SYSTRAY_PKG, 'package.json'));
33
+ }
34
+
35
+ /** 清理旧版 systray@1.0.5(其 Go 二进制 Mach-O 头被 macOS 14+ dyld 拒绝,托盘静默失败) */
36
+ function cleanupLegacySystray({ silent = false } = {}) {
37
+ const targets = [
38
+ path.join(getRuntimeNodeModules(), LEGACY_SYSTRAY_PKG),
39
+ ];
40
+ for (const dir of targets) {
41
+ if (fs.existsSync(dir)) {
42
+ try {
43
+ fs.rmSync(dir, { recursive: true, force: true });
44
+ if (!silent) console.log(`[tray] removed legacy systray: ${dir}`);
45
+ } catch (e) {
46
+ if (!silent) console.warn(`[tray] failed to remove ${dir}: ${e.message}`);
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ /** spawnSync npm install;npm 不可用 / 网络不通时返回 null(托盘降级无图标,daemon 照常) */
53
+ function runNpmInstall({ silent = false } = {}) {
54
+ const runtimeDir = getRuntimeDir();
55
+ try {
56
+ fs.mkdirSync(runtimeDir, { recursive: true });
57
+ } catch (e) {
58
+ return null;
59
+ }
60
+ const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
61
+ const res = spawnSync(npmCmd, ['install', '--no-audit', '--no-fund', '--omit-dev', `${SYSTRAY_PKG}@${SYSTRAY_VERSION}`], {
62
+ cwd: runtimeDir,
63
+ encoding: 'utf8',
64
+ timeout: 120_000,
65
+ windowsHide: true,
66
+ });
67
+ if (res.status !== 0) {
68
+ if (!silent) console.warn(`[tray] systray2 install failed: ${res.stderr || res.error || 'exit ' + res.status}`);
69
+ return null;
70
+ }
71
+ return path.join(getRuntimeNodeModules(), SYSTRAY_PKG);
72
+ }
73
+
74
+ /**
75
+ * 确保托盘运行时就绪(CLI 启动时调用)。失败不抛——托盘是增强能力,不是 daemon 的依赖。
76
+ * @returns {{installed: boolean, cleaned: boolean}}
77
+ */
78
+ function ensureTrayRuntime({ silent = false } = {}) {
79
+ if (process.platform === 'win32') return { installed: false, cleaned: false }; // Windows 用 PowerShell 方案
80
+ let cleaned = false;
81
+ try {
82
+ cleanupLegacySystray({ silent });
83
+ cleaned = true;
84
+ } catch (e) {}
85
+ if (hasSystray()) return { installed: true, cleaned };
86
+ const installed = Boolean(runNpmInstall({ silent }));
87
+ return { installed, cleaned };
88
+ }
89
+
90
+ export { ensureTrayRuntime, getRuntimeDir, getRuntimeNodeModules, hasSystray, cleanupLegacySystray };