-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.js
382 lines (340 loc) · 11.7 KB
/
utils.js
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
const fs = require("fs");
const path = require("path");
const readline = require("readline");
const {createParser} = require('css-selector-parser');
const pluginName = "PostCSS Obfuscator";
function getRandomName(length) {
// Generate a random string of characters with the specified length
const randomString = Math.random()
.toString(36)
.substring(2, length - 1 + 2);
// Combine the random string with a prefix to make it a valid class name (starts with a letter, contains only letters, digits, hyphens, and underscores)
const randomLetter = String.fromCharCode(Math.floor(Math.random() * 26) + 97); // 97 is the ASCII code for lowercase 'a'
return `${randomLetter}${randomString}`;
}
function simplifyString(str) {
tempStr = str.replace(/[aeiouw\d_-]/gi, "");
return tempStr.length < 1
? String.fromCharCode(Math.floor(Math.random() * 26) + 97) + tempStr
: tempStr;
}
function writeJsonToFile(
data,
filePath,
format = true,
fresh = false,
startOver = false
) {
// If startOver is true, remove the directory path
const dirPath = filePath.substring(0, filePath.lastIndexOf("/"));
if (startOver) {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true });
logger("info", pluginName, "Directory removed:", dirPath);
}
}
// Create the directory path if it doesn't exist
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
logger("info", pluginName, "Directory created:", dirPath);
}
// Check if the file exists
if (!fs.existsSync(filePath)) {
// Create the file with an empty object as the default content
fs.writeFileSync(filePath, "{}");
logger("info", pluginName, "File created:", filePath);
}
// Read the existing JSON data from the file
let jsonData = fs.readFileSync(filePath);
// Parse the existing JSON data
let parsedData = JSON.parse(jsonData);
// Merge the new data with the existing data
const mergedData = fresh ? data : { ...data, ...parsedData };
// Write the merged data to the file
const outputData = format
? JSON.stringify(mergedData, null, 2)
: JSON.stringify(mergedData);
fs.writeFileSync(filePath, outputData);
logger("info", pluginName, "Data written to file:", filePath);
}
function replaceJsonKeysInFiles(
filesDir,
htmlExtensions,
htmlExclude,
jsonDataPath,
indicatorStart,
indicatorEnd,
keepData
) {
// Read and merge the JSON data
const jsonData = {};
fs.readdirSync(jsonDataPath).forEach((file) => {
const filePath = path.join(jsonDataPath, file);
const fileData = JSON.parse(fs.readFileSync(filePath, "utf-8"));
Object.assign(jsonData, fileData);
});
// Read and process the files
const replaceJsonKeysInFile = (filePath) => {
const fileExt = path.extname(filePath).toLowerCase();
if (fs.statSync(filePath).isDirectory()) {
// Recursively process all files in subdirectories
fs.readdirSync(filePath).forEach((subFilePath) => {
replaceJsonKeysInFile(path.join(filePath, subFilePath));
});
} else if (
htmlExtensions.includes(fileExt) &&
!htmlExclude.includes(path.basename(filePath))
) {
// Replace JSON keys in the file
let fileContent = fs.readFileSync(filePath, "utf-8");
Object.keys(jsonData).forEach((key) => {
let keyUse = escapeRegExp(key.slice(1).replace(/\\/g, ""));
let regex;
regex = new RegExp(`([\\s"'\\\`]|^)(${keyUse})(?=$|[\\s"'\\\`])`, 'g'); // match exact wording & avoid ` ' ""
fileContent = fileContent.replace(regex, `$1` + jsonData[key].slice(1).replace(/\\/g, "")); // capture preceding space
if (indicatorStart || indicatorEnd) {
regex = new RegExp(`([\\s"'\\\`]|^)(${indicatorStart ?? ''}${keyUse})(?=$|[\\s"'\\\`])`, 'g');
fileContent = fileContent.replace(regex, `$1` + jsonData[key].slice(1).replace(/\\/g, ""));
regex = new RegExp(`([\\s"'\\\`]|^)(${keyUse}${indicatorEnd ?? ''})(?=$|[\\s"'\\\`])`, 'g');
fileContent = fileContent.replace(regex, `$1` + jsonData[key].slice(1).replace(/\\/g, ""));
regex = new RegExp(`([\\s"'\\\`]|^)(${indicatorStart ?? ''}${keyUse}${indicatorEnd ?? ''})(?=$|[\\s"'\\\`])`, 'g');
fileContent = fileContent.replace(regex, `$1` + jsonData[key].slice(1).replace(/\\/g, ""));
}
});
fs.writeFileSync(filePath, fileContent);
}
if (!keepData) {
if (fs.existsSync(jsonDataPath)) {
fs.rmSync(jsonDataPath, { recursive: true });
logger("info", pluginName, "Data removed:", jsonDataPath);
}
}
};
// Process all files in the directory
replaceJsonKeysInFile(filesDir);
}
function copyDirectory(source, destination, copyHiddenFiles = false) {
return new Promise((resolve, reject) => {
// Create the destination directory if it doesn't exist
if (!fs.existsSync(destination)) {
fs.mkdirSync(destination);
}
// Get a list of all the files and directories in the source directory
const files = fs.readdirSync(source);
// Loop through the files and directories
for (const file of files) {
// Check if hidden file should be copied
if (!copyHiddenFiles && file.startsWith(".")) {
continue;
}
const sourcePath = path.join(source, file);
const destPath = path.join(destination, file);
// Check if the current item is a directory
if (fs.statSync(sourcePath).isDirectory()) {
// Recursively copy the directory
copyDirectory(sourcePath, destPath);
} else {
// Copy the file
fs.copyFileSync(sourcePath, destPath);
}
}
// All files and directories have been copied
resolve();
});
}
function getFileCount(directoryPath, extensions, excludePathsOrFiles = []) {
let count = 0;
const files = fs.readdirSync(directoryPath);
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
const isExcluded = excludePathsOrFiles.some((excludePathOrFile) => {
return (
excludePathOrFile === file ||
excludePathOrFile === filePath ||
excludePathOrFile === path.basename(filePath)
);
});
if (fs.statSync(filePath).isDirectory()) {
count += getFileCount(filePath, extensions, excludePathsOrFiles);
} else if (
extensions.some((extension) => file.endsWith(extension)) &&
!isExcluded
) {
count++;
}
});
return count;
}
function extractClassNames(obj) {
const classNames = new Set();
function traverse(node) {
if (node.type === "ClassName") {
classNames.add(node.name);
}
for (const key of Object.keys(node)) {
const value = node[key];
if (typeof value === "object" && value !== null) {
if (Array.isArray(value)) {
value.forEach(traverse);
} else {
traverse(value);
}
}
}
}
traverse(obj);
return classNames;
}
function escapeClassName(className) {
// CSS escapes for some special characters
const escapes = {
'!': '\\!',
'"': '\\"',
'#': '\\#',
'$': '\\$',
'%': '\\%',
'&': '\\&',
'\'': '\\\'',
'(': '\\(',
')': '\\)',
'*': '\\*',
'+': '\\+',
',': '\\,',
'.': '\\.',
'/': '\\/',
':': '\\:',
';': '\\;',
'<': '\\<',
'=': '\\=',
'>': '\\>',
'?': '\\?',
'@': '\\@',
'[': '\\[',
'\\': '\\\\',
']': '\\]',
'^': '\\^',
'`': '\\`',
'{': '\\{',
'|': '\\|',
'}': '\\}',
'~': '\\~',
' ': '\\ ',
};
// Special handling for class names starting with a digit
if (/^\d/.test(className)) {
// Convert the first digit to its hexadecimal escape code
const firstCharCode = className.charCodeAt(0).toString(16);
const rest = className.slice(1);
// Use the hexadecimal escape for the first character, followed by the rest of the class name
// Note: A trailing space is added after the escape sequence to ensure separation
return `\\${firstCharCode}${rest.split('').map(char => escapes[char] || char).join('')}`;
}
// Replace each special character with its escaped version for the rest of the class name
return className.split('').map(char => escapes[char] || char).join('');
}
function octalizeClassName(className) {
// Escape the first character if it's a digit or a special character
let firstCharEscaped = '';
if (/[\d>]/.test(className.charAt(0))) {
const firstChar = className.charCodeAt(0).toString(16).toLowerCase();
firstCharEscaped = `\\${firstChar}`;
}
// Escape other special characters in the rest of the className
const restEscaped = className.slice(firstCharEscaped ? 1 : 0)
.split('')
.map(char => {
if (/[!\"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/.test(char)) {
// Directly escape special characters
return `\\${char}`;
}
return char;
})
.join('');
return firstCharEscaped + restEscaped;
}
function getClassNames(selectorStr) {
// https://github.com/mdevils/css-selector-parser/issues/40
// Avoid keyframe selectors: @keyframes, from, to, 0%, 100%. 50%
const keyframeOrAtRuleRegex = /^(?:@|\d+|from|to)\b/;
if (keyframeOrAtRuleRegex.test(selectorStr)) {
return new Set(); // Return an empty set for ignored cases
}
// https://github.com/mdevils/css-selector-parser/issues/41
// Remove '&' used for nesting in CSS, if present
selectorStr = selectorStr.replace(/(^|\s+)&/g, '');
const parse = createParser({syntax: 'progressive'});
const ast = parse(selectorStr);
return extractClassNames(ast);
}
function getIdNames(selectorStr) {
let ids = selectorStr.replace(".#", " ").replace(".", " ").trim().split(" ");
ids = ids.filter((id) => id.charAt(0) == "#");
return ids;
}
function logger(type, issuer, task, data) {
const mainColor = "\x1b[38;2;99;102;241m%s\x1b[0m";
switch (type) {
case "info":
console.info(mainColor, issuer, "\x1b[36m", task, data, "\x1b[0m");
break;
case "warn":
console.warn(mainColor, issuer, "\x1b[33m", task, data, "\x1b[0m");
break;
case "error":
console.error(mainColor, issuer, "\x1b[31m", task, data, "\x1b[0m");
break;
case "success":
console.log(mainColor, issuer, "\x1b[32m", task, data, "\x1b[0m");
break;
default:
console.log("'\x1b[0m'", issuer, task, data, "\x1b[0m");
break;
}
}
function getRelativePath(absolutePath) {
const currentDirectory = process.cwd();
const relativePath = path.relative(currentDirectory, absolutePath);
return relativePath;
}
function isFileOrInDirectory(paths, filePath) {
const resolvedFilePath = filePath.replace(/\\/g, "/"); // Replace backslashes with forward slashes
for (const currentPath of paths) {
const resolvedCurrentPath = currentPath.replace(/\\/g, "/"); // Replace backslashes with forward slashes
if (resolvedCurrentPath === resolvedFilePath) {
// The path is one of the items in the array, so it's a file or directory
return true;
}
if (
resolvedCurrentPath.endsWith("/") &&
resolvedFilePath.startsWith(resolvedCurrentPath)
) {
// The current path is a directory, so check whether the file is inside it
const relativeFilePath = resolvedFilePath.substr(
resolvedCurrentPath.length
);
if (!relativeFilePath.startsWith("/") && relativeFilePath !== "") {
// The file is inside the directory
return true;
}
}
}
return false;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
module.exports = {
getRandomName,
simplifyString,
writeJsonToFile,
copyDirectory,
replaceJsonKeysInFiles,
getFileCount,
getClassNames,
getIdNames,
logger,
getRelativePath,
isFileOrInDirectory,
escapeClassName,
octalizeClassName,
};