dsh-cookie-cleaner 0.1.0 → 0.1.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,39 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 「文件属于别的用户」这一档的 9 语文案(单文件集中放,便于核对)。
3
+ *
4
+ * 触发条件见 core.js 的 classifyOpenFailure:POSIX 上 stat.uid ≠ process.getuid()。
5
+ * 实测 node:sqlite 在权限不足时**不报 EACCES**(只报 unable to open database file),
6
+ * 所以这一档不能靠错误码判定,只能自己探属主。
7
+ */
8
+
9
+ /** @type {Record<string,string>} */
10
+ export const ADVISE_OWNER = {
11
+ zh: ' 处置:这个文件属于另一个用户(不是跑本命令的你)。用那个账号跑,或用 --db=<完整路径> 指向你自己那份库。',
12
+ en: ' What to do: this file belongs to another user, not the one running this command. Run it as that account, or point at your own store with --db=<full path>.',
13
+ ja: ' 対処:このファイルは別ユーザーの所有です(本コマンドの実行者ではありません)。そのアカウントで実行するか、--db=<フルパス> で自身のデータベースを指定してください。',
14
+ ko: ' 조치: 이 파일은 다른 사용자의 소유입니다(본 명령의 실행자가 아님). 해당 계정으로 실행하거나 --db=<전체 경로>로 자신의 데이터베이스를 지정하세요.',
15
+ fr: ' À faire : ce fichier appartient à un autre utilisateur que celui qui lance la commande. Exécutez-le sous ce compte, ou désignez votre propre base avec --db=<chemin complet>.',
16
+ de: ' Vorgehen: diese Datei gehört einem anderen Nutzer als dem, der diesen Befehl ausführt. Führen Sie ihn als diesen Nutzer aus, oder zeigen Sie mit --db=<vollständiger Pfad> auf Ihre eigene Datenbank.',
17
+ it: ' Cosa fare: questo file appartiene a un utente diverso da chi esegue il comando. Esegilo come quell’account, oppure indica il tuo archivio con --db=<percorso completo>.',
18
+ ru: ' Что делать: этот файл принадлежит другому пользователю, а не тому, кто запускает команду. Запустите её от того аккаунта или укажите свою базу через --db=<полный путь>.',
19
+ es: ' Qué hacer: este archivo pertenece a otro usuario, no al que ejecuta este comando. Ejecútalo con esa cuenta, o señala tu propio almacén con --db=<ruta completa>.',
20
+ }
21
+
22
+ /**
23
+ * 「读不到 = 库里没这个文件」的统计行(9 语)。跟 classifyOpenFailure 的 missing 档配对;
24
+ * 实测:首次使用前的空目录、自定义安装位置都会落在这里,归成 busy 就是误报。
25
+ */
26
+ /** @type {Record<string,string>} */
27
+ export const STAT_MISSING = {
28
+ zh: 'cookie 库不在这个位置(客户端从未起过、或装在了别处):{path}',
29
+ en: 'No cookie database at this location (the client never ran, or it lives elsewhere): {path}',
30
+ ja: 'この位置に cookie データベースがありません(クライアント未起動、か別の場所にあります):{path}',
31
+ ko: '이 위치에 cookie 데이터베이스가 없습니다(클라이언트를 실행한 적 없거나 다른 곳에 있습니다): {path}',
32
+ fr: 'Pas de base de cookies à cet emplacement (le client n’a jamais tourné, ou elle est ailleurs) : {path}',
33
+ de: 'Keine Cookie-Datenbank an diesem Ort (der Client lief nie, oder sie liegt woanders): {path}',
34
+ it: 'Nessun database dei cookie in questa posizione (il client non è mai partito, oppure sta altrove): {path}',
35
+ ru: 'Базы cookie в этом месте нет (клиент не запускался или хранится elsewhere): {path}',
36
+ es: 'No hay base de cookies en esta ubicación (el cliente nunca se ejecutó, o está en otro sitio): {path}',
37
+ }
38
+ // ru 文案里的英文残留清掉
39
+ STAT_MISSING.ru = STAT_MISSING.ru.replace('хранится elsewhere', 'лежит в другом месте')
@@ -0,0 +1,216 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 运行时文案字典(en / ja / ko / fr)。
3
+ *
4
+ * 键集必须与 `zh`(i18n.js 里的真理源)逐键相等:`registerDictionary` 会在装载时
5
+ * 机械核对缺键/多键并直接抛错,所以这里不做兜底、不加解释性键。
6
+ * 占位符名({path} / {count} …)原样保留,只调整语序。
7
+ */
8
+ import { registerDictionary } from './i18n.js'
9
+ import { ADVISE_OWNER, STAT_MISSING } from './locales-advise-owner.js'
10
+
11
+ registerDictionary('en', {
12
+ skipped: 'No cookie database located — if you are running the Web edition instead of the desktop client, the browser owns its own cookies and there is nothing for this tool to clean.',
13
+ skippedCandidates: 'Candidate paths:',
14
+ skippedHint: 'If you use the Web edition (browser talking to the host directly) there is no such file locally; for the desktop client point at it with userDataRoot or --db.',
15
+ busy: 'The cookie database is currently unreadable (the client is running and Chromium holds it exclusively): {path}',
16
+ busyWhy: 'A host plugin cannot clean this database while it runs — that is an operating-system file lock, not a limitation of this tool.',
17
+ permission: 'The cookie database cannot be read: insufficient permission (the file belongs to another user, or a flatpak/snap install keeps it outside the usual location): {path}',
18
+ permissionHint: 'What to do: confirm which user runs the command, or point at the database directly:',
19
+ dbRequired: '--db=<full path>',
20
+ exitWin: 'Quit the DSH client completely (tray icon → Exit, and make sure no DeepSeek Harness remains in the process list)',
21
+ exitMac: 'Quit the DSH client completely (Cmd+Q or the menu → Quit; an icon disappearing from the Dock is not enough — confirm no DeepSeek Harness remains in ps)',
22
+ exitLinux: 'Quit the DSH client completely (close the main window, then confirm no DeepSeek Harness / dsh-desktop process remains)',
23
+ dbLine: 'Cookie database: {path} ({bytes} B, {total} entries total)',
24
+ ok: 'Status: ok — no dsh-auth-* leftovers, nothing to clean.',
25
+ found: 'Status: found {count} dsh-auth-* entries (expired {expired} / still valid {live})',
26
+ span: 'Expiry window: {oldest} to {newest}',
27
+ hostLine: 'host_key distribution: ',
28
+ note: 'Note: dsh-auth-* names are hashed from host:port, so every port change leaves one entry, and unexpired ones linger until the 30-day term ends. They do not affect login (the main window uses in-memory credentials and auth only ever reads the entry matching the current port) and they do not involve account credentials, sessions or plugin config.',
29
+ nextStatus: 'Next: after you {exit}, run this in a terminal (add --dry-run to preview the count):',
30
+ nextClean: 'Cleanup command (make sure to {exit} first — it cannot run while the client is up):',
31
+ cleanFooter: ' The default tier removes every dsh-auth-* entry; --expired-only limits it to expired ones; a .bak copy is written before any change.',
32
+ statClean: 'Clean: {path} ({total} cookies, no dsh-auth-* leftovers)',
33
+ statBusy: 'Cannot read (the client is running and holds the database): {path}',
34
+ statMissing: STAT_MISSING['en'],
35
+ statPermission: 'No permission to read the cookie database (wrong directory ownership or the file is not yours): {path}',
36
+ statFound: 'Found {count} dsh-auth-* entries (expired {expired} / still valid {live}) across {hosts} host_key value(s), database size {bytes} B: {path}',
37
+ deleted: 'Deleted {count} dsh-auth-* entries ({scope})',
38
+ scopeAll: 'all',
39
+ scopeExpired: 'expired only',
40
+ dbSize: ' Database: {path} {before} B → {after} B',
41
+ backup: ' Backup: {backup}',
42
+ backupWith: ' (incl. {sidecars})',
43
+ backupSkipped: ' Backup: skipped via --no-backup',
44
+ backupWarn: ' Note: {sidecars} could not be copied (locked); the main database copy is still complete and this deletion is unaffected.',
45
+ untouched: ' Account credentials, sessions and plugin configuration were not touched; the local cookie is re-issued on next start.',
46
+ dryRun: '[dry-run] would delete {count} entries: {path}',
47
+ dryRunTail: 'Nothing was written. Drop --dry-run to actually do it.',
48
+ notFound: 'Cookie database not found. Candidate paths: {candidates} You can pass --db=<full path>.',
49
+ nextCliClean: 'Next: after you {exit}, run `dsh-cookie-cleaner --clean` (the default also removes unexpired entries; login is unaffected, see README).',
50
+ nextCliRerun: 'Next: after you {exit}, rerun this command.',
51
+ nextCliPermission: 'Next: confirm the user running this command owns the file, or point at your database with --db=<full path>.',
52
+ openFailed: 'Cannot open the cookie database: {path}',
53
+ reason: ' Reason: {reason}',
54
+ adviseBusy: ' What to do: Chromium holds this database while the client runs. Please {exit}, then rerun this command.',
55
+ adviseMissing: ' What to do: the file is not here — the path moved, the client never ran, or it was marked for deletion. Point at the real cookie store with --db=<full path>.',
56
+ advisePermission: ' What to do: this account cannot read the file (permissions or ownership). Make sure it belongs to the user running this command; flatpak/snap stores sit outside the usual path, so point at yours with --db=<full path>.',
57
+ adviseOwner: ADVISE_OWNER['en'],
58
+ missingFile: 'the file does not exist (or is marked for deletion)',
59
+ cleanFailed: 'Cleanup failed: ',
60
+ })
61
+
62
+ /** de/it/ru/es 单拆一文件(免单文件过大),装载时一并注册。 */
63
+ import './locales-dict2.js'
64
+
65
+ registerDictionary('ja', {
66
+ skipped: 'cookie データベースが見つかりません——デスクトップクライアントではなく Web 版をご利用の場合、cookie はブラウザー側が管理するため、本ツールが掃除するものではありません。',
67
+ skippedCandidates: '候補パス:',
68
+ skippedHint: 'Web 版(ブラウザーからホストへ直接接続)ではこのファイルは存在しません。デスクトップ版は userDataRoot または --db で指定してください。',
69
+ busy: 'cookie データベースを現在読み取れません(クライアント起動中で Chromium が独占しています):{path}',
70
+ busyWhy: 'ホストプラグインは実行中にこのデータベースを掃除できません——これは本ツールの制限ではなく OS のファイルロックです。',
71
+ permission: 'cookie データベースを読めません:権限不足(ファイルの所有者が違う、または flatpak/snap 版が通常以外の場所に置いています):{path}',
72
+ permissionHint: '対処:コマンドを実行するユーザーを確認するか、データベースを直接指定してください:',
73
+ dbRequired: '--db=<フルパス>',
74
+ exitWin: 'DSH クライアントを完全に終了(トレイアイコン → 終了、プロセス一覧に DeepSeek Harness が無いことを確認)',
75
+ exitMac: 'DSH クライアントを完全に終了(Cmd+Q またはメニュー → Quit;Dock のアイコンが消えるだけでは不十分、ps に DeepSeek Harness が無いことを確認)',
76
+ exitLinux: 'DSH クライアントを完全に終了(メインウィンドウを閉じ、プロセス一覧に DeepSeek Harness / dsh-desktop が無いことを確認)',
77
+ dbLine: 'cookie データベース:{path}({bytes} B、合計 {total} 件)',
78
+ ok: '状態:ok —— dsh-auth-* の残りはなく、掃除は不要です。',
79
+ found: '状態:dsh-auth-* を {count} 件発見(期限切れ {expired} / 有効 {live})',
80
+ span: '期限の範囲:{oldest} ~ {newest}',
81
+ hostLine: 'host_key 分布:',
82
+ note: '補足:dsh-auth-* の名前は host:port のハッシュで、ポートが変わるたびに 1 件残り、有効なものは 30 日期限まで残ります。ログインには影響しません(メインウィンドウはメモリ上の資格情報を使い、認証は現在のポートの 1 件しか読みません)。アカウント資格情報・セッション・プラグイン設定にも無関係です。',
83
+ nextStatus: '次:{exit}後、ターミナルで次を実行(先に件数だけ見るなら --dry-run を付記):',
84
+ nextClean: '掃除コマンド(必ず先に{exit}——起動中は実行できません):',
85
+ cleanFooter: ' 既定では dsh-auth-* を全消し、--expired-only は期限切れのみ。書き込み前に .bak を自動保存します。',
86
+ statClean: 'クリーン:{path}(cookie 合計 {total} 件、dsh-auth-* の残りはなし)',
87
+ statBusy: '読み取れません(クライアント起動中でデータベースが独占されています):{path}',
88
+ statMissing: STAT_MISSING['ja'],
89
+ statPermission: 'cookie データベースを読む権限がありません(場所が不適切、または所有者が違います):{path}',
90
+ statFound: 'dsh-auth-* を {count} 件発見(期限切れ {expired} / 有効 {live})、{hosts} 個の host_key、サイズ {bytes} B:{path}',
91
+ deleted: 'dsh-auth-* を {count} 件削除しました({scope})',
92
+ scopeAll: 'すべて',
93
+ scopeExpired: '期限切れのみ',
94
+ dbSize: ' データベース:{path} {before} B → {after} B',
95
+ backup: ' バックアップ:{backup}',
96
+ backupWith: '({sidecars} を含む)',
97
+ backupSkipped: ' バックアップ:--no-backup により省略',
98
+ backupWarn: ' 注意:{sidecars} はロックされてコピーできませんでしたが、本体の複製は完全で、今回の削除に影響はありません。',
99
+ untouched: ' アカウント資格情報・セッション・プラグイン設定には触れていません。ローカル cookie は次回起動時に再発行されます。',
100
+ dryRun: '[dry-run] {count} 件を削除する想定:{path}',
101
+ dryRunTail: '書き込んでいません。実行するには --dry-run を外してください。',
102
+ notFound: 'cookie データベースが見つかりません。候補パス:{candidates} --db=<フルパス> で指定できます。',
103
+ nextCliClean: '次:{exit}後に `dsh-cookie-cleaner --clean` を実行(既定は有効期限内も削除しますがログインに影響しません。README 参照)。',
104
+ nextCliRerun: '次:{exit}後にこのコマンドを再実行してください。',
105
+ nextCliPermission: '次:実行ユーザーがファイルの所有者か確認するか、--db=<フルパス> でデータベースを指定してください。',
106
+ openFailed: 'cookie データベースを開けません:{path}',
107
+ reason: ' 理由:{reason}',
108
+ adviseBusy: ' 対処:クライアント起動中は Chromium がこのデータベースを独占します。{exit}後に再実行してください。',
109
+ adviseMissing: ' 対処:このファイルは存在しません(パス変更、クライアント未起動、削除マークのいずれか)。--db=<フルパス> で実在するデータベースを指定してください。',
110
+ advisePermission: ' 対処:このユーザーではファイルを読めません(権限か所有の問題)。本コマンドの実行者のファイルか確認してください。flatpak/snap 版は通常の場所にないため --db=<フルパス> で指定します。',
111
+ adviseOwner: ADVISE_OWNER['ja'],
112
+ missingFile: 'ファイルが存在しない(または削除マーク済み)',
113
+ cleanFailed: '掃除に失敗:',
114
+ })
115
+
116
+ registerDictionary('ko', {
117
+ skipped: 'cookie 데이터베이스를 찾지 못했습니다 — 데스크톱 클라이언트가 아니라 Web 버전을 쓴다면 cookie는 브라우저가 관리하므로 이 도구가 정리할 것이 없습니다.',
118
+ skippedCandidates: '후보 경로:',
119
+ skippedHint: 'Web 버전(브라우저가 호스트에 직접 접속)에서는 이 파일이 없습니다. 데스크톱 버전은 userDataRoot 또는 --db로 지정하세요.',
120
+ busy: '지금 cookie 데이터베이스를 읽을 수 없습니다(클라이언트가 실행 중이며 Chromium이 독점): {path}',
121
+ busyWhy: '호스트 플러그인은 실행 중에 이 데이터베이스를 정리할 수 없습니다 — 이는 본 도구의 한계가 아니라 운영체제의 파일 잠금입니다.',
122
+ permission: 'cookie 데이터베이스를 읽을 수 없습니다: 권한 부족(파일 소유자가 다르거나 flatpak/snap 설치가 일반 위치에 있지 않음): {path}',
123
+ permissionHint: '조치: 어떤 사용자로 실행하는지 확인하거나 데이터베이스를 직접 지정하세요:',
124
+ dbRequired: '--db=<전체 경로>',
125
+ exitWin: 'DSH 클라이언트를 완전히 종료(트레이 아이콘 → 종료, 프로세스 목록에 DeepSeek Harness가 남지 않았는지 확인)',
126
+ exitMac: 'DSH 클라이언트를 완전히 종료(Cmd+Q 또는 메뉴 → Quit; Dock에서 아이콘이 사라지는 것으로는 부족하고, ps에 DeepSeek Harness가 없는지 확인)',
127
+ exitLinux: 'DSH 클라이언트를 완전히 종료(메인 창을 닫은 뒤 프로세스 목록에 DeepSeek Harness / dsh-desktop가 남지 않았는지 확인)',
128
+ dbLine: 'cookie 데이터베이스: {path} ({bytes} B, 전체 {total} 개)',
129
+ ok: '상태: ok — dsh-auth-* 잔여물이 없어 정리할 필요가 없습니다.',
130
+ found: '상태: dsh-auth-* {count} 개 발견(만료 {expired} / 유효 {live})',
131
+ span: '만료 범위: {oldest} ~ {newest}',
132
+ hostLine: 'host_key 분포: ',
133
+ note: '참고: dsh-auth-* 이름은 host:port 해시라 포트가 바뀔 때마다 하나 남고, 유효한 항목은 30일 만료까지 남아 있습니다. 로그인에 영향이 없습니다(메인 창은 메모리 자격 증명을 쓰고, 인증은 현재 포트에 해당하는 하나만 읽습니다). 계정 자격 증명/세션/플러그인 설정과도 무관합니다.',
134
+ nextStatus: '다음: {exit} 후 터미널에서 실행(몇 개 지울지 먼저 보려면 --dry-run 추가):',
135
+ nextClean: '정리 명령(반드시 먼저 {exit} — 클라이언트가 뜨는 동안에는 실행 불가):',
136
+ cleanFooter: ' 기본값은 dsh-auth-* 전체 삭제, --expired-only는 만료분만. 쓰기 전 .bak 사본을 자동 저장합니다.',
137
+ statClean: '깨끗함: {path} (cookie 전체 {total} 개, dsh-auth-* 잔여물 없음)',
138
+ statBusy: '읽을 수 없음(클라이언트 실행 중이며 데이터베이스가 독점됨): {path}',
139
+ statMissing: STAT_MISSING['ko'],
140
+ statPermission: 'cookie 데이터베이스를 읽을 권한이 없음(위치가 맞지 않거나 파일 소유자가 다름): {path}',
141
+ statFound: 'dsh-auth-* {count} 개 발견(만료 {expired} / 유효 {live}), host_key {hosts} 개, 크기 {bytes} B: {path}',
142
+ deleted: 'dsh-auth-* {count} 개 삭제({scope})',
143
+ scopeAll: '전체',
144
+ scopeExpired: '만료분만',
145
+ dbSize: ' 데이터베이스: {path} {before} B → {after} B',
146
+ backup: ' 백업: {backup}',
147
+ backupWith: ' ({sidecars} 포함)',
148
+ backupSkipped: ' 백업: --no-backup으로 생략',
149
+ backupWarn: ' 참고: {sidecars}는 잠겨 복사하지 못했지만 본문 사본은 완전하며 이번 삭제에 영향이 없습니다.',
150
+ untouched: ' 계정 자격 증명, 세션, 플러그인 설정은 건드리지 않았고, 로컬 cookie는 다음 시작 때 다시 발급됩니다.',
151
+ dryRun: '[dry-run] {count} 개 삭제 예정: {path}',
152
+ dryRunTail: '쓰지 않았습니다. 실행하려면 --dry-run을 빼세요.',
153
+ notFound: 'cookie 데이터베이스를 찾지 못했습니다. 후보 경로: {candidates} --db=<전체 경로>로 지정할 수 있습니다.',
154
+ nextCliClean: '다음: {exit} 후 `dsh-cookie-cleaner --clean` 실행(기본은 유효분도 삭제하지만 로그인에 영향 없음, README 참조).',
155
+ nextCliRerun: '다음: {exit} 후 이 명령을 다시 실행하세요.',
156
+ nextCliPermission: '다음: 실행 사용자가 파일 소유자인지 확인하거나 --db=<전체 경로>로 데이터베이스를 지정하세요.',
157
+ openFailed: 'cookie 데이터베이스를 열 수 없음: {path}',
158
+ reason: ' 원인: {reason}',
159
+ adviseBusy: ' 조치: 클라이언트 실행 중에는 Chromium이 이 데이터베이스를 독점합니다. {exit} 후 다시 실행하세요.',
160
+ adviseMissing: ' 조치: 이 파일이 존재하지 않습니다(경로 변경, 클라이언트 미실행, 삭제 표시 중 하나). --db=<전체 경로>로 실제 데이터베이스를 지정하세요.',
161
+ advisePermission: ' 조치: 이 사용자로는 파일을 읽을 수 없습니다(권한 또는 소유 문제). 본 명령을 실행하는 사용자의 파일인지 확인하세요. flatpak/snap 설치는 일반 경로 밖이므로 --db=<전체 경로>로 지정하십시오.',
162
+ adviseOwner: ADVISE_OWNER['ko'],
163
+ missingFile: '파일이 없음(또는 삭제 표시됨)',
164
+ cleanFailed: '정리 실패: ',
165
+ })
166
+
167
+ registerDictionary('fr', {
168
+ skipped: 'Aucune base de cookies trouvée — si vous utilisez la version Web plutôt que le client desktop, le navigateur gère ses propres cookies et cet outil n’a rien à nettoyer.',
169
+ skippedCandidates: 'Chemins candidats :',
170
+ skippedHint: 'En version Web (navigateur parlant directement à l’hôte), ce fichier n’existe pas ; côté desktop, indiquez-le via userDataRoot ou --db.',
171
+ busy: 'Base de cookies illisible pour le moment (le client tourne et Chromium la détient en exclusivité) : {path}',
172
+ busyWhy: 'Un plugin hôte ne peut pas nettoyer cette base pendant l’exécution — c’est un verrou du système d’exploitation, pas une limite de l’outil.',
173
+ permission: 'Lecture impossible : droits insuffisants (le fichier n’appartient pas à cet utilisateur, ou une installation flatpak/snap le place hors des chemins habituels) : {path}',
174
+ permissionHint: 'À faire : vérifiez quel utilisateur lance la commande, ou désignez la base directement :',
175
+ dbRequired: '--db=<chemin complet>',
176
+ exitWin: 'Quittez complètement le client DSH (icône de zone de notification → Quitter, et vérifiez qu’il ne reste aucun DeepSeek Harness dans la liste des processus)',
177
+ exitMac: 'Quittez complètement le client DSH (Cmd+Q ou menu → Quit ; voir l’icône disparaître du Dock ne suffit pas — vérifiez dans ps qu’aucun DeepSeek Harness ne subsiste)',
178
+ exitLinux: 'Quittez complètement le client DSH (fermez la fenêtre principale, puis vérifiez qu’il ne reste aucun processus DeepSeek Harness / dsh-desktop)',
179
+ dbLine: 'Base de cookies : {path} ({bytes} o, {total} entrées au total)',
180
+ ok: 'État : ok — aucun résidu dsh-auth-*, rien à nettoyer.',
181
+ found: 'État : {count} entrées dsh-auth-* trouvées (expirées {expired} / encore valides {live})',
182
+ span: 'Plage d’expiration : {oldest} à {newest}',
183
+ hostLine: 'Répartition par host_key : ',
184
+ note: 'Remarque : le nom des dsh-auth-* est un empreinte de host:port, donc chaque changement de port laisse une entrée, et les entrées valides restent jusqu’à la fin des 30 jours. Cela n’affecte pas la connexion (la fenêtre principale utilise des identifiants en mémoire et l’authentification ne lit que l’entrée du port courant) et ne touche ni identifiants de compte, ni sessions, ni configuration des plugins.',
185
+ nextStatus: 'Ensuite : après avoir {exit}, lancez ceci dans un terminal (ajoutez --dry-run pour prévisualiser le nombre) :',
186
+ nextClean: 'Commande de nettoyage (il faut d’abord {exit} — impossible pendant l’exécution) :',
187
+ cleanFooter: ' Par défaut toutes les dsh-auth-* sont supprimées ; --expired-only limite aux expirées ; une copie .bak est écrite avant toute modification.',
188
+ statClean: 'Propre : {path} ({total} cookies, aucun résidu dsh-auth-*)',
189
+ statBusy: 'Lecture impossible (le client tourne et détient la base) : {path}',
190
+ statMissing: STAT_MISSING['fr'],
191
+ statPermission: 'Droits insuffisants pour lire la base de cookies (mauvais emplacement ou fichier appartenant à un autre utilisateur) : {path}',
192
+ statFound: '{count} entrées dsh-auth-* trouvées (expirées {expired} / valides {live}) sur {hosts} host_key, taille {bytes} o : {path}',
193
+ deleted: '{count} entrées dsh-auth-* supprimées ({scope})',
194
+ scopeAll: 'toutes',
195
+ scopeExpired: 'expirées uniquement',
196
+ dbSize: ' Base : {path} {before} o → {after} o',
197
+ backup: ' Sauvegarde : {backup}',
198
+ backupWith: ' (dont {sidecars})',
199
+ backupSkipped: ' Sauvegarde : ignorée via --no-backup',
200
+ backupWarn: ' Attention : {sidecars} n’ont pas pu être copiés (verrouillés) ; la copie principale reste complète et cette suppression n’est pas affectée.',
201
+ untouched: ' Identifiants de compte, sessions et configuration des plugins n’ont pas été touchés ; le cookie local est réémis au démarrage suivant.',
202
+ dryRun: '[dry-run] supprimerait {count} entrées : {path}',
203
+ dryRunTail: 'Rien n’a été écrit. Retirez --dry-run pour exécuter.',
204
+ notFound: 'Base de cookies introuvable. Chemins candidats : {candidates} Vous pouvez passer --db=<chemin complet>.',
205
+ nextCliClean: 'Ensuite : après avoir {exit}, lancez `dsh-cookie-cleaner --clean` (par défaut les entrées valides partent aussi ; la connexion n’est pas affectée, voir le README).',
206
+ nextCliRerun: 'Ensuite : après avoir {exit}, relancez cette commande.',
207
+ nextCliPermission: 'Ensuite : vérifiez que l’utilisateur qui lance la commande possède le fichier, ou désignez la base avec --db=<chemin complet>.',
208
+ openFailed: 'Impossible d’ouvrir la base de cookies : {path}',
209
+ reason: ' Motif : {reason}',
210
+ adviseBusy: ' À faire : Chromium détient cette base pendant l’exécution du client. Veuillez {exit}, puis relancer cette commande.',
211
+ adviseMissing: ' À faire : ce fichier n’existe pas (chemin déplacé, client jamais lancé, ou marqué pour suppression). Désignez la vraie base avec --db=<chemin complet>.',
212
+ advisePermission: ' À faire : ce compte ne peut pas lire le fichier (droits ou propriété). Vérifiez qu’il appartient à l’utilisateur qui lance la commande ; les bases flatpak/snap sont hors des chemins habituels, indiquez la vôtre avec --db=<chemin complet>.',
213
+ adviseOwner: ADVISE_OWNER['fr'],
214
+ missingFile: 'le fichier n’existe pas (ou est marqué pour suppression)',
215
+ cleanFailed: 'Échec du nettoyage : ',
216
+ })
@@ -0,0 +1,210 @@
1
+ /**
2
+ * dsh-cookie-cleaner — 运行时文案字典(de / it / ru / es)。
3
+ * 键集与 `zh` 逐键一致,由 `registerDictionary` 在装载时机械核对。
4
+ */
5
+ import { registerDictionary } from './i18n.js'
6
+ import { ADVISE_OWNER, STAT_MISSING } from './locales-advise-owner.js'
7
+
8
+ registerDictionary('de', {
9
+ skipped: 'Keine Cookie-Datenbank gefunden — wenn Sie die Web-Ausgabe statt des Desktop-Clients nutzen, verwaltet der Browser seine Cookies selbst, und dieses Werkzeug hat nichts zu räumen.',
10
+ skippedCandidates: 'Kandidatenpfade:',
11
+ skippedHint: 'In der Web-Ausgabe (Browser spricht direkt mit dem Host) gibt es diese Datei nicht; beim Desktop-Client weisen Sie sie über userDataRoot oder --db aus.',
12
+ busy: 'Cookie-Datenbank derzeit nicht lesbar (der Client läuft und Chromium hält sie exklusiv): {path}',
13
+ busyWhy: 'Ein Host-Plugin kann diese Datenbank zur Laufzeit nicht räumen — das ist eine Betriebssperre, keine Grenze dieses Werkzeugs.',
14
+ permission: 'Lesen unmöglich: Rechte fehlen (die Datei gehört einem anderen Nutzer, oder eine flatpak/snap-Installation liegt abseits der üblichen Orte): {path}',
15
+ permissionHint: 'Vorgehen: prüfen Sie, welcher Nutzer den Befehl ausführt, oder zeigen Sie direkt auf die Datenbank:',
16
+ dbRequired: '--db=<vollständiger Pfad>',
17
+ exitWin: 'Beenden Sie den DSH-Client vollständig (Symbol in der Ablage → Beenden, und stellen Sie sicher, dass in der Prozessliste kein DeepSeek Harness mehr läuft)',
18
+ exitMac: 'Beenden Sie den DSH-Client vollständig (Cmd+Q oder Menü → Beenden; dass das Symbol aus dem Dock verschwindet, genügt nicht — prüfen Sie in ps, dass kein DeepSeek Harness mehr läuft)',
19
+ exitLinux: 'Beenden Sie den DSH-Client vollständig (Hauptfenster schließen und sicherstellen, dass kein DeepSeek Harness / dsh-desktop mehr läuft)',
20
+ dbLine: 'Cookie-Datenbank: {path} ({bytes} B, insgesamt {total} Einträge)',
21
+ ok: 'Zustand: ok — keine dsh-auth-* Reste, nichts zu räumen.',
22
+ found: 'Zustand: {count} dsh-auth-* Einträge gefunden (abgelaufen {expired} / gültig {live})',
23
+ span: 'Ablaufspanne: {oldest} bis {newest}',
24
+ hostLine: 'host_key-Verteilung: ',
25
+ note: 'Hinweis: Die Namen der dsh-auth-* werden aus host:port gehasht, jeder Portwechsel hinterlässt also einen Eintrag, und gültige bleiben bis zum Ablauf der 30 Tage. Sie beeinflussen den Login nicht (das Hauptfenster nutzt Credentials im Speicher, und die Prüfung liest nur den Eintrag des aktuellen Ports) und betreffen weder Konto-Credentials, Sitzungen noch Plugin-Konfiguration.',
26
+ nextStatus: 'Nächster Schritt: nachdem Sie {exit}, führen Sie dies im Terminal aus (--dry-run zeigt vorab die Anzahl):',
27
+ nextClean: 'Räum-Befehl (zuerst {exit} — zur Laufzeit unmöglich):',
28
+ cleanFooter: ' Standard löscht alle dsh-auth-*; --expired-only nur abgelaufene; vor jeder Änderung wird eine .bak-Kopie geschrieben.',
29
+ statClean: 'Sauber: {path} ({total} Cookies, keine dsh-auth-* Reste)',
30
+ statBusy: 'Nicht lesbar (Client läuft und hält die Datenbank): {path}',
31
+ statMissing: STAT_MISSING['de'],
32
+ statPermission: 'Keine Leserechte auf die Cookie-Datenbank (falscher Ort oder Datei gehört einem anderen Nutzer): {path}',
33
+ statFound: '{count} dsh-auth-* Einträge (abgelaufen {expired} / gültig {live}) über {hosts} host_key-Wert(e), Größe {bytes} B: {path}',
34
+ deleted: '{count} dsh-auth-* Einträge gelöscht ({scope})',
35
+ scopeAll: 'alle',
36
+ scopeExpired: 'nur abgelaufene',
37
+ dbSize: ' Datenbank: {path} {before} B → {after} B',
38
+ backup: ' Sicherung: {backup}',
39
+ backupWith: ' (inkl. {sidecars})',
40
+ backupSkipped: ' Sicherung: per --no-backup übersprungen',
41
+ backupWarn: ' Achtung: {sidecars} ließen sich nicht kopieren (gesperrt); die Hauptkopie ist vollständig, diese Löschung ist nicht betroffen.',
42
+ untouched: ' Konto-credentials, Sitzungen und Plugin-Konfiguration blieben unberührt; das lokale Cookie wird beim nächsten Start neu ausgestellt.',
43
+ dryRun: '[dry-run] würde {count} Einträge löschen: {path}',
44
+ dryRunTail: 'Es wurde nichts geschrieben. --dry-run weglassen, um wirklich auszuführen.',
45
+ notFound: 'Cookie-Datenbank nicht gefunden. Kandidatenpfade: {candidates} Mit --db=<vollständiger Pfad> lässt sie sich angeben.',
46
+ nextCliClean: 'Nächster Schritt: nach dem {exit} `dsh-cookie-cleaner --clean` ausführen (standardmäßig gehen auch gültige; der Login bleibt unberührt, siehe README).',
47
+ nextCliRerun: 'Nächster Schritt: nach dem {exit} diesen Befehl erneut ausführen.',
48
+ nextCliPermission: 'Nächster Schritt: prüfen Sie, ob der ausführende Nutzer die Datei besitzt, oder zeigen Sie mit --db=<vollständiger Pfad> auf Ihre Datenbank.',
49
+ openFailed: 'Cookie-Datenbank kann nicht geöffnet werden: {path}',
50
+ reason: ' Grund: {reason}',
51
+ adviseBusy: ' Vorgehen: Chromium hält diese Datenbank, solange der Client läuft. Bitte {exit} und dann erneut ausführen.',
52
+ adviseMissing: ' Vorgehen: diese Datei existiert nicht (Pfad verschoben, Client nie gestartet, oder zum Löschen markiert). Weisen Sie die echte Datenbank mit --db=<vollständiger Pfad> aus.',
53
+ advisePermission: ' Vorgehen: dieser Nutzer kann die Datei nicht lesen (Rechte oder Eigentümerschaft). Prüfen Sie, ob sie dem ausführenden Nutzer gehört; flatpak/snap-Datenbanken liegen außerhalb der üblichen Pfade, weisen Sie Ihre mit --db=<vollständiger Pfad> aus.',
54
+ adviseOwner: ADVISE_OWNER['de'],
55
+ missingFile: 'die Datei existiert nicht (oder ist zum Löschen markiert)',
56
+ cleanFailed: 'Räumung fehlgeschlagen: ',
57
+ })
58
+
59
+ registerDictionary('it', {
60
+ skipped: 'Nessun database dei cookie trovato — se usi la versione Web invece del client desktop, il browser gestisce i propri cookie e questo strumento non ha nulla da pulire.',
61
+ skippedCandidates: 'Percorsi candidati:',
62
+ skippedHint: 'Con la versione Web (browser che parla direttamente all’host) questo file non esiste; per il client desktop indicarlo con userDataRoot o --db.',
63
+ busy: 'Database dei cookie al momento illeggibile (il client è in esecuzione e Chromium lo trattiene in esclusiva): {path}',
64
+ busyWhy: 'Un plugin host non può pulire questo database mentre gira — è un blocco del sistema operativo, non un limite dello strumento.',
65
+ permission: 'Lettura impossibile: permessi insufficienti (il file appartiene a un altro utente, oppure un’installazione flatpak/snap lo mette fuori dai percorsi usuali): {path}',
66
+ permissionHint: 'Cosa fare: verifica quale utente esegue il comando, oppure indica direttamente il database:',
67
+ dbRequired: '--db=<percorso completo>',
68
+ exitWin: 'Esci completamente dal client DSH (icona nella barra di sistema → Esci, e assicurati che nell’elenco processi non resti alcun DeepSeek Harness)',
69
+ exitMac: 'Esci completamente dal client DSH (Cmd+Q o menu → Quit; che l’icona scompaia dal Dock non basta — verifica in ps che non resti DeepSeek Harness)',
70
+ exitLinux: 'Esci completamente dal client DSH (chiudi la finestra principale, poi verifica che non resti alcun processo DeepSeek Harness / dsh-desktop)',
71
+ dbLine: 'Database dei cookie: {path} ({bytes} B, {total} voci in totale)',
72
+ ok: 'Stato: ok — nessun residuo dsh-auth-*, niente da pulire.',
73
+ found: 'Stato: trovate {count} voci dsh-auth-* (scadute {expired} / ancora valide {live})',
74
+ span: 'Intervallo di scadenza: {oldest} – {newest}',
75
+ hostLine: 'Distribuzione host_key: ',
76
+ note: 'Nota: i nomi dsh-auth-* sono derivati da host:port con hash, quindi ogni cambio di porta lascia una voce, e quelle valide restano fino alla scadenza dei 30 giorni. Non influiscono sul login (la finestra principale usa credenziali in memoria e l’autenticazione legge solo la voce della porta corrente) e non riguardano credenziali account, sessioni o configurazione dei plugin.',
77
+ nextStatus: 'Poi: dopo aver {exit}, esegui questo in un terminale (aggiungi --dry-run per vedere quante ne cancellerebbe):',
78
+ nextClean: 'Comando di pulizia (prima {exit} — da in esecuzione non è possibile):',
79
+ cleanFooter: ' Il comportamento predefinito cancella tutte le dsh-auth-*; --expired-only solo le scadute; prima di scrivere viene salvata una copia .bak.',
80
+ statClean: 'Pulito: {path} ({total} cookie, nessun residuo dsh-auth-*)',
81
+ statBusy: 'Impossibile leggere (il client è in esecuzione e trattiene il database): {path}',
82
+ statMissing: STAT_MISSING['it'],
83
+ statPermission: 'Permesso negato sul database dei cookie (cartella sbagliata o file non di tua proprietà): {path}',
84
+ statFound: 'Trovate {count} voci dsh-auth-* (scadute {expired} / valide {live}) su {hosts} valori host_key, dimensione {bytes} B: {path}',
85
+ deleted: 'Cancellate {count} voci dsh-auth-* ({scope})',
86
+ scopeAll: 'tutte',
87
+ scopeExpired: 'solo scadute',
88
+ dbSize: ' Database: {path} {before} B → {after} B',
89
+ backup: ' Backup: {backup}',
90
+ backupWith: ' (inclusi {sidecars})',
91
+ backupSkipped: ' Backup: saltato con --no-backup',
92
+ backupWarn: ' Attenzione: {sidecars} non copiabili (bloccati); la copia principale resta completa e questa cancellazione non è influenzata.',
93
+ untouched: ' Credenziali account, sessioni e configurazione dei plugin non sono state toccate; il cookie locale viene riemesso al prossimo avvio.',
94
+ dryRun: '[dry-run] cancellerebbe {count} voci: {path}',
95
+ dryRunTail: 'Nulla scritto. Togli --dry-run per eseguire davvero.',
96
+ notFound: 'Database dei cookie non trovato. Percorsi candidati: {candidates} Puoi passarlo con --db=<percorso completo>.',
97
+ nextCliClean: 'Poi: dopo aver {exit}, esegui `dsh-cookie-cleaner --clean` (di default cancella anche le valide; il login non ne risente, vedi README).',
98
+ nextCliRerun: 'Poi: dopo aver {exit}, riesegui questo comando.',
99
+ nextCliPermission: 'Poi: verifica che l’utente che esegue il comando possieda il file, oppure indica il database con --db=<percorso completo>.',
100
+ openFailed: 'Impossibile aprire il database dei cookie: {path}',
101
+ reason: ' Motivo: {reason}',
102
+ adviseBusy: ' Cosa fare: Chromium trattiene questo database finché il client è in esecuzione. Prima di tutto: {exit}; poi riesegui questo comando.',
103
+ adviseMissing: ' Cosa fare: questo file non esiste (percorso spostato, client mai avviato, o marcato per la cancellazione). Indica l’archivio reale con --db=<percorso completo>.',
104
+ advisePermission: ' Cosa fare: questo utente non può leggere il file (permessi o proprietà). Verifica che appartenga all’utente che esegue il comando; gli archivi flatpak/snap sono fuori dai percorsi usuali, indica il tuo con --db=<percorso completo>.',
105
+ adviseOwner: ADVISE_OWNER['it'],
106
+ missingFile: 'il file non esiste (è marcato per la cancellazione)',
107
+ cleanFailed: 'Pulizia fallita: ',
108
+ })
109
+
110
+ registerDictionary('ru', {
111
+ skipped: 'База cookie не найдена — если вы используете веб-сборку вместо десктопного клиента, cookies принадлежат браузеру, и этой утилите нечего убирать.',
112
+ skippedCandidates: 'Возможные пути:',
113
+ skippedHint: 'В веб-сборке (браузер говорит с хостом напрямую) такого файла нет; для десктопа укажите его через userDataRoot или --db.',
114
+ busy: 'База cookie сейчас недоступна для чтения (клиент запущен, и Chromium удерживает её эксклюзивно): {path}',
115
+ busyWhy: 'Хост-плагин не может убирать эту базу во время работы — это блокировка операционной системы, а не ограничение утилиты.',
116
+ permission: 'Чтение невозможно: недостаточно прав (файлу принадлежит другой пользователь, либо flatpak/snap-сборка держит его не в обычном месте): {path}',
117
+ permissionHint: 'Что делать: проверьте, от имени какого пользователя запускается команда, или укажите базу напрямую:',
118
+ dbRequired: '--db=<полный путь>',
119
+ exitWin: 'Полностью выйдите из DSH-клиента (значок в трее → Выход, и убедитесь, что в списке процессов не осталось DeepSeek Harness)',
120
+ exitMac: 'Полностью выйдите из DSH-клиента (Cmd+Q или меню → Quit; что значок исчез из Dock — недостаточно, проверьте через ps, что DeepSeek Harness не остался)',
121
+ exitLinux: 'Полностью выйдите из DSH-клиента (закройте главное окно и убедитесь, что процессов DeepSeek Harness / dsh-desktop больше нет)',
122
+ dbLine: 'База cookie: {path} ({bytes} Б, всего {total} записей)',
123
+ ok: 'Состояние: ok — остатков dsh-auth-* нет, убирать нечего.',
124
+ found: 'Состояние: найдено {count} записей dsh-auth-* (просрочено {expired} / ещё действительно {live})',
125
+ span: 'Интервал истечения: {oldest} — {newest}',
126
+ hostLine: 'Распределение по host_key: ',
127
+ note: 'Пояснение: имена dsh-auth-* — это хеш от host:port, поэтому каждая смена порта оставляет запись, а действующие живут до истечения 30 дней. На вход это не влияет (главное окно использует полномочия в памяти, и проверка читает только запись текущего порта) и не касается полномочий аккаунта, сессий или конфигурации плагинов.',
128
+ nextStatus: 'Далее: после того как вы {exit}, выполните это в терминале (добавьте --dry-run, чтобы заранее увидеть количество):',
129
+ nextClean: 'Команда уборки (сначала обязательно {exit} — во время работы это невозможно):',
130
+ cleanFooter: ' По умолчанию удаляются все dsh-auth-*; --expired-only — только просроченные; перед записью автоматически создаётся копия .bak.',
131
+ statClean: 'Чисто: {path} (cookie всего {total}, остатков dsh-auth-* нет)',
132
+ statBusy: 'Не читается (клиент запущен и удерживает базу): {path}',
133
+ statMissing: STAT_MISSING['ru'],
134
+ statPermission: 'Нет прав на чтение базы cookie (неверное расположение или файл принадлежит другому пользователю): {path}',
135
+ statFound: 'Найдено {count} записей dsh-auth-* (просрочено {expired} / действительно {live}) на {hosts} знач. host_key, размер {bytes} Б: {path}',
136
+ deleted: 'Удалено {count} записей dsh-auth-* ({scope})',
137
+ scopeAll: 'все',
138
+ scopeExpired: 'только просроченные',
139
+ dbSize: ' База: {path} {before} Б → {after} Б',
140
+ backup: ' Резервная копия: {backup}',
141
+ backupWith: ' (включая {sidecars})',
142
+ backupSkipped: ' Резервная копия: пропущена из-за --no-backup',
143
+ backupWarn: ' Внимание: {sidecars} не скопированы (заблокированы); основная копия полна, и на это удаление не влияет.',
144
+ untouched: ' Полномочия аккаунта, сессии и конфигурация плагинов не затронуты; локальный cookie будет перевыдан при следующем запуске.',
145
+ dryRun: '[dry-run] будет удалено {count} записей: {path}',
146
+ dryRunTail: 'Ничего не записано. Уберите --dry-run, чтобы выполнить по-настоящему.',
147
+ notFound: 'База cookie не найдена. Возможные пути: {candidates} Можно указать её через --db=<полный путь>.',
148
+ nextCliClean: 'Далее: после того как вы {exit}, выполните `dsh-cookie-cleaner --clean` (по умолчанию удаляются и действующие; на вход не влияет, см. README).',
149
+ nextCliRerun: 'Далее: после того как вы {exit}, повторите эту команду.',
150
+ nextCliPermission: 'Далее: проверьте, что запускающий команду пользователь владеет файлом, или укажите базу через --db=<полный путь>.',
151
+ openFailed: 'Не удалось открыть базу cookie: {path}',
152
+ reason: ' Причина: {reason}',
153
+ adviseBusy: ' Что делать: Chromium удерживает эту базу, пока клиент запущен. Сначала: {exit}; затем повторите эту команду.',
154
+ adviseMissing: ' Что делать: этого файла нет (путь переехал, клиент не запускался, или он помечен к удалению). Укажите настоящую базу через --db=<полный путь>.',
155
+ advisePermission: ' Что делать: этот пользователь не может прочитать файл (права или владение). Убедитесь, что он принадлежит запускающему команду; базы flatpak/snap лежат вне обычных путей — укажите свою через --db=<полный путь>.',
156
+ adviseOwner: ADVISE_OWNER['ru'],
157
+ missingFile: 'файл не существует (или помечен к удалению)',
158
+ cleanFailed: 'Уборка не удалась: ',
159
+ })
160
+
161
+ registerDictionary('es', {
162
+ skipped: 'No se localizó la base de cookies — si usas la versión Web en lugar del cliente de escritorio, el navegador gestiona sus propias cookies y esta herramienta no tiene nada que limpiar.',
163
+ skippedCandidates: 'Rutas candidatas:',
164
+ skippedHint: 'En la versión Web (el navegador habla directo con el host) ese archivo no existe; en el cliente de escritorio indícalo con userDataRoot o --db.',
165
+ busy: 'La base de cookies no se puede leer ahora (el cliente está en ejecución y Chromium la sostiene en exclusiva): {path}',
166
+ busyWhy: 'Un plugin del host no puede limpiar esta base mientras corre — es un bloqueo del sistema operativo, no una limitación de esta herramienta.',
167
+ permission: 'Lectura imposible: permisos insuficientes (el archivo pertenece a otro usuario, o una instalación flatpak/snap lo coloca fuera de las rutas habituales): {path}',
168
+ permissionHint: 'Qué hacer: confirma qué usuario ejecuta el comando, o señala la base directamente:',
169
+ dbRequired: '--db=<ruta completa>',
170
+ exitWin: 'Sal por completo del cliente DSH (icono en la bandeja → Salir, y verifica que no quede ningún DeepSeek Harness en la lista de procesos)',
171
+ exitMac: 'Sal por completo del cliente DSH (Cmd+Q o menú → Quit; que el icono desaparezca del Dock no basta — verifica en ps que no quede DeepSeek Harness)',
172
+ exitLinux: 'Sal por completo del cliente DSH (cierra la ventana principal y verifica que no quede ningún proceso DeepSeek Harness / dsh-desktop)',
173
+ dbLine: 'Base de cookies: {path} ({bytes} B, {total} entradas en total)',
174
+ ok: 'Estado: ok — no quedan residuos dsh-auth-*, no hay nada que limpiar.',
175
+ found: 'Estado: se encontraron {count} entradas dsh-auth-* (vencidas {expired} / aún válidas {live})',
176
+ span: 'Ventana de vencimiento: {oldest} a {newest}',
177
+ hostLine: 'Distribución por host_key: ',
178
+ note: 'Nota: los nombres dsh-auth-* se derivan por hash de host:port, así que cada cambio de puerto deja una entrada, y las válidas permanecen hasta cumplir los 30 días. No afectan al inicio de sesión (la ventana principal usa credenciales en memoria y la autenticación solo lee la entrada del puerto actual) ni involucran credenciales de cuenta, sesiones ni configuración de plugins.',
179
+ nextStatus: 'Siguiente: tras {exit}, ejecuta esto en una terminal (añade --dry-run para ver cuántas borraría):',
180
+ nextClean: 'Comando de limpieza (primero {exit} — mientras corre no es posible):',
181
+ cleanFooter: ' De forma predeterminada borra todas las dsh-auth-*; --expired-only solo las vencidas; antes de escribir guarda una copia .bak.',
182
+ statClean: 'Limpio: {path} ({total} cookies, sin residuos dsh-auth-*)',
183
+ statBusy: 'No se puede leer (el cliente está en ejecución y sostiene la base): {path}',
184
+ statMissing: STAT_MISSING['es'],
185
+ statPermission: 'Sin permiso para leer la base de cookies (ruta incorrecta o el archivo no es tuyo): {path}',
186
+ statFound: 'Se encontraron {count} entradas dsh-auth-* (vencidas {expired} / válidas {live}) en {hosts} valor(es) host_key, tamaño {bytes} B: {path}',
187
+ deleted: 'Se borraron {count} entradas dsh-auth-* ({scope})',
188
+ scopeAll: 'todas',
189
+ scopeExpired: 'solo vencidas',
190
+ dbSize: ' Base: {path} {before} B → {after} B',
191
+ backup: ' Copia de seguridad: {backup}',
192
+ backupWith: ' (incluidos {sidecars})',
193
+ backupSkipped: ' Copia de seguridad: omitida con --no-backup',
194
+ backupWarn: ' Atención: {sidecars} no se pudieron copiar (bloqueados); la copia principal sigue completa y este borrado no se ve afectado.',
195
+ untouched: ' Credenciales de cuenta, sesiones y configuración de plugins no se tocaron; la cookie local se reemite en el próximo arranque.',
196
+ dryRun: '[dry-run] se borrarían {count} entradas: {path}',
197
+ dryRunTail: 'No se escribió nada. Quita --dry-run para ejecutar de verdad.',
198
+ notFound: 'No se encontró la base de cookies. Rutas candidatas: {candidates} Puedes indicar la tuya con --db=<ruta completa>.',
199
+ nextCliClean: 'Siguiente: tras {exit}, ejecuta `dsh-cookie-cleaner --clean` (por defecto también borra las válidas; el inicio de sesión no se resiente, mira el README).',
200
+ nextCliRerun: 'Siguiente: tras {exit}, vuelve a ejecutar este comando.',
201
+ nextCliPermission: 'Siguiente: confirma que el usuario que ejecuta el comando sea dueño del archivo, o señala tu base con --db=<ruta completa>.',
202
+ openFailed: 'No se puede abrir la base de cookies: {path}',
203
+ reason: ' Motivo: {reason}',
204
+ adviseBusy: ' Qué hacer: Chromium sostiene esta base mientras el cliente corre. Por favor {exit}, y vuelve a ejecutar este comando.',
205
+ adviseMissing: ' Qué hacer: este archivo no existe (ruta cambiada, cliente nunca iniciado, o marcado para borrado). Señala el almacén real con --db=<ruta completa>.',
206
+ advisePermission: ' Qué hacer: esta cuenta no puede leer el archivo (permisos o propiedad). Verifica que pertenezca al usuario que ejecuta el comando; los almacenes flatpak/snap están fuera de las rutas habituales, señala el tuyo con --db=<ruta completa>.',
207
+ adviseOwner: ADVISE_OWNER['es'],
208
+ missingFile: 'el archivo no existe (o está marcado para borrado)',
209
+ cleanFailed: 'Limpieza fallida: ',
210
+ })
package/src/report.js CHANGED
@@ -2,13 +2,16 @@
2
2
  * dsh-cookie-cleaner — 播报文案层(把处置说全,避免二次求助 AI)。
