Repository navigation
Expand file tree
/
Copy pathpatch-core.js
More file actions
313 lines (283 loc) · 15.1 KB
/
Copy pathpatch-core.js
File metadata and controls
313 lines (283 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// patch-core.js — MiniMax Code Russian Patcher
// by Leostrange
const path = require('path');
const fs = require('fs');
const os = require('os');
const vm = require('vm');
const asar = require('@electron/asar');
function yieldToMain() { return new Promise(resolve => setImmediate(resolve)); }
function candidateRoots() {
const env = process.env;
const local = env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
return [path.join(local, 'Programs'), path.join(env.ProgramFiles || 'C:\\Program Files'), path.join(env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'), local].map(base => path.join(base, 'MiniMax Code'));
}
function isMiniMaxRoot(dir) {
const prev = process.noAsar; process.noAsar = true;
try { return fs.existsSync(path.join(dir, 'resources', 'app.asar')); }
catch { return false; }
finally { process.noAsar = prev; }
}
function detectMiniMaxDir() { for (const root of candidateRoots()) { if (isMiniMaxRoot(root)) return root; } return null; }
function resolveMiniMaxRoot(input) {
if (!input) return null;
let p = String(input).trim().replace(/^"+|"+$/g, '');
if (!p) return null;
p = path.normalize(p);
if (/app\.asar$/i.test(p)) { const root = path.dirname(path.dirname(p)); if (isMiniMaxRoot(root)) return root; }
if (isMiniMaxRoot(p)) return p;
return p;
}
function checkMiniMax(input) {
const prev = process.noAsar; process.noAsar = true;
try {
const root = resolveMiniMaxRoot(input);
const asarPath = root ? path.join(root, 'resources', 'app.asar') : null;
const backupPath = asarPath ? asarPath + '.ru-backup' : null;
return { root, path: asarPath, backupPath, exists: asarPath ? fs.existsSync(asarPath) : false, hasBackup: backupPath ? fs.existsSync(backupPath) : false };
} finally { process.noAsar = prev; }
}
function findJsonParse(source, startPos) {
const marker = "JSON.parse('";
const idx = source.indexOf(marker, startPos);
if (idx < 0) return null;
const jsonStart = idx + marker.length;
let i = jsonStart, escaped = false;
while (i < source.length) {
if (escaped) { escaped = false; i++; continue; }
if (source[i] === '\\') { escaped = true; i++; continue; }
if (source[i] === "'" && source[i+1] === ')') break;
i++;
}
try { const obj = vm.runInNewContext(source.substring(idx, i + 2)); return { obj, jsonStart, jsonEnd: i }; }
catch { return null; }
}
function countStringValues(obj) {
let c = 0;
for (const v of Object.values(obj)) { if (typeof v === 'string') c++; else if (typeof v === 'object' && v !== null) c += countStringValues(v); }
return c;
}
function hasChineseValues(obj) {
for (const v of Object.values(obj)) {
if (typeof v === 'string' && /[\u4e00-\u9fff]/.test(v)) return true;
if (typeof v === 'object' && v !== null && hasChineseValues(v)) return true;
}
return false;
}
function replaceChineseWithRussian(obj, ruDict, prefix) {
const result = {};
for (const [k, v] of Object.entries(obj)) {
const fullKey = prefix ? prefix + '.' + k : k;
if (typeof v === 'string') result[k] = ruDict[fullKey] !== undefined ? ruDict[fullKey] : v;
else if (typeof v === 'object' && v !== null) result[k] = replaceChineseWithRussian(v, ruDict, fullKey);
else result[k] = v;
}
return result;
}
function replaceDictInFile(filePath, ruDict) {
let source = fs.readFileSync(filePath, 'utf-8');
const before = source;
let replacements = 0;
let searchFrom = 0;
while (searchFrom < source.length) {
const found = findJsonParse(source, searchFrom);
if (!found) break;
const { obj, jsonStart, jsonEnd } = found;
if (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) {
const strVals = countStringValues(obj);
const hasChinese = hasChineseValues(obj);
if (strVals >= 10 && hasChinese) {
const newObj = replaceChineseWithRussian(obj, ruDict, '');
let newJson = JSON.stringify(newObj);
newJson = newJson.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
source = source.substring(0, jsonStart) + newJson + source.substring(jsonEnd);
replacements++;
}
}
searchFrom = jsonEnd + 2;
}
if (source !== before) fs.writeFileSync(filePath, source, 'utf-8');
return replacements;
}
function getMenuPatches() {
return [
[/isEnLanguage\s*\?\s*'Mini Chat'\s*:\s*'打开小窗'/g, "isEnLanguage ? 'Мини-чат' : 'Мини-чат'"],
[/isEnLanguage\s*\?\s*'Quit'\s*:\s*'退出'/g, "isEnLanguage ? 'Выход' : 'Выход'"],
[/isEn\s*\?\s*'Check for Updates\.\.'\s*:\s*'[^']*'/g, "isEn ? 'Проверить обновления...' : 'Проверить обновления...'"],
[/isEn\s*\?\s*'Contribute'\s*:\s*'[^']*'/g, "isEn ? 'Внести вклад' : 'Внести вклад'"],
[/isEn\s*\?\s*'Docs'\s*:\s*'[^']*'/g, "isEn ? 'Документация' : 'Документация'"],
[/isEn\s*\?\s*'Feedback'\s*:\s*'[^']*'/g, "isEn ? 'Обратная связь' : 'Обратная связь'"],
[/isEn\s*\?\s*'Open Logs'\s*:\s*'[^']*'/g, "isEn ? 'Открыть логи' : 'Открыть логи'"],
[/isEn\s*\?\s*'About \$\{constants_1\.DISPLAY_NAME\}'\s*:\s*'[^']*'/g, "isEn ? `О ${constants_1.DISPLAY_NAME}` : `О ${constants_1.DISPLAY_NAME}`"],
[/isEn\s*\?\s*'Hide'\s*:\s*'[^']*'/g, "isEn ? 'Скрыть' : 'Скрыть'"],
[/isEn\s*\?\s*'Hide Others'\s*:\s*'[^']*'/g, "isEn ? 'Скрыть остальные' : 'Скрыть остальные'"],
[/isEn\s*\?\s*'Unhide'\s*:\s*'[^']*'/g, "isEn ? 'Показать все' : 'Показать все'"],
[/isEn\s*\?\s*'Quit'\s*:\s*'[^']*'/g, "isEn ? 'Выход' : 'Выход'"],
[/isEn\s*\?\s*'Edit'\s*:\s*'[^']*'/g, "isEn ? 'Правка' : 'Правка'"],
[/isEn\s*\?\s*'Undo'\s*:\s*'[^']*'/g, "isEn ? 'Отменить' : 'Отменить'"],
[/isEn\s*\?\s*'Redo'\s*:\s*'[^']*'/g, "isEn ? 'Повторить' : 'Повторить'"],
[/isEn\s*\?\s*'Cut'\s*:\s*'[^']*'/g, "isEn ? 'Вырезать' : 'Вырезать'"],
[/isEn\s*\?\s*'Copy'\s*:\s*'[^']*'/g, "isEn ? 'Копировать' : 'Копировать'"],
[/isEn\s*\?\s*'Paste'\s*:\s*'[^']*'/g, "isEn ? 'Вставить' : 'Вставить'"],
[/isEn\s*\?\s*'Select All'\s*:\s*'[^']*'/g, "isEn ? 'Выделить всё' : 'Выделить всё'"],
[/isEn\s*\?\s*'View'\s*:\s*'[^']*'/g, "isEn ? 'Вид' : 'Вид'"],
[/isEn\s*\?\s*'Zoom In'\s*:\s*'[^']*'/g, "isEn ? 'Приблизить' : 'Приблизить'"],
[/isEn\s*\?\s*'Zoom Out'\s*:\s*'[^']*'/g, "isEn ? 'Отдалить' : 'Отдалить'"],
[/isEn\s*\?\s*'Actual Size'\s*:\s*'[^']*'/g, "isEn ? 'Размер по умолчанию' : 'Размер по умолчанию'"],
[/isEn\s*\?\s*'Window'\s*:\s*'[^']*'/g, "isEn ? 'Окно' : 'Окно'"],
[/isEn\s*\?\s*'Minimize'\s*:\s*'[^']*'/g, "isEn ? 'Свернуть' : 'Свернуть'"],
[/isEn\s*\?\s*'Close'\s*:\s*'[^']*'/g, "isEn ? 'Закрыть' : 'Закрыть'"],
[/isEn\s*\?\s*'Help'\s*:\s*'[^']*'/g, "isEn ? 'Справка' : 'Справка'"],
[/isEn\s*\?\s*'Settings'\s*:\s*'[^']*'/g, "isEn ? 'Настройки' : 'Настройки'"],
[/isEn\s*\?\s*'File'\s*:\s*'[^']*'/g, "isEn ? 'Файл' : 'Файл'"],
[/isEn\s*\?\s*'New Chat'\s*:\s*'[^']*'/g, "isEn ? 'Новый чат' : 'Новый чат'"],
[/isEn\s*\?\s*'New Mini Chat'\s*:\s*'[^']*'/g, "isEn ? 'Новый мини-чат' : 'Новый мини-чат'"],
[/isEn\s*\?\s*'New Tab'\s*:\s*'[^']*'/g, "isEn ? 'Новая вкладка' : 'Новая вкладка'"],
[/isEn\s*\?\s*'Close Tab'\s*:\s*'[^']*'/g, "isEn ? 'Закрыть вкладку' : 'Закрыть вкладку'"],
[/isEn\s*\?\s*'Delete'\s*:\s*'[^']*'/g, "isEn ? 'Удалить' : 'Удалить'"],
[/isEn\s*\?\s*'Toggle Fullscreen'\s*:\s*'[^']*'/g, "isEn ? 'Полноэкранный режим' : 'Полноэкранный режим'"],
[/isEn\s*\?\s*'Reload'\s*:\s*'[^']*'/g, "isEn ? 'Перезагрузить' : 'Перезагрузить'"],
];
}
async function patch(dir, options = {}) {
const { asarSource, onProgress } = options;
const log = [];
const push = (type, msg) => { log.push({ type, msg }); if (onProgress) onProgress(msg); };
let tempDir;
push('info', 'MiniMax Code Russian Patcher by Leostrange');
push('info', '');
push('info', '📍 Шаг 1/5: Поиск MiniMax Code...');
const root = dir || detectMiniMaxDir();
if (!root) throw new Error('MiniMax Code не найден.');
push('ok', ' Найден: ' + root);
let ruDict;
try {
const dictPath = path.join(__dirname, 'ru-RU.json');
if (fs.existsSync(dictPath)) {
ruDict = JSON.parse(fs.readFileSync(dictPath, 'utf-8'));
push('ok', ' Словарь: ' + Object.keys(ruDict).length + ' ключей');
} else { throw new Error('ru-RU.json not found'); }
} catch (e) { throw new Error('Словарь ru-RU.json не найден: ' + e.message); }
const prevNoAsar = process.noAsar;
process.noAsar = true;
try {
const asarPath = asarSource || path.join(root, 'resources', 'app.asar');
const backupPath = asarPath + '.ru-backup';
if (!fs.existsSync(asarPath)) throw new Error('app.asar не найден.');
push('info', '');
push('info', '💾 Шаг 2/5: Резервная копия...');
if (!fs.existsSync(backupPath)) { fs.copyFileSync(asarPath, backupPath); push('ok', ' Создана.'); }
else { push('ok', ' Уже существует.'); }
push('info', '');
push('info', '📦 Шаг 3/5: Извлечение app.asar...');
tempDir = path.join(path.dirname(asarPath), '_temp_mm_ru_patch');
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
fs.mkdirSync(tempDir, { recursive: true });
// Extract all files individually (avoids unpacked-file errors from extractAll)
const fileList = asar.listPackage(asarPath);
let extracted = 0;
let skipped = 0;
for (const rawPath of fileList) {
// On Windows listPackage() returns archive paths such as "\\dist\\main\\index.js".
// extractFile() expects a relative archive path, but the output location
// must also be kept relative to the temporary directory.
const relPath = rawPath.replace(/^[\\/]+/, '');
if (!relPath) continue;
let entry;
try { entry = asar.statFile(asarPath, relPath); } catch { skipped++; continue; }
if (!entry || !Number.isFinite(entry.size)) { skipped++; continue; }
const destPath = path.resolve(tempDir, relPath);
if (!destPath.startsWith(tempDir + path.sep)) {
skipped++;
continue;
}
try {
const buf = asar.extractFile(asarPath, relPath);
fs.mkdirSync(path.dirname(destPath), { recursive: true });
fs.writeFileSync(destPath, buf);
extracted++;
} catch {
skipped++;
}
}
await yieldToMain();
push('ok', ' Извлечено файлов: ' + extracted + (skipped ? ' (пропущено каталогов: ' + skipped + ')' : ''));
if (extracted < 1000) throw new Error('Извлечено слишком мало файлов (' + extracted + '). Исходный app.asar не изменён.');
push('info', '');
push('info', '🔧 Шаг 4/5: Замена словарей и меню...');
await yieldToMain();
const chunksDir = path.join(tempDir, 'out', '_next', 'static', 'chunks');
if (!fs.existsSync(chunksDir)) throw new Error('Каталог chunks не найден: ' + chunksDir);
const filesToPatch = [];
const collect = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { const f = path.join(d, e.name); if (e.isDirectory()) collect(f); else if (e.isFile() && e.name.endsWith('.js')) filesToPatch.push(f); } };
collect(chunksDir);
let dictReplaced = 0;
for (const file of filesToPatch) {
const count = replaceDictInFile(file, ruDict);
if (count > 0) { dictReplaced += count; push('ok', ' ✅ ' + path.basename(file) + ': ' + count); }
}
await yieldToMain();
if (dictReplaced === 0) push('warn', ' ⚠️ Словари не найдены');
else push('ok', ' Заменено: ' + dictReplaced);
// Menu patches
const menuPatches = getMenuPatches();
let menuPatched = 0, menuReps = 0;
const distDir = path.join(tempDir, 'dist');
if (fs.existsSync(distDir)) {
const walk = (d) => {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const full = path.join(d, e.name);
if (e.isDirectory()) walk(full);
else if (e.name.endsWith('.js')) {
let content = fs.readFileSync(full, 'utf-8');
let changed = false, reps = 0;
for (const [pat, rep] of menuPatches) { const b = content; content = content.replace(pat, rep); if (content !== b) { changed = true; reps++; } }
if (changed) { fs.writeFileSync(full, content, 'utf-8'); menuPatched++; menuReps += reps; }
}
}
};
walk(distDir);
}
push('ok', ' Меню: ' + menuPatched + ' файлов, ' + menuReps + ' замен');
push('info', '');
push('info', '📦 Шаг 5/5: Пересборка app.asar...');
await yieldToMain();
const newAsarPath = asarPath + '.ru-new';
try { fs.rmSync(newAsarPath, { force: true }); } catch {}
await asar.createPackage(tempDir, newAsarPath);
if (!fs.existsSync(newAsarPath) || fs.statSync(newAsarPath).size < fs.statSync(asarPath).size * 0.85) {
throw new Error('Пересобранный app.asar слишком мал. Исходный файл не изменён.');
}
fs.rmSync(asarPath, { force: true });
fs.renameSync(newAsarPath, asarPath);
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
push('ok', ' Готово.');
push('info', '');
push('success', '🎉 Русская локализация установлена!');
push('info', ' Перезапустите MiniMax Code.');
return { success: true, log, replacements: dictReplaced + menuReps };
} catch (e) {
push('error', e.message);
if (tempDir) { try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {} }
return { success: false, log, error: e.message };
} finally { process.noAsar = prevNoAsar; }
}
function restore(dir) {
const log = [];
const push = (type, msg) => log.push({ type, msg });
push('info', '🔄 Откат...');
const root = dir || detectMiniMaxDir();
if (!root) throw new Error('MiniMax Code не найден.');
const prevNoAsar = process.noAsar; process.noAsar = true;
try {
const asarPath = path.join(root, 'resources', 'app.asar');
const backupPath = asarPath + '.ru-backup';
if (!fs.existsSync(backupPath)) throw new Error('Резервная копия не найдена.');
if (fs.existsSync(asarPath)) fs.unlinkSync(asarPath);
fs.copyFileSync(backupPath, asarPath);
fs.unlinkSync(backupPath);
push('success', '✅ Откат завершён. Перезапустите MiniMax Code.');
return { success: true, log };
} catch (e) { push('error', e.message); return { success: false, log }; }
finally { process.noAsar = prevNoAsar; }
}
module.exports = { patch, restore, detectMiniMaxDir, checkMiniMax, candidateRoots };