easy-claude 0.3.4 → 1.0.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.
@@ -5,8 +5,9 @@
5
5
  <key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
6
6
  <key>CFBundleName</key><string>Easy Claude Overlay</string>
7
7
  <key>CFBundlePackageType</key><string>APPL</string>
8
- <key>CFBundleShortVersionString</key><string>0.3.4</string>
8
+ <key>CFBundleShortVersionString</key><string>1.0.2</string>
9
9
  <key>LSMinimumSystemVersion</key><string>14.0</string>
10
+ <key>CFBundleLocalizations</key><array><string>en</string><string>zh-Hans</string><string>zh-Hant</string></array>
10
11
  <key>LSUIElement</key><true/>
11
12
  <key>NSHighResolutionCapable</key><true/>
12
13
  </dict></plist>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-claude",
3
- "version": "0.3.4",
3
+ "version": "1.0.2",
4
4
  "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  "bin",
11
11
  "src",
12
12
  "README.md",
13
+ "README.zh-CN.md",
13
14
  "native/Overlay.swift",
14
15
  "native/build/EasyClaudeOverlay.app",
15
16
  "scripts/build-overlay.mjs",
@@ -24,7 +25,9 @@
24
25
  "build:overlay": "node scripts/build-overlay.mjs",
25
26
  "test:native": "python3 scripts/test-native-update.py",
26
27
  "test:lock": "python3 scripts/test-native-lock.py",
27
- "test:reminder": "python3 scripts/test-native-reminder.py"
28
+ "test:reminder": "python3 scripts/test-native-reminder.py",
29
+ "test:controls": "python3 scripts/test-controls.py",
30
+ "test:refresh": "python3 scripts/test-refresh.py"
28
31
  },
29
32
  "license": "MIT",
30
33
  "author": "UnionSchool",
@@ -27,6 +27,7 @@ await writeFile(`${app}/Info.plist`, `<?xml version="1.0" encoding="UTF-8"?>
27
27
  <key>CFBundlePackageType</key><string>APPL</string>
28
28
  <key>CFBundleShortVersionString</key><string>${version}</string>
29
29
  <key>LSMinimumSystemVersion</key><string>14.0</string>
30
+ <key>CFBundleLocalizations</key><array><string>en</string><string>zh-Hans</string><string>zh-Hant</string></array>
30
31
  <key>LSUIElement</key><true/>
31
32
  <key>NSHighResolutionCapable</key><true/>
32
33
  </dict></plist>`);
package/src/format.js CHANGED
@@ -1,37 +1,38 @@
1
+ import { L } from './language.js';
1
2
  function duration(minutes, fallback) {
2
3
  if (!Number.isFinite(minutes) || minutes <= 0) return fallback;
3
- if (minutes % 1440 === 0) return `${minutes / 1440} 天`;
4
- if (minutes % 60 === 0) return `${minutes / 60} 小时`;
5
- return `${minutes} 分钟`;
4
+ if (minutes % 1440 === 0) return L(`${minutes / 1440} 天`, `${minutes / 1440} days`);
5
+ if (minutes % 60 === 0) return L(`${minutes / 60} 小时`, `${minutes / 60} hours`);
6
+ return L(`${minutes} 分钟`, `${minutes} minutes`);
6
7
  }
7
8
 
8
9
  function windowText(window, label) {
9
- if (!window || typeof window !== 'object') return ` ${label}:未知(未提供数据)`;
10
+ if (!window || typeof window !== 'object') return L(` ${label}:未知(未提供数据)`, ` ${label}: unknown (no data)`);
10
11
  const remaining = Number.isFinite(window.usedPercent)
11
12
  ? `${Number(Math.max(0, Math.min(100, 100 - window.usedPercent)).toFixed(1))}%`
12
- : '未知';
13
+ : L('未知', 'Unknown');
13
14
  const date = Number.isFinite(window.resetsAt) ? new Date(window.resetsAt * 1000) : null;
14
- const reset = date && Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '未知';
15
- return ` ${duration(window.windowDurationMins, label)}:剩余 ${remaining};重置 ${reset}`;
15
+ const reset = date && Number.isFinite(date.getTime()) ? date.toLocaleString() : L('未知', 'Unknown');
16
+ return L(` ${duration(window.windowDurationMins, label)}:剩余 ${remaining};重置 ${reset}`, ` ${duration(window.windowDurationMins, label)}: ${remaining} left; resets ${reset}`);
16
17
  }
17
18
 