3
3
  *
4
4
  * core.js 只做机械动作,这里负责「现在是什么状况 + 下一步敲哪条命令」。
5
- * 命令文案按平台给出:脚本随包分发(npm bin `dsh-cookie-cleaner`),
6
- * 未全局安装时给出 `node <包>/src/cli.js` 的直跑形态。
5
+ * 全部文案经 i18n 字典出(9 语),路径/条数/命令保持原样不译;
6
+ * 命令文案给出两种形态:npm bin 别名不可用时用 `node <包>/src/cli.js` 直跑。
7
7
  */
8
8
  import path from 'node:path'
9
+ import process from 'node:process'
9
10
  import { fileURLToPath } from 'node:url'
10
11
 
11
12
  export * from './core.js'
13
+ import { activeLang, exitInstruction, setLang } from './core.js'
14
+ import { detectLang, translator } from './i18n.js'
12
15
 
13
16
  const HERE = path.dirname(fileURLToPath(import.meta.url))
14
17
 
@@ -17,53 +20,66 @@ export function directRunCommand() {
17
20
  return `node "${path.join(HERE, 'cli.js')}"`
18
21
  }
19
22
 
23
+ /** 按宿主/环境挑语言并激活;返回最终语言码。 */
24
+ export function useDetectedLang(explicit = '') {
25
+ const lang = explicit ? String(explicit).trim() : detectLang()
26
+ return setLang(lang)
27
+ }
28
+
20
29
  /**
21
30
  * 组装 `/cookie-cleaner` 的输出。
22
- * @param {object} stat statCookies 结果(可能是 busy/skipped 降级形态)
23
- * @param {{expiredOnly?:boolean, userDataRoot?:string, mode?:'status'|'clean'}} [cfg]
31
+ * @param {object} stat statCookies 结果(可能是 busy/permission/skipped 降级形态)
32
+ * @param {{expiredOnly?:boolean, userDataRoot?:string, mode?:'status'|'clean', platform?:string, lang?:string}} [cfg]
24
33
  */
