-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
296 lines (292 loc) · 10.5 KB
/
index.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
const {
getRandomName,
simplifyString,
writeJsonToFile,
copyDirectory,
replaceJsonKeysInFiles,
getFileCount,
getClassNames,
getIdNames,
logger,
getRelativePath,
isFileOrInDirectory,
escapeClassName,
octalizeClassName,
} = require("./utils");
const path = require("path");
const pluginName = "PostCSS Obfuscator";
const pluginVersion = "V 1.6.0 Beta";
const pluginWebSite = "https://github.com/n4j1Br4ch1D/postcss-obfuscator";
const pluginHead = ` __ ${pluginName} __
(oo) ${pluginVersion} (xx)
//||\\\\ ${pluginWebSite} //||\\\\
======================================================================> `;
const defaultOptions = {
enable: true, // Enable plugin
length: 5, // Random name length.
classMethod: "random", // 'random', 'simple', 'none' obfuscation method for classes.
classPrefix: "", // ClassName prefix.
classSuffix: "", // ClassName suffix.
classIgnore: [], // Class to ignore from obfuscation.
ids: false, // Obfuscate #IdNames.
idMethod: "random", // 'random', 'simple', 'none' obfuscation method for ids .
idPrefix: "", // idName Prefix.
idSuffix: "", // idName suffix.
idIgnore: [], // Ids to ignore from obfuscation.
indicatorStart: null, // Identify ids & classes by the preceding string.
indicatorEnd: null, // Identify ids & classes by the following string.
jsonsPath: "css-obfuscator", // Path and file name where to save obfuscation data.
srcPath: "src", // Source of your files.
desPath: "out", // Destination for obfuscated html/js/.. files. Be careful using the same directory as your src(you will lose your original files).
extensions: ['.html'], // Extesnion of files you want osbfucated ['.html', '.php', '.js', '.svelte'].
htmlExcludes: [], // Files and paths to exclude from html obfuscation replacement.
cssExcludes: [], // Files and paths to exclude from css obfuscation.
fresh: false, // Create new obfuscation data list or use already existed one (to keep production cache or prevent data scrapping).
multi: false, // Generate obsfucated data file for each css file.
differMulti: false, // Generate different Random names for each file.
formatJson: false, // Format obfuscation data JSON file.
showConfig: false, // Show config on terminal when runinng.
keepData: true, // Keep or delete Data after obfuscation is finished?
preRun: () => Promise.resolve(), // do something before the plugin runs.
callBack: function () {}, // Callback function to call after obfuscation is done.
};
let data = {};
let jsonData = {};
let singleFileData = {};
let processedFiles = new Set();
let idList = new Set();
let cssNo = 0;
let classesNo = 0;
let idsNo = 0;
const envMode = process.env.NODE_ENV;
module.exports = (options = {}) => {
// Get Final Option By Merging the default and user-defined options
const {
enable,
length,
classMethod,
classPrefix,
classSuffix,
classIgnore,
ids,
idMethod,
idPrefix,
idSuffix,
idIgnore,
indicatorStart,
indicatorEnd,
jsonsPath,
srcPath,
desPath,
extensions,
htmlExcludes,
cssExcludes,
fresh,
multi,
differMulti,
formatJson,
showConfig,
keepData,
preRun,
callBack,
} = { ...defaultOptions, ...options };
return {
postcssPlugin: pluginName,
Once: async (root, { result }) => {
// Add the file path to the set of processed files
if (!enable) {
return;
} else {
await preRun();
if (processedFiles.size == 0) {
console.log("\x1b[48;2;103;113;210m%s\x1b[0m", pluginHead);
if (envMode === "dev" || envMode === "development") {
logger(
"warn",
pluginName,
"Warning:",
"You are Running in Dev Mode!"
);
}
if (srcPath === desPath) {
logger(
"warn",
pluginName,
"Warning:",
"Are You Sure You wanna Replace this file This my cause you loose your surce data please specify antother folder"
);
}
cssFilesNo = getFileCount(srcPath, [".css"], cssExcludes);
if (showConfig) {
console.info("\x1b[34m", "Plug", "\x1b[36m", "Config:", {
...defaultOptions,
...options,
});
}
logger("info", pluginName, "PreRun:", "PreRun event hook finished.");
}
let cssFile = getRelativePath(result.opts.from);
if (isFileOrInDirectory(cssExcludes, cssFile)) {
logger("info", pluginName, "Ignoring:", cssFile);
return;
}
cssNo++;
logger("info", pluginName, "processing:", cssFile);
if (envMode === "dev" || envMode === "development") {
root.prepend({
text: ` __
(oo)
//||\\\\
${pluginName}
${pluginVersion}
${pluginWebSite}
** this only appears on Dev Mode **
`,
});
}
singleFileData = {};
if (multi) {
data = singleFileData;
if (differMulti) {
data = singleFileData;
} else {
data = jsonData;
}
} else {
data = jsonData;
}
root.walkRules((rule) => {
rule.selectors = rule.selectors.map((selector) => {
// get List of all classNames in the selector
const classList = getClassNames(selector);
classesNo += classList.size;
classList.forEach((className) => {
// Generate new className
let oldClassName = "." + className;
let newClassName;
if (classIgnore.includes(className) || classMethod == "none") {
newClassName = className;
} else if (classMethod == "simple") {
newClassName = simplifyString(className);
} else {
newClassName = getRandomName(length);
}
newClassName = `.${classPrefix}${newClassName}${classSuffix}`;
validCssClassName = '.'+escapeClassName(oldClassName.slice(1));
//cond
octalValidCssClassName = '.'+octalizeClassName(oldClassName.slice(1));
// If ClassName already exist replace with its value else generate new : the should have same name.
console.log("validCssClassName:", validCssClassName);
if (jsonData.hasOwnProperty(oldClassName)) {
selector = selector.replace(
validCssClassName,
jsonData[oldClassName]
);
//cond
selector = selector.replace(
octalValidCssClassName,
jsonData[oldClassName]
);
} else {
selector = selector.replace(validCssClassName, newClassName);
//cond
selector = selector.replace(octalValidCssClassName, newClassName);
jsonData[oldClassName] = newClassName;
}
singleFileData[oldClassName] = newClassName;
});
if (ids) {
idList = getIdNames(selector);
idList.forEach((idName) => {
idsNo++;
// Get only idName not other elements or pseudo-element & remove spaces.
let oldIdName = idName;
// Generate new idName
let newIdName;
if (idIgnore.includes(idName) || idMethod == "none") {
newIdName = idName.splice(1);
} else if (idMethod == "simple") {
newIdName = simplifyString(idName);
} else {
newIdName = getRandomName(length);
}
newIdName = `#${idPrefix}${newIdName}${idSuffix}`;
if (jsonData.hasOwnProperty(oldIdName)) {
selector = selector.replace(oldIdName, jsonData[oldIdName]);
} else {
selector = selector.replace(oldIdName, newIdName);
jsonData[oldIdName] = newIdName;
}
singleFileData[oldIdName] = newIdName;
});
}
return selector;
});
});
jsonData = { ...jsonData, ...singleFileData };
const fileName = path.basename(root.source.input.file, ".css");
// If mult & keep same get and replace.
const newjsonsPath = `${jsonsPath}/${multi ? fileName : "main"}.json`;
writeJsonToFile(data, newjsonsPath, formatJson, fresh, !multi & fresh);
if (cssNo == cssFilesNo) {
copyDirectory(srcPath, desPath, true)
.then(() => {
logger(
"info",
pluginName,
"Copying:",
`${srcPath} to ${desPath} finished!`
);
replaceJsonKeysInFiles(
desPath,
extensions,
htmlExcludes,
jsonsPath,
indicatorStart,
indicatorEnd,
keepData
);
logger(
"info",
pluginName,
"Replacing:",
`All files have been updated!`
);
logger(
"success",
pluginName,
"Processed:",
`${cssFilesNo}/${getFileCount(
srcPath,
[".css"],
[]
)} CSS| ${getFileCount(
srcPath,
extensions,
htmlExcludes
)}/${getFileCount(srcPath, extensions, [])} Files| ${
classesNo - classIgnore.length
}/${classesNo} Class| ${idsNo - idIgnore.length}/${idsNo} Id`
);
callBack();
console.info(
"\x1b[38;2;99;102;241m%s\x1b[0m",
"==========================================================================>",
"\x1b[0m"
);
})
.catch((error) => {
logger(
"error",
pluginName,
"Error copying directory:",
error.message
);
});
}
}
processedFiles.add(jsonsPath);
},
};
};
module.exports.postcss = true;