18
19
  export function formatUsage(result) {
19
- if (!result || typeof result !== 'object') throw new Error('额度响应格式无效。');
20
+ if (!result || typeof result !== 'object') throw new Error(L('额度响应格式无效。', 'Invalid usage response.'));
20
21
  const buckets = result.rateLimitsByLimitId;
21
22
  const entries = buckets && typeof buckets === 'object' && !Array.isArray(buckets)
22
23
  ? Object.entries(buckets).filter(([, value]) => value && typeof value === 'object') : [];
23
24
  if (!entries.length && result.rateLimits && typeof result.rateLimits === 'object') {
24
25
  entries.push([result.rateLimits.limitId ?? 'claude', result.rateLimits]);
25
26
  }
26
- if (!entries.length) throw new Error('服务端未提供额度数据,无法判断剩余额度。');
27
- const output = ['Claude Code 剩余额度(账号共享,非当前会话)'];
27
+ if (!entries.length) throw new Error(L('服务端未提供额度数据,无法判断剩余额度。', 'The server returned no usage limits. Remaining usage is unknown.'));
28
+ const output = [L('Claude Code 剩余额度(账号共享,非当前会话)', 'Claude Code remaining usage (shared account, not this session)')];
28
29
  for (const [id, bucket] of entries) {
29
30
  // 限制服务端标签中的控制字符,避免终端转义序列影响显示。
30
31
  const label = String(bucket.limitName || bucket.limitId || id).replace(/[\x00-\x1f\x7f-\x9f]/g, '');
31
- output.push(label, windowText(bucket.primary, '主窗口'));
32
- if (bucket.secondary) output.push(windowText(bucket.secondary, '次窗口'));
32
+ output.push(label, windowText(bucket.primary, L('主窗口', 'Primary')));
33
+ if (bucket.secondary) output.push(windowText(bucket.secondary, L('次窗口', 'Secondary')));
33
34
  }
34
- if (result.ordinaryUsageAllowed === false) output.push('服务端提示:当前普通额度使用受限。');
35
- output.push(`重置时间使用本机时区:${Intl.DateTimeFormat().resolvedOptions().timeZone}`);
35
+ if (result.ordinaryUsageAllowed === false) output.push(L('服务端提示:当前普通额度使用受限。', 'Server reports restricted usage.'));
36
+ output.push(L(`重置时间使用本机时区:${Intl.DateTimeFormat().resolvedOptions().timeZone}`, `Reset times use the local time zone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`));
36
37
  return output.join('\n');
37
38
  }
@@ -0,0 +1,22 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ export function resolveLanguage(choice, preferred = 'en') {
5
+ return ['zh', 'en'].includes(choice) ? choice : /^zh(?:[-_]|$)/i.test(preferred) ? 'zh' : 'en';
6
+ }
7
+ let preference;
8
+ function storedLanguage() {
9
+ if (preference !== undefined) return preference;
10
+ let selected = 'system', preferred = Intl.DateTimeFormat().resolvedOptions().locale;
11
+ if (process.platform === 'darwin') {
12
+ const { name } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
13
+ try { selected = execFileSync('/usr/bin/defaults', ['read', `com.unionschool.${name}.overlay`, 'interfaceLanguage'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1000 }).trim(); } catch { /* 未设置时跟随系统。 */ }
14
+ try { preferred = execFileSync('/usr/bin/defaults', ['read', '-g', 'AppleLanguages'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1000 }).match(/[a-z]{2,3}(?:[-_][A-Za-z0-9]+)*/i)?.[0] ?? preferred; } catch { /* 其他系统保留Intl地区。 */ }
15
+ }
16
+ preference = resolveLanguage(selected, preferred);
17
+ return preference;
18
+ }
19
+ export function language() {
20
+ return ['zh', 'en'].includes(process.env.EASY_LANGUAGE) ? process.env.EASY_LANGUAGE : storedLanguage();
21
+ }
22
+ export function L(chinese, english) { return language() === 'zh' ? chinese : english; }
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { formatUsage } from './usage.js';
2
3
 