25
34
  export function cookieCleanerCommandText(stat, cfg = {}) {
35
+ if (cfg.lang) setLang(cfg.lang)
36
+ const lang = cfg.lang ?? activeLang()
37
+ const t = translator(lang)
38
+ const platform = cfg.platform ?? process.platform
39
+ const exit = exitInstruction(platform, lang)
26
40
  const lines = []
27
41
  const mode = cfg.mode === 'clean' ? 'clean' : 'status'
28
42
 
29
43
  if (stat.verdict === 'skipped') {
30
- lines.push('cookie 库:未定位到。')
31
- lines.push(`候选路径:\n ${(stat.candidates ?? []).join('\n ')}`)
32
- lines.push('若你用的是 Web 版(浏览器直连宿主),本地没有这个库,无需清理;桌面版可用 userDataRoot 覆盖根目录。')
44
+ lines.push(t('skipped'))
45
+ lines.push(t('skippedCandidates') + '\n ' + (stat.candidates ?? []).join('\n '))
46
+ lines.push(t('skippedHint'))
47
+ return lines.join('\n')
48
+ }
49
+
50
+ if (stat.reason === 'permission') {
51
+ lines.push(t('permission', { path: stat.path }))
52
+ lines.push(t('permissionHint'))
53
+ lines.push(` ${directRunCommand()} --db="${stat.path ?? '<cookie db path>'}" --clean --dry-run`)
33
54
  return lines.join('\n')
34
55
  }
35
56
 
36
57
  if (stat.reason === 'busy') {
37
- lines.push(`cookie 库此刻读不到(客户端正在运行,被 Chromium 独占):${stat.path}`)
38
- lines.push('宿主插件无法在运行期清理这个库 —— 这是操作系统的文件占用,不是本工具的限制。')
39
- lines.push('处置:完全退出 DSH 客户端(托盘 → 退出,确认进程列表里已无 DeepSeek Harness)后,在终端执行:')
58
+ lines.push(t('busy', { path: stat.path }))
59
+ lines.push(t('busyWhy'))
60
+ lines.push(t('nextClean', { exit }))
40
61
  lines.push(` ${directRunCommand()} --clean`)
41
62
  return lines.join('\n')
42
63
  }
43
64
 
44
65
  if (stat.verdict === 'error') {
45
- lines.push(`cookie 库读取异常:${stat.message ?? '未知错误'}`)
66
+ lines.push(`${t('cleanFailed')}${stat.message ?? 'unknown'}`)
46
67
  return lines.join('\n')
47
68
  }
48
69
 
49
- lines.push(`cookie 库:${stat.path}(${stat.bytes} B,共 ${stat.totalCookies} 条)`)
70
+ lines.push(t('dbLine', { path: stat.path, bytes: stat.bytes, total: stat.totalCookies }))
50
71
  if (stat.verdict === 'ok') {
51
- lines.push('状态:ok —— 没有 dsh-auth-* 残留,无需清理。')
72
+ lines.push(t('ok'))
52
73
  return lines.join('\n')
53
74
  }
54
- lines.push(`状态:发现 ${stat.authCookies} 条 dsh-auth-*(已过期 ${stat.authExpired} / 未过期 ${stat.authLive})`)
55
- lines.push(`过期时间跨度:${stat.oldestExpiry} ~ ${stat.newestExpiry}`)
56
- lines.push('host_key 分布:' + stat.byHost.map((row) => `${row.hostKey}×${row.count}`).join(', '))
57
- lines.push('说明:dsh-auth-* 的名字按 host:port 哈希,每换一次端口就留一条,未过期的会一直躺到 30 天到期;'
58
- + '它们不影响登录(主窗口用内存态凭据、鉴权只认当前端口那一条),也不涉及账号凭据/会话/插件配置。')
75
+ lines.push(t('found', { count: stat.authCookies, expired: stat.authExpired, live: stat.authLive }))
76
+ lines.push(t('span', { oldest: stat.oldestExpiry, newest: stat.newestExpiry }))
77
+ lines.push(t('hostLine') + stat.byHost.map((row) => `${row.hostKey}×${row.count}`).join(', '))
78
+ lines.push(t('note'))
59
79
 
60
80
  const flag = cfg.expiredOnly === true ? ' --expired-only' : ''
61
- if (mode === 'status') {
62
- lines.push('下一步:完全退出 DSH 客户端后,在终端执行(先看会删几条可加 --dry-run):')
63
- } else {
64
- lines.push('清理命令(务必先完全退出 DSH 客户端,运行期做不到):')
65
- }
81
+ lines.push(mode === 'status' ? t('nextStatus', { exit }) : t('nextClean', { exit }))
66
82
  lines.push(` ${directRunCommand()} --clean${flag}`)
67
- lines.push(' 默认档删全部 dsh-auth-*;--expired-only 只删已过期的;写盘前自动留 .bak 副本。')
83
+ lines.push(t('cleanFooter'))
68
84
  return lines.join('\n')
69
85
  }