@pmate/cli 0.43.0 → 0.44.1

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.
package/README.md CHANGED
@@ -401,8 +401,8 @@ Roles group explicit actions and resource scopes. Platform roles use a bare name
401
401
 
402
402
  ```bash
403
403
  pmate role definition list --json
404
- pmate role definition create pmate/reviewer --display-name Reviewer --description "Review PMate apps"
405
- pmate role permission create app:review --scope-type namespace --display-name "Review app" --description "Approve an app review"
404
+ pmate role definition create pmate/reviewer --level maintainer --display-name Reviewer --description "Review PMate apps"
405
+ pmate role permission create app:review --scope-type namespace --risk M --display-name "Review app" --description "Approve an app review"
406
406
  pmate role grant add --role pmate/reviewer --permission app:review --namespace pmate
407
407
  pmate role binding add --role pmate/reviewer --account <account-id>
408
408
  pmate role check --permission app:review --namespace pmate --json
@@ -416,3 +416,5 @@ pmate role definition update pmate/reviewer --status disabled
416
416
  For platform actions use `--scope platform`. Platform roles can grant namespace actions with `--namespace '*'`, including future namespaces; permission checks require a concrete namespace. Definitions and grants are independent, and disabled definitions grant no access. Platform authorization administrators can explicitly delegate new actions; namespace administrators remain bounded by their own namespace and permissions. All commands support `--base-url` and `--json`.
417
417
 
418
418
  Root-only migration: `pmate role migration preview --json`, then `pmate role migration apply --json`. It preserves old records, migrates bindings to canonical role IDs, and records completion so revoked grants are not restored by rerunning migration.
419
+
420
+ Permission risk: H requires an admin-level role, M requires maintainer or admin, L allows dev or higher. The same role must carry the explicit scoped grant. New roles default to dev and new permissions default to H. Use `role definition update <role> --level ...` and `role permission update <permission> --risk ...`; omitted values are preserved. Root may preview/apply the one-time risk migration using `role migration preview|apply --risk-model --json`.
package/dist/index.d.ts CHANGED
@@ -335,6 +335,9 @@ type OssCommandArgs = {
335
335
  objectKey: string;
336
336
  };
337
337
  type RoleCommandArgs = {
338
+ risk?: "H" | "M" | "L";
339
+ level?: "admin" | "maintainer" | "dev";
340
+ riskModel?: boolean;
338
341
  type: Command.Role;
339
342
  resource: "definition" | "permission" | "grant" | "binding" | "migration" | "check";
340
343
  action: "list" | "create" | "update" | "add" | "remove" | "preview" | "apply" | "check";
package/dist/index.js CHANGED
@@ -18275,6 +18275,7 @@ var import_node_child_process9 = require("child_process");
18275
18275
  var import_node_fs21 = require("fs");
18276
18276
  var import_node_os10 = require("os");
18277
18277
  var import_node_path26 = __toESM(require("path"));
18278
+ var import_sharp2 = __toESM(require("sharp"));
18278
18279
 
18279
18280
  // src/desktopRelease.ts
18280
18281
  init_sessionStore();
@@ -18335,6 +18336,11 @@ function readDesktopConfig(file, appId) {
18335
18336
  if (c.externalOrigins !== void 0 && !Array.isArray(c.externalOrigins)) throw new Error("externalOrigins must be an array");
18336
18337
  c.externalOrigins?.forEach(origin);
18337
18338
  if (c.notaryProfile !== void 0 && (typeof c.notaryProfile !== "string" || !c.notaryProfile.trim())) throw new Error("Invalid notaryProfile");
18339
+ if (c.tray !== void 0) {
18340
+ if (!c.tray || typeof c.tray !== "object" || typeof c.tray.icon !== "string" || !c.tray.icon.trim()) throw new Error("Invalid desktop tray icon");
18341
+ if (c.tray.platforms !== void 0 && (!Array.isArray(c.tray.platforms) || !c.tray.platforms.length || c.tray.platforms.some((value) => !["mac", "win"].includes(value)))) throw new Error("Invalid desktop tray platforms");
18342
+ if (c.tray.closeToTray !== void 0 && typeof c.tray.closeToTray !== "boolean") throw new Error("Invalid desktop closeToTray");
18343
+ }
18338
18344
  if ("web" in c) throw new Error("Remote desktop builds do not accept web build configuration; remove web");
18339
18345
  return c;
18340
18346
  }
@@ -18407,16 +18413,26 @@ async function runBuildCommand(command, cwd, env = process.env) {
18407
18413
  child.once("exit", (code, signal) => code === 0 ? resolve() : reject(new Error(`${command[0]} failed (${signal ?? code})`)));
18408
18414
  });
18409
18415
  }
18416
+ async function renderTrayIcons(source, output) {
18417
+ const idle = await (0, import_sharp2.default)(source).resize(36, 36, { fit: "contain" }).png().toBuffer();
18418
+ const gap = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="7" fill="#000"/></svg>');
18419
+ const dot = Buffer.from('<svg width="36" height="36" xmlns="http://www.w3.org/2000/svg"><circle cx="30" cy="6" r="5" fill="#000"/></svg>');
18420
+ await (0, import_sharp2.default)(idle).toFile(import_node_path26.default.join(output, "trayTemplate.png"));
18421
+ await (0, import_sharp2.default)(idle).composite([{ input: gap, blend: "dest-out" }, { input: dot }]).png().toFile(import_node_path26.default.join(output, "trayUnreadTemplate.png"));
18422
+ }
18410
18423
  async function buildDesktop(args) {
18411
18424
  const { file, output } = resolveDesktopPaths(args);
18412
18425
  const c = readDesktopConfig(file, args.id);
18413
18426
  const base = import_node_path26.default.dirname(file);
18414
18427
  const icon = import_node_path26.default.resolve(base, c.icon);
18428
+ const tray = c.tray && (!c.tray.platforms || c.tray.platforms.includes(args.platform)) ? c.tray : void 0;
18429
+ const trayIcon = tray ? import_node_path26.default.resolve(base, tray.icon) : void 0;
18415
18430
  const env = desktopBuildEnvironment(c);
18416
18431
  if (!(0, import_node_fs21.existsSync)(icon) || !(0, import_node_fs21.statSync)(icon).isFile()) throw new Error(`Desktop icon not found: ${icon}`);
18432
+ if (trayIcon && (!(0, import_node_fs21.existsSync)(trayIcon) || !(0, import_node_fs21.statSync)(trayIcon).isFile())) throw new Error(`Desktop tray icon not found: ${trayIcon}`);
18417
18433
  if (!["mac", "win"].includes(args.platform) || !["arm64", "x64"].includes(args.arch)) throw new Error("Supported target: mac|win --arch arm64|x64");
18418
18434
  if (args.platform === "mac" && process.platform !== "darwin") throw new Error("macOS desktop packaging requires a macOS build host");
18419
- const plan = { config: file, notaryProfile: env.APPLE_KEYCHAIN_PROFILE, app: c.app, productName: c.productName, version: c.version, target: "electron", platform: args.platform, arch: args.arch, contentSource: "remote", origin: c.origin, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
18435
+ const plan = { config: file, notaryProfile: env.APPLE_KEYCHAIN_PROFILE, app: c.app, productName: c.productName, version: c.version, target: "electron", platform: args.platform, arch: args.arch, contentSource: "remote", origin: c.origin, tray: !!tray, output, electron: ELECTRON_VERSION, builder: BUILDER_VERSION, signed: args.signed };
18420
18436
  console.log(JSON.stringify({ phase: "plan", ...plan }, null, 2));
18421
18437
  if (args.dryRun) return;
18422
18438
  if (args.signed && args.platform === "mac") {
@@ -18429,7 +18445,8 @@ async function buildDesktop(args) {
18429
18445
  (0, import_node_fs21.mkdirSync)(appDir);
18430
18446
  const templateDir = import_node_path26.default.join(__dirname, "templates", "electron");
18431
18447
  (0, import_node_fs21.cpSync)(templateDir, appDir, { recursive: true });
18432
- (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId }));
18448
+ if (trayIcon) await renderTrayIcons(trayIcon, appDir);
18449
+ (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "desktop-config.json"), JSON.stringify({ app: c.app, productName: c.productName, origin: c.origin, authOrigins: c.authOrigins, externalOrigins: c.externalOrigins ?? [], bundleId: c.bundleId, ...tray ? { tray: { closeToTray: tray.closeToTray !== false } } : {} }));
18433
18450
  (0, import_node_fs21.writeFileSync)(import_node_path26.default.join(appDir, "package.json"), JSON.stringify({ name: c.bundleId.replace(/\./g, "-"), version: c.version, description: `${c.productName} desktop application`, author: "PMate", main: "main.cjs", dependencies: { "@pmate/chat-sdk": "0.11.7", "electron-updater": "6.8.3" } }));
18434
18451
  await runBuildCommand(["npm", "install", "--omit=dev", "--no-audit", "--no-fund"], appDir);
18435
18452
  const cache = import_node_path26.default.join((0, import_node_os10.homedir)(), ".cache", "pmate", "electron", `${ELECTRON_VERSION}-${BUILDER_VERSION}`);
@@ -22677,7 +22694,7 @@ var RoleCommandHandler = class {
22677
22694
  };
22678
22695
  const scope = args.scope === "platform" ? { type: "platform" } : { type: "namespace", namespace: args.namespace };
22679
22696
  let result;
22680
- if (args.resource === "migration") result = await request2("POST", "/authorization/migrate", { dryRun: args.action !== "apply" });
22697
+ if (args.resource === "migration") result = await request2("POST", args.riskModel ? "/authorization/migrate-risk" : "/authorization/migrate", { dryRun: args.action !== "apply" });
22681
22698
  else if (args.resource === "check") result = await request2("POST", "/authz/permission", { permission: args.permission, scope, ...args.account ? { account: args.account } : {} });
22682
22699
  else if (args.action === "list") {
22683
22700
  const data = await request2("GET", "/authorization");
@@ -22691,7 +22708,7 @@ var RoleCommandHandler = class {
22691
22708
  existing = inventory[args.resource === "definition" ? "definitions" : "permissions"].find((row) => row.id === id);
22692
22709
  if (!existing) throw new Error(`Not found: ${id}`);
22693
22710
  }
22694
- const body = { ...args.resource === "definition" ? { roleId: id } : { id, scopeType: args.scopeType ?? existing?.scopeType }, displayName: args.displayName ?? existing?.displayName ?? id, description: args.description ?? existing?.description ?? id, status: args.status ?? existing?.status ?? "active" };
22711
+ const body = { ...args.resource === "definition" ? { roleId: id, level: args.level ?? existing?.level ?? "dev" } : { id, risk: args.risk ?? existing?.risk ?? "H", scopeType: args.scopeType ?? existing?.scopeType }, displayName: args.displayName ?? existing?.displayName ?? id, description: args.description ?? existing?.description ?? id, status: args.status ?? existing?.status ?? "active" };
22695
22712
  result = await request2(args.action === "update" ? "PUT" : "POST", `/authorization/${args.resource === "definition" ? "roles" : "permissions"}`, body);
22696
22713
  } else if (args.resource === "binding") result = await request2(args.action === "remove" ? "DELETE" : "POST", "/authorization/bindings", { account: args.account, roleId: args.role });
22697
22714
  else result = await request2(args.action === "remove" ? "DELETE" : "POST", "/authorization/role-permissions", { roleId: args.role, permission: args.permission, scope });
@@ -25623,9 +25640,14 @@ function parseRoleArgs(tokens) {
25623
25640
  args.description = void 0;
25624
25641
  } else args.permission = id;
25625
25642
  }
25626
- const options = { "--role": "role", "--permission": "permission", "--account": "account", "--namespace": "namespace", "--scope": "scope", "--scope-type": "scopeType", "--status": "status", "--display-name": "displayName", "--description": "description", "--base-url": "baseUrl" };
25643
+ const options = { "--risk": "risk", "--level": "level", "--role": "role", "--permission": "permission", "--account": "account", "--namespace": "namespace", "--scope": "scope", "--scope-type": "scopeType", "--status": "status", "--display-name": "displayName", "--description": "description", "--base-url": "baseUrl" };
25627
25644
  while (rest.length) {
25628
25645
  const flag = rest.shift();
25646
+ if (flag === "--risk-model") {
25647
+ if (resource !== "migration") throw new Error("--risk-model requires role migration");
25648
+ args.riskModel = true;
25649
+ continue;
25650
+ }
25629
25651
  if (flag === "--json") {
25630
25652
  args.json = true;
25631
25653
  continue;
@@ -25636,6 +25658,8 @@ function parseRoleArgs(tokens) {
25636
25658
  if (args[key] !== void 0) throw new Error(`Duplicate role option: ${flag}`);
25637
25659
  Object.assign(args, { [key]: value });
25638
25660
  }
25661
+ if (args.risk && (!["H", "M", "L"].includes(args.risk) || resource !== "permission" || !["create", "update"].includes(action))) throw new Error("--risk H|M|L requires permission create/update");
25662
+ if (args.level && (!["admin", "maintainer", "dev"].includes(args.level) || resource !== "definition" || !["create", "update"].includes(action))) throw new Error("--level admin|maintainer|dev requires definition create/update");
25639
25663
  if (args.role && !rolePattern.test(args.role)) throw new Error("Invalid role reference: use admin or blue/admin");
25640
25664
  if (args.permission && !permissionPattern.test(args.permission)) throw new Error("Invalid permission: use app:create");
25641
25665
  if (args.scopeType && !["platform", "namespace"].includes(args.scopeType)) throw new Error("Invalid --scope-type");
@@ -27069,11 +27093,11 @@ var HELP_TEXT = [
27069
27093
  ` ${import_chalk4.default.gray(" definition list [--base-url <url>] [--json]")}`,
27070
27094
  ` ${import_chalk4.default.gray(" definition create <role> [--display-name <name>] [--description <text>] [--base-url <url>] [--json]")}`,
27071
27095
  ` ${import_chalk4.default.gray(" definition update <role> [--display-name <name>] [--description <text>] [--status active|disabled]")}`,
27072
- ` ${import_chalk4.default.gray(" permission list|create|update [<action>] [--scope-type platform|namespace] [--status active|disabled]")}`,
27096
+ ` ${import_chalk4.default.gray(" permission list|create|update [<action>] [--scope-type platform|namespace] [--risk H|M|L] [--status active|disabled]")}`,
27073
27097
  ` ${import_chalk4.default.gray(" grant list|add|remove --role <role> [--permission <action>] [--scope platform | --namespace <ns|*>]")}`,
27074
27098
  ` ${import_chalk4.default.gray(" binding list|add|remove [--account <id>] [--role <role>]")}`,
27075
27099
  ` ${import_chalk4.default.gray(" check --permission <action> (--scope platform | --namespace <ns>) [--account <id>]")}`,
27076
- ` ${import_chalk4.default.gray(" migration preview|apply (root only)")}`,
27100
+ ` ${import_chalk4.default.gray(" migration preview|apply [--risk-model] (root only)")}`,
27077
27101
  ` ${import_chalk4.default.gray(" roles: admin (platform), blue/admin (namespace); shared flags: --base-url <url> --json")}`,
27078
27102
  ` ${import_chalk4.default.gray(" default base URL: https://auth-api-v2.pmate.chat")}`,
27079
27103
  ` ${import_chalk4.default.cyan("account")} View accounts and manage account role bindings`,
@@ -1,5 +1,5 @@
1
1
  const { createUpdateChecker, installUpdateHandlers } = require('./updates.cjs')
2
- const { app, BrowserWindow, session, shell, Menu, desktopCapturer, ipcMain, Notification, dialog } = require('electron')
2
+ const { app, BrowserWindow, session, shell, Menu, Tray, nativeImage, desktopCapturer, ipcMain, Notification, dialog } = require('electron')
3
3
  const path = require('node:path')
4
4
  const { installNotificationSettings } = require('./notification-settings.cjs')
5
5
  const { installMediaPermissions } = require('./media.cjs')
@@ -9,26 +9,35 @@ const { createRendererReach } = require('./reach-renderer.cjs')
9
9
  const { createDesktopCalls, supportsDesktopCalls } = require('./calls.cjs')
10
10
  const { installNavigationRestrictions } = require('./navigation.cjs')
11
11
  const { installDesktopApps } = require('./apps.cjs')
12
+ const { createDesktopTray } = require('./tray.cjs')
12
13
  const config = require('./desktop-config.json')
13
14
  app.setName(config.productName)
14
15
  if (process.platform === 'win32') app.setAppUserModelId(config.bundleId)
15
16
  // Stable across installer versions; separate from every other packaged PMate app.
16
17
  app.setPath('userData', path.join(app.getPath('appData'), config.bundleId))
17
18
  let mainWindow
18
- let desktopNotifications, desktopReach, desktopCalls, desktopApps
19
+ let desktopNotifications, desktopReach, desktopCalls, desktopApps, desktopTray
19
20
  function createWindow() {
20
- mainWindow = new BrowserWindow({ width: 1180, height: 820, minWidth: 380, minHeight: 540, title: config.productName, backgroundColor: '#f6f8fb', webPreferences: { additionalArguments: [`--pmate-app-version=${app.getVersion()}`, `--pmate-origin=${config.origin}`, `--pmate-desktop-calls=${supportsDesktopCalls(config.app)}`], preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:desktop', nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true } })
21
+ mainWindow = new BrowserWindow({ width: 1180, height: 820, minWidth: 380, minHeight: 540, title: config.productName, backgroundColor: '#f6f8fb', webPreferences: { additionalArguments: [`--pmate-app-version=${app.getVersion()}`, `--pmate-origin=${config.origin}`, `--pmate-desktop-calls=${supportsDesktopCalls(config.app)}`, `--pmate-desktop-tray=${!!config.tray}`], preload: path.join(__dirname, 'preload.cjs'), partition: 'persist:desktop', nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true } })
21
22
  installNavigationRestrictions(mainWindow, config, url => shell.openExternal(url))
22
23
  mainWindow.webContents.on('did-start-navigation', (_event, _url, _inPlace, mainFrame) => { if (mainFrame) desktopNotifications?.clearContext() })
23
24
  mainWindow.webContents.on('did-fail-load', (_event, code, _description, url, mainFrame) => {
24
25
  if (mainFrame && code !== -3 && url !== `${config.origin}/_desktop/offline`) void mainWindow.loadURL(`${config.origin}/_desktop/offline`).catch(error => console.error("Offline page failed:", error.message))
25
26
  })
26
27
  void mainWindow.loadURL(config.origin).catch(error => console.error("Page load failed:", error.message))
28
+ mainWindow.on('close', event => { if (desktopTray?.shouldHideOnClose()) { event.preventDefault(); mainWindow.hide() } })
27
29
  mainWindow.on('closed', () => { mainWindow = null })
30
+ return mainWindow
31
+ }
32
+ function showMainWindow() {
33
+ if (!mainWindow) createWindow()
34
+ if (mainWindow.isMinimized()) mainWindow.restore()
35
+ mainWindow.show(); mainWindow.focus()
36
+ return mainWindow
28
37
  }
29
38
  if (!app.requestSingleInstanceLock()) app.quit()
30
39
  else {
31
- app.on('second-instance', () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus() } })
40
+ app.on('second-instance', showMainWindow)
32
41
  app.whenReady().then(() => {
33
42
  const desktopSession = session.fromPartition('persist:desktop')
34
43
  desktopSession.protocol.handle('https', request => {
@@ -47,16 +56,17 @@ else {
47
56
  installNotificationSettings({ ipcMain, shell, origin: config.origin, getWindow: () => mainWindow })
48
57
  let updateController
49
58
  const checkForUpdates = createUpdateChecker({ app, dialog, shell, appId: config.app, getController: () => updateController })
59
+ if (config.tray) desktopTray = createDesktopTray({ Tray, Menu, nativeImage, iconPath: path.join(__dirname, 'trayTemplate.png'), unreadIconPath: path.join(__dirname, 'trayUnreadTemplate.png'),
60
+ productName: config.productName, getWindow: () => mainWindow, createWindow, checkForUpdates, quit: () => app.quit(), closeToTray: config.tray.closeToTray !== false })
50
61
  Menu.setApplicationMenu(Menu.buildFromTemplate([
51
62
  { role: 'appMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' },
52
63
  { label: config.productName, submenu: [{ label: '检查更新…', click: checkForUpdates }, { type: 'separator' }, { label: 'Back to app', click: () => { if (!mainWindow) createWindow(); else void mainWindow.loadURL(config.origin).catch(error => console.error("Page load failed:", error.message)) } }] },
53
64
  ]))
54
- desktopNotifications = createDesktopNotifications({ ipcMain, Notification, origin: config.origin, appId: config.app, getWindow: () => mainWindow, showWindow: () => {
55
- if (!mainWindow) createWindow()
56
- if (mainWindow.isMinimized()) mainWindow.restore()
57
- mainWindow.show(); mainWindow.focus()
58
- return mainWindow
59
- } })
65
+ desktopNotifications = createDesktopNotifications({ ipcMain, Notification, origin: config.origin, appId: config.app, getWindow: () => mainWindow, showWindow: showMainWindow })
66
+ if (desktopTray) ipcMain.handle('pmate:tray:unread', (event, count) => {
67
+ if (!desktopNotifications.trusted(event) || !Number.isSafeInteger(count) || count < 0 || count > 999999) throw new Error('Invalid tray unread count')
68
+ desktopTray.setUnread(count)
69
+ })
60
70
  desktopApps = installDesktopApps({ ipcMain, BrowserWindow, session: desktopSession, config, installNavigationRestrictions,
61
71
  openExternal: url => shell.openExternal(url), trusted: event => desktopNotifications.trusted(event) })
62
72
  updateController = installUpdateHandlers({ ipcMain, app, shell, appId: config.app, trusted: event => desktopNotifications.trusted(event), updater: require('electron-updater').autoUpdater, getWindow: () => mainWindow })
@@ -89,9 +99,10 @@ else {
89
99
  if (!desktopNotifications.trusted(event)) throw new Error('Untrusted reach sender')
90
100
  desktopReach.stop(); desktopNotifications.reset()
91
101
  })
92
- app.on('before-quit', () => { desktopApps.close(); desktopReach.stop(); desktopNotifications.reset() })
102
+ app.on('before-quit', () => { desktopTray?.beginQuit(); desktopApps.close(); desktopReach.stop(); desktopNotifications.reset() })
103
+ app.on('will-quit', () => desktopTray?.destroy())
93
104
  createWindow()
94
- app.on('activate', () => { if (!mainWindow) createWindow() })
105
+ app.on('activate', showMainWindow)
95
106
  }).catch(error => { console.error('Desktop startup failed:', error.message); app.exit(1) })
96
- app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() })
107
+ app.on('window-all-closed', () => { if (!config.tray && process.platform !== 'darwin') app.quit() })
97
108
  }
@@ -1,7 +1,7 @@
1
1
  const { contextBridge, ipcRenderer } = require('electron')
2
2
  const origin = process.argv.find(value => value.startsWith('--pmate-origin='))?.slice('--pmate-origin='.length)
3
3
  if (process.isMainFrame && location.origin === origin) contextBridge.exposeInMainWorld('pmateDesktop', Object.freeze({
4
- runtime: Object.freeze({ platform: process.platform, appVersion: process.argv.find(value => value.startsWith('--pmate-app-version='))?.slice('--pmate-app-version='.length), electronVersion: process.versions.electron, bridgeVersion: '1.2.0', contentSource: 'remote' }),
4
+ runtime: Object.freeze({ platform: process.platform, appVersion: process.argv.find(value => value.startsWith('--pmate-app-version='))?.slice('--pmate-app-version='.length), electronVersion: process.versions.electron, bridgeVersion: '1.3.0', contentSource: 'remote' }),
5
5
  updates: Object.freeze({
6
6
  check: () => ipcRenderer.invoke('pmate:update:check'),
7
7
  download: () => ipcRenderer.invoke('pmate:update:download'),
@@ -15,6 +15,9 @@ if (process.isMainFrame && location.origin === origin) contextBridge.exposeInMai
15
15
  apps: Object.freeze({
16
16
  open: url => ipcRenderer.invoke('pmate:app:open', url),
17
17
  }),
18
+ tray: process.argv.includes('--pmate-desktop-tray=true') ? Object.freeze({
19
+ setUnread: count => ipcRenderer.invoke('pmate:tray:unread', count),
20
+ }) : undefined,
18
21
  reach: Object.freeze({
19
22
  onEvent: handler => {
20
23
  const listener = (_event, value) => {
@@ -0,0 +1,49 @@
1
+ function createDesktopTray({ Tray, Menu, nativeImage, iconPath, unreadIconPath, productName, platform = process.platform, getWindow, createWindow, checkForUpdates, quit, closeToTray = true }) {
2
+ const load = path => {
3
+ const source = nativeImage.createFromPath(path)
4
+ if (source.isEmpty()) throw new Error(`Invalid tray icon: ${path}`)
5
+ const image = source.resize({ width: 18, height: 18, quality: 'best' })
6
+ if (platform === 'darwin') image.setTemplateImage(true)
7
+ return image
8
+ }
9
+ const icons = { idle: load(iconPath), unread: load(unreadIconPath) }
10
+ const tray = new Tray(icons.idle)
11
+ let quitting = false
12
+
13
+ const show = () => {
14
+ const window = getWindow() ?? createWindow()
15
+ if (window.isMinimized()) window.restore()
16
+ window.show()
17
+ window.focus()
18
+ return window
19
+ }
20
+ const hide = () => getWindow()?.hide()
21
+ const toggle = () => {
22
+ const window = getWindow()
23
+ if (window?.isVisible()) hide()
24
+ else show()
25
+ }
26
+ const menu = () => Menu.buildFromTemplate([
27
+ { label: `打开 ${productName}`, click: show },
28
+ { label: `隐藏 ${productName}`, enabled: !!getWindow()?.isVisible(), click: hide },
29
+ { type: 'separator' },
30
+ { label: '检查更新…', click: checkForUpdates },
31
+ { type: 'separator' },
32
+ { label: `退出 ${productName}`, click: () => { quitting = true; quit() } },
33
+ ])
34
+
35
+ tray.setToolTip(productName)
36
+ if (platform === 'darwin') tray.setIgnoreDoubleClickEvents(true)
37
+ tray.on('click', toggle)
38
+ tray.on('right-click', () => tray.popUpContextMenu(menu()))
39
+ return {
40
+ show,
41
+ hide,
42
+ setUnread(count) { tray.setImage(count > 0 ? icons.unread : icons.idle) },
43
+ shouldHideOnClose() { return closeToTray && !quitting },
44
+ beginQuit() { quitting = true },
45
+ destroy() { tray.destroy() },
46
+ }
47
+ }
48
+
49
+ module.exports = { createDesktopTray }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/cli",
3
- "version": "0.43.0",
3
+ "version": "0.44.1",
4
4
  "description": "CLI utilities for the pMate project",
5
5
  "license": "MIT",
6
6
  "bin": {