-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrescue_codebase.js
More file actions
324 lines (275 loc) · 13.2 KB
/
rescue_codebase.js
File metadata and controls
324 lines (275 loc) · 13.2 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
314
315
316
317
318
319
320
321
322
323
324
const fs = require('fs');
const path = require('path');
const glob = require('glob'); // Assume simple Glob or use recursive file walker
const contextPath = path.join(__dirname, '..', 'src', 'contexts', 'LanguageContext.tsx');
const srcDir = path.join(__dirname, '..', 'src');
function getAllFiles(dirPath, arrayOfFiles) {
const files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function (file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
} else {
if (file.endsWith('.tsx') || file.endsWith('.ts')) {
arrayOfFiles.push(path.join(dirPath, "/", file));
}
}
});
return arrayOfFiles;
}
try {
const contextContent = fs.readFileSync(contextPath, 'utf8');
const lines = contextContent.split('\n');
// We need to parse keys and values, handling invalid multi-line strings
const garbageKeys = new Map(); // Key -> Original Value
let currentKey = null;
let currentValue = '';
let isMultiLine = false;
// Regex for start of key: 'key': 'value...
const keyStartRegex = /^\s*['"]([a-zA-Z0-9_.-]+)['"]:\s*['"](.*)/;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!isMultiLine) {
const match = line.match(keyStartRegex);
if (match) {
const key = match[1];
let rest = match[2];
// Check if it ends on same line
// Handle escaped quotes \'
// Count unescaped quotes
// If odd number of quotes at the end? (We started with one quote)
// Actually `rest` starts after the opening quote.
// We look for closing quote `'` or `',`
// Check if rest ends with `',` or `'`
if (rest.trim().endsWith("',") || (rest.trim().endsWith("'") && !rest.trim().endsWith("\\'"))) {
// Single line value
// Remove trailing comma/quote
let val = rest.trim();
if (val.endsWith("',")) val = val.slice(0, -2);
else if (val.endsWith("'")) val = val.slice(0, -1);
// Check if garbage
if (isGarbage(val)) {
garbageKeys.set(key, val);
}
} else {
// Multi-line start
currentKey = key;
currentValue = rest + '\n'; // Add newline that was stripped by split
isMultiLine = true;
}
}
} else {
// Continuation of multi-line
// Check for closing quote
// It might be on a line by itself or at end of text
if (line.trim().endsWith("',") || (line.trim().endsWith("'") && !line.trim().endsWith("\\'"))) {
let val = line.trim();
let literalPart = line; // preserve indentation for value?
// split removes newline, so we add it back if not last line?
if (val.endsWith("',")) literalPart = literalPart.substring(0, literalPart.lastIndexOf("',"));
else if (val.endsWith("'")) literalPart = literalPart.substring(0, literalPart.lastIndexOf("'"));
currentValue += literalPart;
isMultiLine = false;
if (isGarbage(currentValue)) {
garbageKeys.set(currentKey, currentValue);
}
currentKey = null;
currentValue = '';
} else {
currentValue += line + '\n';
}
}
}
console.log(`Found ${garbageKeys.size} garbage keys.`);
if (garbageKeys.size === 0) {
console.log("No garbage keys found. Exiting.");
return;
}
// List of files to scan
const files = getAllFiles(srcDir);
let restoredCount = 0;
// Process files
files.forEach(filePath => {
// Optimization: Skip context file
if (filePath.includes('LanguageContext')) return;
let content = fs.readFileSync(filePath, 'utf8');
let originalContent = content;
// Naive search for each key? Expensive (400 files * N keys).
// Better: Scan file for `t('key')` tokens, exclude good keys.
// Regex for `t('key')`
const tUsageRegex = /t\(['"]([a-zA-Z0-9_.-]+)['"]\)/g;
let match;
const matches = [];
while ((match = tUsageRegex.exec(content)) !== null) {
matches.push({ full: match[0], key: match[1], index: match.index });
}
// Iterate matches in reverse order to replace safely
for (let i = matches.length - 1; i >= 0; i--) {
const m = matches[i];
if (garbageKeys.has(m.key)) {
let originalCode = garbageKeys.get(m.key);
// Unescape quotes
originalCode = originalCode.replace(/\\'/g, "'");
// Fix JSX context
// If pattern is `>{t('key')}<`, replace `t('key')` matches code. `>{code}<`
// But if code was `) : (`, then `>{) : (}<` is invalid JSX usually,
// UNLESS it was `>{t('key')}<` and we replace with `} ) : ( {` ??
// Wait.
// If original was `) : (`, and I replaced it with `>{t('key')}<`
// Then simply putting `) : (` back generates `> ) : ( <` which is text content ' ) : ( '.
// BUT `) : (` usually implies TERNARY structure in code, not text.
// Original: `condition ? (A) : (B)`
// I matched ` : ` as text between `)` and `(`?
// No, I match `>...<`.
// Ternary: `<div> { cond ? ( <p>A</p> ) : ( <p>B</p> ) } </div>`
// If I have `) : (` as text?
// Ah, maybe usage was `<Comp prop={cond ? 'A' : 'B'} />`
// My script handled ternaries too. `'A' -> t('key')`
// If regex matched `) : (` inside `>`...`<`?
// Maybe: `<div>{cond ? (A) : (B)}</div>`
// `> {cond ? (A) : (B)} <`
// Text matching `>...<` usually ignores `{}`? No.
// `>([^<{]+)<`.
// `{}` are not `<`.
// so `{cond ? (A) : (B)}` matches `>...<`!
// And if I extracted it and put it in a key...
// Then I replaced `{cond ? (A) : (B)}` with `{t('key')}` (if inside JSX text).
// So `<div>{t('key')}</div>`.
// Value of key is `{cond ? (A) : (B)}`.
// If I restore it: `<div>{cond ? (A) : (B)}</div>`.
// This is correct!
// However, I need to strip the wrapping `{t('...')}` if I am inside JSX text block `{...}` container?
// My script usually output `>{t('key')}<`.
// If source has `>{t('key')}<` and I restore value `CODE`, result `>CODE<`.
// `>{cond ? A : B}<` -> invalid syntax if CODE contains `{}`?
// No, `>{...}<` is valid.
// But wait, `> { cond ... } <`
// If code starts with `{`, then `>>{...}<` -> `>{...}<`?
// My scanner matched `> TEXT <`.
// If text was `{...}`, I replaced it with `{t(key)}`.
// `>{t(key)}<`.
// Restoration: `>{...}<`. Valid.
// Only issue is if I added extra braces.
// `>Text<` -> `>{t(key)}<`.
// If Text was `) : (`, then `>{t(key)}<`.
// Restoration `>) : (<`.
// This renders text string `) : (`.
// It doesn't execute ternary.
// UNLESS original was NOT `>{...}<` but just logic flow.
// `apply_missing_translations.js`:
// `>([^<{]+)<`
// It only touches things between `>` and `<`.
// If code was `return ( <div> { cond ? (A) : (B) } </div> )`
// JSX Text is ` { cond ? (A) : (B) } `.
// My script thinks this is text.
// Replaces with ` {t(key)} `.
// `return ( <div> {t(key)} </div> )`.
// If key value is ` { cond ? (A) : (B) } `.
// Then `t()` returns string "{ cond ? (A) : (B) }".
// UI shows string.
// I need to RESTORE the code to be executed, not stringified.
// So I must remove `t('key')` wrappers?
// Or rather replace `t('key')` with the raw CODE.
// `<div>{t('key')}</div>` -> `<div>CODE</div>`.
// If CODE is `{ cond ? A : B }`.
// `<div>{ cond ? A : B }</div>`.
// This works!
// BUT `t('key')` call itself is JS code.
// Usage: `... {t('key')} ...`
// Replacement: `... CODE ...`
// If usage was `>{t('key')}<`.
// Replacement: `>CODE<`.
// If CODE is `{...}`, result `>{...}<`. Correct.
// What if improper replacement happened?
// `attr={t('key')}`.
// Replacement: `attr=CODE`.
// If CODE is `cond ? 'A' : 'B'`.
// `attr=cond ? 'A' : 'B'`. INVALID syntax (need braces).
// My script put `{}` around `t(key)`. `attr={t('key')}`.
// If I replace `t('key')` with `CODE`.
// `attr={CODE}`.
// `attr={cond ? 'A' : 'B'}`. Valid!
// So, blindly replacing `t('key')` with `CODE` seems mostly safe IF `t('key')` is inside `{}` or similar boundary.
// But regex `t\(['"]key['"]\)` matches just the function call.
// Let's try replacing `t('key')` with `originalCode`.
// There is one catch: Unescape quotes.
// And if original code contained `"` and I am pasting it?
// `t('key')` is expression. `CODE` is expression.
// It should be fine.
content = content.substring(0, m.index) + originalCode + content.substring(m.index + m.full.length);
restoredCount++;
}
}
if (content !== originalContent) {
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Restored code in ${filePath}`);
}
});
console.log(`Restored ${restoredCount} instances.`);
// Now remove keys from LanguageContext
// We filter `lines` array
// This is hard because of multi-line values.
// Better to filter `garbageKeys` from the file content we read earlier?
// We can rewrite the file excluding the lines corresponding to garbage keys.
// But line numbers match strict indices.
// Let's filter line by line, but need to reconstruct proper structure.
// Simpler: Read key/values again and build new file string.
// Or iterate `lines` and skip those that start with garbage keys?
// What about multiline values? We need to skip them too.
// Pass 2 on LanguageContext to strip
const newContextLines = [];
isMultiLine = false;
let skipMode = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (!isMultiLine) {
const match = line.match(keyStartRegex);
if (match) {
const key = match[1];
if (garbageKeys.has(key)) {
// Skip this line
// Check if multiline
let rest = match[2];
if (!rest.trim().endsWith("',") && !(rest.trim().endsWith("'") && !rest.trim().endsWith("\\'"))) {
isMultiLine = true;
skipMode = true;
}
continue;
}
}
newContextLines.push(line);
} else {
// In multi-line value
// Check end
if (line.trim().endsWith("',") || (line.trim().endsWith("'") && !line.trim().endsWith("\\'"))) {
isMultiLine = false;
if (skipMode) {
skipMode = false;
continue;
}
newContextLines.push(line);
} else {
if (skipMode) continue;
newContextLines.push(line);
}
}
}
fs.writeFileSync(contextPath, newContextLines.join('\n'), 'utf8');
console.log("LanguageContext cleaned.");
} catch (e) {
console.error(e);
}
function isGarbage(text) {
if (!text) return false;
// Indicators of code
if (text.includes(') : (') || text.includes('? (') || text.includes(') ?') || text.includes(' && ') || text.includes(' || ')) return true;
if (text.trim().startsWith('//') || text.includes('/*')) return true;
if (text.includes('=>') && text.includes('{')) return true;
if (text.includes('</') && text.includes('>')) return true; // HTML tags
if (text.endsWith('}') && text.includes('return ')) return true;
if (text.includes('?.') || text.includes('!. ')) return true;
// Specific garbage saw
if (text.includes('setShowLocationPicker')) return true;
if (text.includes('.current?.click()')) return true;
return false;
}