3
4
  export function overlayData(result, now = Date.now()) {
@@ -13,8 +14,8 @@ export function overlayData(result, now = Date.now()) {
13
14
  if (!w) continue;
14
15
  const mins = w.windowDurationMins;
15
16
  const label = Number.isFinite(mins) && mins > 0
16
- ? mins % 1440 === 0 ? `${mins / 1440}天` : mins % 60 === 0 ? `${mins / 60}小时` : `${mins}分钟`
17
- : key === 'primary' ? '主窗口' : '次窗口';
17
+ ? mins % 1440 === 0 ? L(`${mins / 1440}天`, `${mins / 1440}d`) : mins % 60 === 0 ? L(`${mins / 60}小时`, `${mins / 60}h`) : L(`${mins}分钟`, `${mins}m`)
18
+ : key === 'primary' ? L('主窗口', 'Primary') : L('次窗口', 'Secondary');
18
19
  windows.push({ id: `${id}:${key}`, label,
19
20
  name: `${String(bucket.limitName || id).replace(/[\x00-\x1f\x7f-\x9f]/g, '')} · ${label}`,
20
21
  remaining: Number.isFinite(w.usedPercent) ? Math.max(0, Math.min(100, 100 - w.usedPercent)) : null,
@@ -23,3 +24,8 @@ export function overlayData(result, now = Date.now()) {
23
24
  }
24
25
  return { windows, detail, fetchedAt: now / 1000, restricted: result.ordinaryUsageAllowed === false };
25
26
  }
27
+
28
+ export function overlayError(error) {
29
+ return { error: error?.message || L('额度查询失败', 'Usage query failed'),
30
+ errorCode: ['auth_required','auth_expired','rate_limited'].includes(error?.code) ? error.code : 'query_failed' };
31
+ }
package/src/overlay-ip.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { readPublicIP } from './public-ip.js';
2
3
  try { console.log(JSON.stringify(await readPublicIP())); }
3
- catch { console.log(JSON.stringify({ error: 'IP异常' })); process.exitCode = 1; }
4
+ catch { console.log(JSON.stringify({ error: L('IP异常', 'IP unavailable') })); process.exitCode = 1; }
@@ -1,14 +1,15 @@
1
+ import { L } from './language.js';
1
2
  import { readUsage } from './usage.js';
2
- import { overlayData } from './overlay-data.js';
3
+ import { overlayData, overlayError } from './overlay-data.js';
3
4
  const controller = new AbortController();
4
5
  process.once('SIGTERM', () => controller.abort());
5
6
  process.once('SIGINT', () => controller.abort());
6
7
  try {
7
8
  const text = JSON.stringify(overlayData(await readUsage({ signal: controller.signal })));
8
9
  // 原生端在进程结束后读取管道;限制体积以免写端等待管道空间。
9
- if (Buffer.byteLength(text) > 12000) throw new Error('额度响应过大,请使用 easy-claude 查看完整数据。');
10
+ if (Buffer.byteLength(text) > 12000) throw new Error(L('额度响应过大,请使用 easy-claude 查看完整数据。', 'Usage response too large. Run easy-claude for full details.'));
10
11
  console.log(text);
11
12
  } catch (error) {
12
- console.log(JSON.stringify({ error: error.message }));
13
+ console.log(JSON.stringify(overlayError(error)));
13
14
  process.exitCode = 1;
14
15
  }
package/src/overlay.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { access } from 'node:fs/promises';
2
3
  import { constants } from 'node:fs';
3
4
  import { fileURLToPath } from 'node:url';
@@ -5,13 +6,13 @@ import { execFile } from 'node:child_process';
5
6
  import { promisify } from 'node:util';
6
7
 
7
8
  export async function launchOverlay({ platform = process.platform, check = access, run = promisify(execFile) } = {}) {
8
- if (platform !== 'darwin') throw new Error('浮窗首版仅支持 macOS。');
9
+ if (platform !== 'darwin') throw new Error(L('浮窗首版仅支持 macOS。', 'The overlay requires macOS.'));
9
10
  const app = fileURLToPath(new URL('../native/build/EasyClaudeOverlay.app', import.meta.url));
10
11
  try { await check(`${app}/Contents/MacOS/EasyClaudeOverlay`, constants.X_OK); }
11
- catch { throw new Error('尚未构建浮窗,请在项目目录执行 npm run build:overlay。'); }
12
+ catch { throw new Error(L('尚未构建浮窗,请在项目目录执行 npm run build:overlay。', 'Overlay not built. Run npm run build:overlay in the project directory.')); }
12
13
  try { await run(`${app}/Contents/MacOS/EasyClaudeOverlay`, ['--quit-running'], { timeout: 7000, maxBuffer: 4096 }); }
13
- catch { throw new Error('无法退出旧浮窗,请从菜单退出后重试。'); }
14
+ catch { throw new Error(L('无法退出旧浮窗,请从菜单退出后重试。', 'Cannot close the previous overlay. Quit it from the menu and retry.')); }
14
15
  await run('/usr/bin/open', ['-g', '-a', app, '--args',
15
16
  process.execPath, fileURLToPath(new URL('./overlay-query.js', import.meta.url)), process.env.PATH ?? '', process.env.CLAUDE_CONFIG_DIR ?? '']);
16
- console.log('额度与电子时钟浮窗已启动;Claude 在前台时显示。拖动调整位置,右键或菜单栏 EA 可设置时区、查看双环额度和退出。');
17
+ console.log(L('额度与电子时钟浮窗已启动;Claude 在前台时显示。拖动调整位置;左键状态栏图标打开控制面板,右键保留兼容菜单。', 'Overlay started; visible while Claude is in front. Drag to reposition. Left-click the menu bar icon for controls; right-click for the menu.'));
17
18
  }
package/src/public-ip.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { execFile } from 'node:child_process';
2
3
  import { promisify } from 'node:util';
3
4
  import { isIP } from 'node:net';
@@ -18,8 +19,8 @@ export async function readPublicIP({ run = promisify(execFile), env = process.en
18
19
  };
19
20
  let data;
20
21
  try { data = JSON.parse(await request('https://ipinfo.io/json')); }
21
- catch { throw new Error('IP异常'); }
22
- if (!data || typeof data.ip !== 'string' || !isIP(data.ip)) throw new Error('IP异常');
22
+ catch { throw new Error(L('IP异常', 'IP unavailable')); }
23
+ if (!data || typeof data.ip !== 'string' || !isIP(data.ip)) throw new Error(L('IP异常', 'IP unavailable'));
23
24
  const ip = data.ip;
24
25
  let city = null, timezone = null;
25
26
  if (typeof data.city === 'string') {
package/src/transport.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { execFile, spawn } from 'node:child_process';
2
3
  import { promisify } from 'node:util';
3
4
 
@@ -10,15 +11,15 @@ export function systemProxy(text) {
10
11
  const host = value('HTTPSProxy');
11
12
  const port = Number(value('HTTPSPort'));
12
13
  if (!host || !/^[a-zA-Z0-9.:-]+$/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) {
13
- throw new Error('系统 HTTPS 代理配置无效。');
14
+ throw new Error(L('系统 HTTPS 代理配置无效。', 'Invalid system HTTPS proxy configuration.'));
14
15
  }
15
16
  return `http://${host.includes(':') ? `[${host}]` : host}:${port}`;
16
17
  }
17
18
 
18
19
  export function curlConfig(url, headers, proxy) {
19
- if (url !== endpoint) throw new Error('仅允许官方额度地址。');
20
+ if (url !== endpoint) throw new Error(L('仅允许官方额度地址。', 'Only the official usage endpoint is allowed.'));
20
21
  const quote = value => {
21
- if (/[\r\n\0]/.test(value)) throw new Error('请求配置包含无效字符。');
22
+ if (/[\r\n\0]/.test(value)) throw new Error(L('请求配置包含无效字符。', 'Request configuration contains invalid characters.'));
22
23
  return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
23
24
  };
24
25
  return [`url = ${quote(url)}`, `proxy = ${quote(proxy)}`,
@@ -40,19 +41,19 @@ export async function quotaFetch(url, options) {
40
41
  let size = 0;
41
42
  child.stdout.on('data', data => {
42
43
  size += data.length;
43
- if (size > 1024 * 1024) { child.kill(); reject(new Error('额度响应过大。')); }
44
+ if (size > 1024 * 1024) { child.kill(); reject(new Error(L('额度响应过大。', 'Usage response too large.'))); }
44
45
  else chunks.push(data);
45
46
  });
46
- child.on('error', () => reject(new Error('额度代理请求失败。')));
47
+ child.on('error', () => reject(new Error(L('额度代理请求失败。', 'Usage proxy request failed.'))));
47
48
  child.stdin.on('error', () => {});
48
49
  child.on('close', code => {
49
- if (code !== 0) { reject(new Error('额度代理请求失败。')); return; }
50
+ if (code !== 0) { reject(new Error(L('额度代理请求失败。', 'Usage proxy request failed.'))); return; }
50
51
  const output = Buffer.concat(chunks).toString('utf8');
51
52
  const split = output.lastIndexOf('\n');
52
53
  const status = Number(output.slice(split + 1));
53
54
  if (status < 200 || status >= 300) {
54
55
  if (status >= 400 && status <= 599) resolve(new Response(null, { status }));
55
- else reject(new Error('额度请求收到无效响应或重定向。'));
56
+ else reject(new Error(L('额度请求收到无效响应或重定向。', 'Invalid usage response or redirect.')));
56
57
  return;
57
58
  }
58
59
  resolve(new Response(output.slice(0, split), { status }));
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { join } from 'node:path';
3
4
  import { tmpdir } from 'node:os';
@@ -14,9 +15,9 @@ const helper = fileURLToPath(new URL('../native/build/EasyClaudeOverlay.app/Cont
14
15
  function runHelper(command, args) {
15
16
  return new Promise((resolve, reject) => {
16
17
  const child = spawn(command, args, { stdio: 'inherit', shell: false });
17
- child.once('error', () => reject(new Error('无法启动系统更新锁组件,请重新安装此工具。')));
18
+ child.once('error', () => reject(new Error(L('无法启动系统更新锁组件,请重新安装此工具。', 'Cannot start the update lock helper. Reinstall this tool.'))));
18
19
  child.once('exit', (code, signal) => {
19
- if (signal) reject(new Error('更新进程已中断;系统会在安装进程退出后自动释放锁。'));
20
+ if (signal) reject(new Error(L('更新进程已中断;系统会在安装进程退出后自动释放锁。', 'Update interrupted. The lock is released when installation exits.')));
20
21
  else resolve(code);
21
22
  });
22
23
  });
@@ -25,11 +26,11 @@ function runHelper(command, args) {
25
26
  export async function runWithUpdateLock(command, args, {
26
27
  lock = lockFile, binary = helper, run = runHelper, platform = process.platform
27
28
  } = {}) {
28
- if (platform !== 'darwin') throw new Error('浮窗更新仅支持 macOS。');
29
+ if (platform !== 'darwin') throw new Error(L('浮窗更新仅支持 macOS。', 'Overlay updates require macOS.'));
29
30
  const code = await run(binary, ['--with-update-lock', lock, command, ...args]);
30
31
  if (code === 0) return;
31
- if (code === 75) throw new Error('另一个 Easy 工具正在更新,请稍后重试;无需清理更新锁。');
32
- if (code === 73) throw new Error('无法建立系统更新锁,请检查临时目录权限。');
33
- if (code === 74) throw new Error('无法启动更新程序,请检查 Node.js 安装。');
34
- throw new Error('更新未完成,请查看上方提示后重试。');
32
+ if (code === 75) throw new Error(L('另一个 Easy 工具正在更新,请稍后重试;无需清理更新锁。', 'Another Easy update is running. Try again later; do not remove the lock.'));
33
+ if (code === 73) throw new Error(L('无法建立系统更新锁,请检查临时目录权限。', 'Cannot acquire the update lock. Check temporary directory permissions.'));
34
+ if (code === 74) throw new Error(L('无法启动更新程序,请检查 Node.js 安装。', 'Cannot start the updater. Check the Node.js installation.'));
35
+ throw new Error(L('更新未完成,请查看上方提示后重试。', 'Update incomplete. Check the messages above and retry.'));
35
36
  }
package/src/update.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { access, realpath } from 'node:fs/promises';
2
3
  import { readFileSync } from 'node:fs';
3
4
  import { dirname, basename, join, delimiter } from 'node:path';
@@ -15,7 +16,7 @@ export function installedPrefix(root, platform = process.platform) {
15
16
 
16
17
  export function isNewer(latest, current) {
17
18
  if (!/^\d+\.\d+\.\d+$/.test(latest) || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(current)) {
18
- throw new Error('无法识别正式版本号,未执行更新。');
19
+ throw new Error(L('无法识别正式版本号,未执行更新。', 'Invalid release version. Update not started.'));
19
20
  }
20
21
  const a = latest.split('.').map(Number), b = current.split('-')[0].split('.').map(Number);
21
22
  for (let i = 0; i < 3; i++) { if (a[i] !== b[i]) return a[i] > b[i]; }
@@ -31,7 +32,7 @@ async function findNpmCli() {
31
32
  catch { /* npm 可能位于 PATH 中另一套 Node 的旁边。 */ }
32
33
  }
33
34
  }
34
- throw new Error('未找到 npm,请先安装 Node.js/npm,再使用 npm i -g 更新。');
35
+ throw new Error(L('未找到 npm,请先安装 Node.js/npm,再使用 npm i -g 更新。', 'npm not found. Install Node.js/npm, then update with npm i -g.'));
35
36
  }
36
37
 
37
38
  export async function readLatest(npmCli, name) {
@@ -39,16 +40,16 @@ export async function readLatest(npmCli, name) {
39
40
  const { stdout } = await promisify(execFile)(process.execPath, [npmCli, 'view', name, 'dist-tags.latest',
40
41
  '--json', '--prefer-online', '--registry=https://registry.npmjs.org'], { timeout: 30000, maxBuffer: 4096 });
41
42
  return JSON.parse(stdout);
42
- } catch { throw new Error('无法在线检查 npm 最新版本,请检查网络后重试。'); }
43
+ } catch { throw new Error(L('无法在线检查 npm 最新版本,请检查网络后重试。', 'Cannot check the latest npm version. Check the network and retry.')); }
43
44
  }
44
45
 
45
46
  function runNpm(command, args) {
46
47
  return new Promise((resolve, reject) => {
47
48
  const child = spawn(command, args, { stdio: 'inherit', shell: false });
48
- child.once('error', () => reject(new Error('无法启动 npm 更新。')));
49
+ child.once('error', () => reject(new Error(L('无法启动 npm 更新。', 'Cannot start npm update.'))));
49
50
  child.once('exit', (code, signal) => {
50
51
  if (code === 0) resolve();
51
- else reject(new Error(`npm 更新失败(${signal ?? code ?? '未知状态'}),请检查网络或安装目录权限。`));
52
+ else reject(new Error(L(`npm 更新失败(${signal ?? code ?? '未知状态'}),请检查网络或安装目录权限。`, `npm update failed (${signal ?? code ?? 'unknown'}). Check network and installation permissions.`)));
52
53
  });
53
54
  });
54
55
  }
@@ -57,13 +58,13 @@ export async function updatePackage(name, { root = fileURLToPath(new URL('../',
57
58
  getNpmCli = findNpmCli, getLatest = readLatest,
58
59
  currentVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version,
59
60
  run = runNpm, platform = process.platform } = {}) {
60
- if (!['easy-codex', 'easy-claude'].includes(name)) throw new Error('不支持的更新包名。');
61
+ if (!['easy-codex', 'easy-claude'].includes(name)) throw new Error(L('不支持的更新包名。', 'Unsupported update package.'));
61
62
  const npmCli = await getNpmCli();
62
63
  const latest = await getLatest(npmCli, name);
63
64
  if (!isNewer(latest, currentVersion)) {
64
65
  console.log(currentVersion === latest
65
- ? `${name} 已经是最新版本(${currentVersion})。`
66
- : `${name} 当前版本 ${currentVersion} 高于 npm 最新版本 ${latest},无需更新。`);
66
+ ? L(`${name} 已经是最新版本(${currentVersion})。`, `${name} is already up to date (${currentVersion}).`)
67
+ : L(`${name} 当前版本 ${currentVersion} 高于 npm 最新版本 ${latest},无需更新。`, `${name} ${currentVersion} is newer than npm ${latest}; no update needed.`));
67
68
  return false;
68
69
  }
69
70
  const prefix = installedPrefix(root, platform);
@@ -71,13 +72,13 @@ export async function updatePackage(name, { root = fileURLToPath(new URL('../',
71
72
  const args = [npmCli, 'install', '--global', ...(prefix ? ['--prefix', prefix] : []),
72
73
  '--prefer-online', '--registry=https://registry.npmjs.org', `${name}@${latest}`];
73
74
  await run(process.execPath, args);
74
- console.log(`${name} 已更新到 ${latest}。`);
75
+ console.log(L(`${name} 已更新到 ${latest}。`, `${name} updated to ${latest}.`));
75
76
  return true;
76
77
  }
77
78
 
78
79
  export async function checkUpdate(name, { getNpmCli = findNpmCli, getLatest = readLatest,
79
80
  currentVersion = version } = {}) {
80
- if (!['easy-codex', 'easy-claude'].includes(name)) throw new Error('不支持的更新包名。');
81
+ if (!['easy-codex', 'easy-claude'].includes(name)) throw new Error(L('不支持的更新包名。', 'Unsupported update package.'));
81
82
  const latest = await getLatest(await getNpmCli(), name);
82
83
  return { latest, available: isNewer(latest, currentVersion) };
83
84
  }
package/src/usage.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { L } from './language.js';
1
2
  import { quotaFetch } from './transport.js';
2
3
  import { readFile } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
@@ -6,13 +7,13 @@ import { execFile } from 'node:child_process';
6
7
  import { promisify } from 'node:util';
7
8
  export { formatUsage } from './format.js';
8
9
  const run = promisify(execFile);
9
- const loginMessage = '请执行 claude auth login 登录与 Claude 桌面相同的订阅账号。';
10
+ const loginMessage = L('请执行 claude auth login 登录与 Claude 桌面相同的订阅账号。', 'Run claude auth login with the same subscription account as Claude Desktop.');
10
11
 
11
12
  export function credentialToken(raw, now = Date.now()) {
12
13
  let auth;
13
- try { auth = JSON.parse(raw)?.claudeAiOauth; } catch { throw new Error(`Claude Code 登录数据格式不受支持。${loginMessage}`); }
14
- if (!auth || typeof auth.accessToken !== 'string' || !auth.accessToken.trim()) throw new Error(loginMessage);
15
- if (Number.isFinite(auth.expiresAt) && auth.expiresAt <= now) throw new Error(`Claude Code 登录已过期。${loginMessage}`);
14
+ try { auth = JSON.parse(raw)?.claudeAiOauth; } catch { throw new Error(L(`Claude Code 登录数据格式不受支持。${loginMessage}`, `Unsupported Claude Code login data. ${loginMessage}`)); }
15
+ if (!auth || typeof auth.accessToken !== 'string' || !auth.accessToken.trim()) throw Object.assign(new Error(loginMessage), { code: 'auth_required' });
16
+ if (Number.isFinite(auth.expiresAt) && auth.expiresAt <= now) throw Object.assign(new Error(L(`Claude Code 登录已过期。${loginMessage}`, `Claude Code login expired. ${loginMessage}`)), { code: 'auth_expired' });
16
17
  return auth.accessToken;
17
18
  }
18
19
 
@@ -21,38 +22,38 @@ export async function loadToken({ signal } = {}) {
21
22
  // 自定义配置目录不猜测钥匙串名称,以免读到另一个账号。
22
23
  if (process.platform === 'darwin' && !process.env.CLAUDE_CONFIG_DIR) {
23
24
  try { raw = (await run('/usr/bin/security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], { timeout: 5000, maxBuffer: 1024 * 1024, signal })).stdout; }
24
- catch { if (signal?.aborted) throw new Error('查询已取消。'); }
25
+ catch { if (signal?.aborted) throw new Error(L('查询已取消。', 'Query cancelled.')); }
25
26
  }
26
27
  if (!raw) {
27
28
  try { raw = await readFile(join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), '.credentials.json'), { encoding: 'utf8', signal }); }
28
- catch { throw new Error(signal?.aborted ? '查询已取消。' : `未找到可读取的 Claude Code 订阅登录。${loginMessage}`); }
29
+ catch { throw Object.assign(new Error(signal?.aborted ? L('查询已取消。', 'Query cancelled.') : L(`未找到可读取的 Claude Code 订阅登录。${loginMessage}`, `No readable Claude Code subscription login found. ${loginMessage}`)), { code: signal?.aborted ? undefined : 'auth_required' }); }
29
30
  }
30
31
  return credentialToken(raw);
31
32
  }
32
33
 
33
34
  export function normalizeUsage(data) {
34
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('额度响应格式无效。');
35
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(L('额度响应格式无效。', 'Invalid usage response.'));
35
36
  const rateLimitsByLimitId = {};
36
37
  for (const [key, value] of Object.entries(data)) {
37
38
  if (!/^(five_hour|seven_day)(_[a-z0-9_]+)?$/.test(key) || value == null) continue;
38
- if (typeof value !== 'object' || Array.isArray(value)) throw new Error('额度窗口格式无效。');
39
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error(L('额度窗口格式无效。', 'Invalid usage window.'));
39
40
  // 明细汇总也使用 seven_day 前缀,只有比例字段才代表额度窗口。
40
41
  if (!Object.hasOwn(value, 'utilization')) continue;
41
42
  const used = value.utilization;
42
- if (used != null && (!Number.isFinite(used) || used < 0 || used > 100)) throw new Error('额度比例格式无效。');
43
+ if (used != null && (!Number.isFinite(used) || used < 0 || used > 100)) throw new Error(L('额度比例格式无效。', 'Invalid usage percentage.'));
43
44
  const reset = typeof value.resets_at === 'string' ? Date.parse(value.resets_at) / 1000 : null;
44
45
  const primary = { usedPercent: used ?? null, resetsAt: Number.isFinite(reset) ? reset : null, windowDurationMins: key.startsWith('five_hour') ? 300 : 10080 };
45
- const label = key === 'five_hour' ? 'Claude · 5 小时' : key === 'seven_day' ? 'Claude · 7 天' : key.replaceAll('_', ' ');
46
+ const label = key === 'five_hour' ? L('Claude · 5 小时', 'Claude · 5 hours') : key === 'seven_day' ? L('Claude · 7 天', 'Claude · 7 days') : key.replaceAll('_', ' ');
46
47
  rateLimitsByLimitId[key] = { limitId: key, limitName: label, primary };
47
48
  }
48
- if (!Object.keys(rateLimitsByLimitId).length) throw new Error('服务端未提供订阅额度,不能判断剩余额度;API Key 余额不在范围内。');
49
+ if (!Object.keys(rateLimitsByLimitId).length) throw new Error(L('服务端未提供订阅额度,不能判断剩余额度;API Key 余额不在范围内。', 'No subscription usage returned. Remaining usage is unknown; API key balances are not supported.'));
49
50
  return { rateLimitsByLimitId };
50
51
  }
51
52
 
52
53
  export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToken, fetchImpl = quotaFetch } = {}) {
53
54
  const controller = new AbortController();
54
55
  const abort = () => controller.abort();
55
- if (signal?.aborted) throw new Error('查询已取消。');
56
+ if (signal?.aborted) throw new Error(L('查询已取消。', 'Query cancelled.'));
56
57
  signal?.addEventListener('abort', abort, { once: true });
57
58
  const timer = setTimeout(abort, timeoutMs);
58
59
  try {
@@ -61,16 +62,16 @@ export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToke
61
62
  const response = await fetchImpl('https://api.anthropic.com/api/oauth/usage', {
62
63
  headers: { authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', accept: 'application/json' },
63
64
  redirect: 'error', signal: controller.signal,
64
- }).catch(() => { throw new Error('无法连接 Claude 额度服务,请检查网络。'); });
65
- if (response.status === 401) throw new Error(`订阅登录已失效(HTTP 401)。${loginMessage}`);
66
- if (response.status === 403) throw new Error('Claude 官方额度服务拒绝访问(HTTP 403)。可能是账号权限、网络访问限制或接口兼容变化;请先检查 Claude Code 的 /usage,不能仅据此判断登录已过期。');
67
- if (response.status === 429) throw new Error('额度查询过于频繁,请稍后再试。');
68
- if (!response.ok) throw new Error(`Claude 额度服务暂不可用(HTTP ${response.status})。`);
65
+ }).catch(() => { throw new Error(L('无法连接 Claude 额度服务,请检查网络。', 'Cannot connect to Claude usage service. Check the network.')); });
66
+ if (response.status === 401) throw Object.assign(new Error(L(`订阅登录已失效(HTTP 401)。${loginMessage}`, `Subscription login expired (HTTP 401). ${loginMessage}`)), { code: 'auth_expired' });
67
+ if (response.status === 403) throw new Error(L('Claude 官方额度服务拒绝访问(HTTP 403)。可能是账号权限、网络访问限制或接口兼容变化;请先检查 Claude Code 的 /usage,不能仅据此判断登录已过期。', 'Claude usage service denied access (HTTP 403). Check account permissions, network access and Claude Code /usage; this does not necessarily mean an expired login.'));
68
+ if (response.status === 429) throw Object.assign(new Error(L('额度查询过于频繁,请稍后再试。', 'Too many usage requests. Try again later.')), { code: 'rate_limited' });
69
+ if (!response.ok) throw new Error(L(`Claude 额度服务暂不可用(HTTP ${response.status})。`, `Claude usage service unavailable (HTTP ${response.status}).`));
69
70
  let data;
70
- try { data = await response.json(); } catch { throw new Error('Claude 返回了无效的额度数据。'); }
71
+ try { data = await response.json(); } catch { throw new Error(L('Claude 返回了无效的额度数据。', 'Claude returned invalid usage data.')); }
71
72
  return normalizeUsage(data);
72
73
  } catch (error) {
73
- if (controller.signal.aborted) throw new Error(signal?.aborted ? '查询已取消。' : '额度查询超时,请检查网络。');
74
+ if (controller.signal.aborted) throw new Error(signal?.aborted ? L('查询已取消。', 'Query cancelled.') : L('额度查询超时,请检查网络。', 'Usage query timed out. Check the network.'));
74
75
  throw error;
75
76
  } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
76
77
  }