zyd-server-build2 1.0.15 → 1.0.17

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.
Files changed (3) hide show
  1. package/README.md +253 -72
  2. package/index.js +34 -1
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,76 +1,233 @@
1
- # [zyd-server-build2](https://github.com/hfzhae/zyd-server-build2)
2
- <p>
3
- <a href="https://github.com/hfzhae/zyd-server-build2/blob/main/LICENSE"><img style="margin-right:5px;" src="https://img.shields.io/badge/license-MIT-grren.svg"></a>
4
- <a href="https://www.npmjs.com/package/uglify-js"><img style="margin-right:5px;" src="https://img.shields.io/badge/terser-5.x-blue.svg"></a>
5
- <a href="https://www.npmjs.com/package/zyd-server-build2"><img style="margin-right:5px;" src="https://img.shields.io/badge/npm-passing-yellow.svg"></a>
6
- </p>
1
+ /**
2
+ * Powered by zydsoft™
3
+ * 2021-9-14
4
+ * zz
5
+ */
6
+ const { minify } = require("terser")
7
+ const { execSync } = require('child_process')
8
+ const fs = require("fs")
9
+ const path = require("path")
10
+ const count = [0, 0, 0]
11
+ const timer = []
12
+ const version = require('./package.json').version
13
+ let baseDst = ''
14
+ const operatingDir = generateComplexRandomString(5)
7
15
 
8
- ## Installation
9
- ```
10
- $ npm install -s zyd-server-build2
11
- ```
16
+ async function build({ src, dst, ignoreDir = [], ignoreFile = [], copyright = "", noBuildFile = [], noBuildDir = [], noEncryptionPathFile = [], confused = 1, options = {}, encryptionPath = 0 }) {
17
+ if (!src || !dst) {
18
+ return
19
+ }
20
+ ignoreDir.length > 0 && ignoreDir.push(dst)
21
+ await fs.readdirSync(src).forEach(async file => {
22
+ const _src = src + "/" + file
23
+ let _dst = dst + "/" + file
24
+ if (encryptionPath && !ignore(noBuildFile, _src) && confused === 1 && path.extname(_src) === ".js" && !ignore(noEncryptionPathFile, _src)) {
25
+ _dst = `${baseDst}/z.${operatingDir}/${generateComplexRandomString(5)}.${Math.random().toString(36).substring(2, 10)}.js`
26
+ }
27
+ const st = fs.statSync(_src)
28
+ if (st.isFile()) {
29
+ count[2] += st.size
30
+ count[0]++
31
+ if (ignore(ignoreFile, _src)) {
32
+ count[2] -= st.size
33
+ console.log(_src, "\x1B[36m=>\x1B[0m", _dst, `\x1B[33m${bytesToSize(st.size)}\x1B[0m`, "\x1B[31mSkip x\x1B[0m")
34
+ count[0]--
35
+ return
36
+ }
37
+ if (path.extname(_src) === ".js") {
38
+ if (ignore(noBuildFile, _src) || confused === 0) {
39
+ console.log(_src, "\x1B[36m=>\x1B[0m", _dst, `\x1B[33m${bytesToSize(st.size)}\x1B[0m`, "\x1B[32m√\x1B[0m")
40
+ readable = fs.createReadStream(_src);
41
+ writable = fs.createWriteStream(_dst);
42
+ readable.pipe(writable);
43
+ } else {
44
+ console.log(_src, "\x1B[36m=>\x1B[0m", _dst, `\x1B[33m${bytesToSize(st.size)}\x1B[0m`, "\x1B[32mCode confused √\x1B[0m")
45
+ await execSync(`npx babel ${_src} --out-file ${_dst}`)
46
+ readable = await fs.readFileSync(_dst, 'utf-8')
47
+ const result = await minify(readable, {
48
+ parse: {
49
+ // parse options
50
+ },
51
+ compress: options,
52
+ mangle: {
53
+ // mangle options
54
+ },
55
+ format: {
56
+ // format options (can also use `output` for backwards compatibility)
57
+ },
58
+ sourceMap: {
59
+ // source map options
60
+ },
61
+ ecma: 2016, // specify one of: 5, 2015, 2016, etc.
62
+ enclose: false, // or specify true, or "args:values"
63
+ ie8: false,
64
+ module: true,
65
+ nameCache: null, // or specify a name cache object
66
+ safari10: false,
67
+ keep_classnames: true, // 默认 false。传 true来防止压缩器干掉对象名。对那些依赖
68
+ keep_fnames: true, // 默认 false。传 true来防止压缩器干掉函数名。对那些依赖
69
+ toplevel: false
70
+ })
71
+ await fs.writeFileSync(_dst, (copyright ? "/* " + copyright + " */" : "") + result.code)
72
+ count[1]++
73
+ }
74
+ } else {
75
+ console.log(_src, "\x1B[36m=>\x1B[0m", _dst, `\x1B[33m${bytesToSize(st.size)}\x1B[0m`, "\x1B[32m√\x1B[0m")
76
+ readable = fs.createReadStream(_src)
77
+ writable = fs.createWriteStream(_dst)
78
+ readable.pipe(writable)
79
+ }
80
+ // sleep(100)
81
+ // count[3] += fs.statSync(_dst).size
82
+ } else if (st.isDirectory()) {
83
+ if (ignore(ignoreDir, _src)) {
84
+ return
85
+ }
86
+ makeDir(_dst)
87
+ await build({ src: _src, dst: _dst, ignoreDir, ignoreFile, copyright, noBuildFile, noBuildDir, noEncryptionPathFile, confused: ignore(noBuildDir, _src) ? 0 : 1, encryptionPath })
88
+ }
89
+ })
90
+ }
91
+
92
+ function ignore(arr, str) {
93
+ let d = false
94
+ arr.forEach(item => {
95
+ item === str && (d = true)
96
+ })
97
+ return d
98
+ }
99
+
100
+ function exists(dst, noDeleteDir) {
101
+ if (!fs.existsSync(dst)) {
102
+ makeDir(dst)
103
+ } else {
104
+ // del(dst)
105
+ delDir(dst, noDeleteDir)
106
+ // makeDir(dst)
107
+ }
108
+ }
12
109
 
13
- ## Quickstart
14
- >./babelrc
15
- ```json
16
- {
17
- "presets": [
18
- "@babel/preset-env"
19
- ],
20
- "plugins": [
21
- [
22
- "@babel/plugin-proposal-decorators",
23
- {
24
- "legacy": true
110
+ function makeDir(dirpath) {
111
+ if (!fs.existsSync(dirpath)) {
112
+ var pathtmp;
113
+ dirpath.split("/").forEach(dirname => {
114
+ if (pathtmp) {
115
+ pathtmp = path.join(pathtmp, dirname);
116
+ }
117
+ else {
118
+ //如果在linux系统中,第一个dirname的值为空,所以赋值为"/"
119
+ if (dirname) {
120
+ pathtmp = dirname;
121
+ } else {
122
+ pathtmp = "/";
123
+ }
124
+ }
125
+ if (!fs.existsSync(pathtmp)) {
126
+ if (!fs.mkdirSync(pathtmp)) {
127
+ return false;
128
+ }
25
129
  }
26
- ]
27
- ]
130
+ });
131
+ // } else {
132
+ // deleteFolderFiles(dirpath);
133
+ }
134
+ return true;
28
135
  }
29
- ```
30
- >./jsconfig.json
31
- ```json
32
- {
33
- "compilerOptions": {
34
- "experimentalDecorators": true
136
+
137
+ const delDir = (url, noDeleteDir) => {
138
+ var files = []
139
+ files = fs.readdirSync(url)
140
+ for (var i = 0; i < files.length; i++) {
141
+ if (!noDeleteDir.find(item => item === files[i])) {
142
+ var path = url + '/' + files[i]
143
+ if (fs.statSync(path).isFile()) {
144
+ fs.unlinkSync(path)
145
+ } else {
146
+ delDir(path, noDeleteDir)
147
+ }
148
+ }
35
149
  }
36
150
  }
37
- ```
38
- >/package.json
39
- ```json
40
- {
41
- "name": "myApp",
42
- "version": "1.0.0",
43
- "description": "",
44
- "main": "index.js",
45
- "scripts": {
46
- "build": "node build.js"
47
- },
48
- "author": "",
49
- "license": "ISC"
151
+
152
+
153
+ function bytesToSize(bytes) {
154
+ if (bytes === 0) return '0 B';
155
+ var k = 1024;
156
+ sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
157
+ i = Math.floor(Math.log(bytes) / Math.log(k))
158
+ //return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
159
+ return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
160
+ //toPrecision(3) 后面保留两位小数,如1.00GB
161
+ }
162
+
163
+ /**
164
+ * 阻塞函数
165
+ * @param {Number} milliSeconds 毫秒数
166
+ */
167
+ function sleep(milliSeconds) {
168
+ const startTime = new Date().getTime()
169
+ while (new Date().getTime() < startTime + milliSeconds) { }
50
170
  }
51
- ```
52
- >/build.js
53
- ```js
54
- const zsb = require("zyd-server-build2")
55
- zsb()
56
- ```
57
- ## Options
58
- >/build.js
59
- ```js
60
- const zsb = require("zyd-server-build2")
61
- zsb({
62
- src: "..", // 源文件夹, . 代表当前目录, .. 代表上级目录
63
- dst: "../build", // 目标文件夹, . 代表当前目录, .. 代表上级目录
64
- noBuildFile: ["../server/config/index.js"], // 不需要混淆压缩的文件(完整路径),文件路径前需要包含src的内容,如实例,会被无改动打包到目标文件夹中
65
- noBuildDir: ["../server/public/js"]. // 不需要混淆压缩的文件夹(完整路径),文件路径前需要包含src的内容,如实例,会被无改动打包到目标文件夹中
66
- ignoreDir: [ // 需要忽略的文件夹(完整路径),文件夹路径前需要包含src的内容,如实例,忽略后不会被打包到目标文件夹中
67
- "../.git",
68
- "../server/node_modules",
69
- ],
70
- ignoreFile: ["../.gitmodules"], // 需要忽略的文件(完整路径),文件路径前需要包含src的内容,如实例,忽略后不会被打包到目标文件夹中
71
- noDeleteDir: [".git", "node_modules"], // 需要忽略删除的文件或文件夹,默认:[".git", "node_modules"]
72
- copyright: "Powered by zydsoft™", // 版权申明
73
- options: { // 压缩选项
171
+
172
+ function formatDuration(ms) {
173
+ if (ms < 0) ms = -ms;
174
+ const time = {
175
+ day: Math.floor(ms / 86400000),
176
+ hour: Math.floor(ms / 3600000) % 24,
177
+ minute: Math.floor(ms / 60000) % 60,
178
+ second: Math.floor(ms / 1000) % 60,
179
+ millisecond: Math.floor(ms) % 1000
180
+ };
181
+ return Object.entries(time)
182
+ .filter(val => val[1] !== 0)
183
+ .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
184
+ .join(', ');
185
+ }
186
+
187
+ function generateComplexRandomString(length) {
188
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
189
+ let result = '';
190
+
191
+ for (let i = 0; i < length; i++) {
192
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
193
+ }
194
+ return result;
195
+ }
196
+
197
+ function safeDelete(dir) {
198
+ try {
199
+ if (!fs.existsSync(dir)) {
200
+ return;
201
+ }
202
+ // 先递归处理子目录
203
+ const files = fs.readdirSync(dir);
204
+ for (const file of files) {
205
+ const fullPath = path.join(dir, file);
206
+ if (fs.statSync(fullPath).isDirectory()) {
207
+ safeDelete(fullPath);
208
+ }
209
+ }
210
+ // 处理完子目录后,再判断自己是否为空
211
+ if (fs.readdirSync(dir).length === 0) {
212
+ fs.rmdirSync(dir);
213
+ // console.log(`已删除: ${dir}`);
214
+ }
215
+ } catch (error) {
216
+ // console.error(`删除失败 [${dir}]:`, error.message);
217
+ }
218
+ }
219
+
220
+ module.exports = async ({
221
+ src = ".",
222
+ dst = "./build",
223
+ ignoreDir = ["./.git", "./node_modules"],
224
+ ignoreFile = ["./build.js"],
225
+ copyright = "",
226
+ noBuildFile = [],
227
+ noBuildDir = [],
228
+ noEncryptionPathFile = [],
229
+ noDeleteDir = [".git", "node_modules"],
230
+ options = {
74
231
  drop_console: true, // 删除console
75
232
  dead_code: true, // 移除没被引用的代码
76
233
  drop_debugger: true, // 移除 debugger;
@@ -88,9 +245,33 @@ zsb({
88
245
  DEBUG: false
89
246
  },
90
247
  },
91
- encryptionPath: 0, // 加密路径,1为加密,默认:0
92
- noEncryptionPathFile: ["../server/middleware/index.js"] // 不需要加密的文件(完整路径),文件路径前需要包含src的内容,如实例,文件路径会被无改动打包到目标文件夹中
93
- })
94
- ```
95
- ## License
96
- [MIT](https://github.com/hfzhae/zyd-server-build/blob/main/LICENSE)
248
+ encryptionPath = 0
249
+ } = {}) => {
250
+ console.log(`\x1B[33m
251
+ ┌─────────────────────┐
252
+ │ Powered by zydsoft® │
253
+ │ zyd-server-build │
254
+ └─────────────────────┘
255
+ \x1B[0m\x1B[37mversion:\x1B[0m\x1B[31m${version}\x1B[0m
256
+ `)
257
+ console.log("\x1B[36m\x1B[1mStart build...\x1B[0m\x1B[0m\n")
258
+ timer[0] = new Date()
259
+ exists(dst, noDeleteDir)
260
+ baseDst = dst.toString()
261
+ await execSync(`rm -rf ${dst}`)
262
+ await build({ src, dst, ignoreDir, ignoreFile, copyright, noBuildFile, noBuildDir, noEncryptionPathFile, options, encryptionPath })
263
+ process.nextTick(async () => {
264
+ console.log("")
265
+ console.log(`number of files: \x1B[36m${count[0]}\x1B[0m`)
266
+ console.log(`Number of Obfuscated Files: \x1B[36m${count[1]}\x1B[0m`)
267
+ console.log(`Collection Size: \x1B[36m${bytesToSize(count[2])}\x1B[0m`)
268
+ console.log(`time consuming: \x1B[36m${formatDuration(new Date() - timer[0])}\x1B[0m`)
269
+ // console.log("\x1B[1m\x1B[32mbuild success √\x1B[0m\x1B[0m")
270
+ console.log(`\x1B[1m\x1B[32m
271
+ ┌─────────────────┐
272
+ │ build success √ │
273
+ └─────────────────┘
274
+ \x1B[0m\x1B[0m`)
275
+ safeDelete(dst)
276
+ })
277
+ }
package/index.js CHANGED
@@ -51,8 +51,16 @@ async function build({ src, dst, ignoreDir = [], ignoreFile = [], copyright = ""
51
51
  compress: options,
52
52
  mangle: {
53
53
  // mangle options
54
+ // properties: {
55
+ // regex: /^_/ // 混淆以下划线开头的属性名
56
+ // },
57
+ // reserved: [], // 保留不被混淆的变量名列表
58
+ // keep_classnames: false, // 改为 false 允许混淆类名
59
+ // keep_fnames: false, // 改为 false 允许混淆函数名
54
60
  },
55
61
  format: {
62
+ ascii_only: true, // 这将把非ASCII字符(如中文)转换为Unicode转义序列
63
+ quote_style: 3 // 随机使用单引号和双引号
56
64
  // format options (can also use `output` for backwards compatibility)
57
65
  },
58
66
  sourceMap: {
@@ -194,6 +202,29 @@ function generateComplexRandomString(length) {
194
202
  return result;
195
203
  }
196
204
 
205
+ function safeDelete(dir) {
206
+ try {
207
+ if (!fs.existsSync(dir)) {
208
+ return;
209
+ }
210
+ // 先递归处理子目录
211
+ const files = fs.readdirSync(dir);
212
+ for (const file of files) {
213
+ const fullPath = path.join(dir, file);
214
+ if (fs.statSync(fullPath).isDirectory()) {
215
+ safeDelete(fullPath);
216
+ }
217
+ }
218
+ // 处理完子目录后,再判断自己是否为空
219
+ if (fs.readdirSync(dir).length === 0) {
220
+ fs.rmdirSync(dir);
221
+ // console.log(`已删除: ${dir}`);
222
+ }
223
+ } catch (error) {
224
+ // console.error(`删除失败 [${dir}]:`, error.message);
225
+ }
226
+ }
227
+
197
228
  module.exports = async ({
198
229
  src = ".",
199
230
  dst = "./build",
@@ -235,8 +266,9 @@ module.exports = async ({
235
266
  timer[0] = new Date()
236
267
  exists(dst, noDeleteDir)
237
268
  baseDst = dst.toString()
269
+ await execSync(`rm -rf ${dst}`)
238
270
  await build({ src, dst, ignoreDir, ignoreFile, copyright, noBuildFile, noBuildDir, noEncryptionPathFile, options, encryptionPath })
239
- process.nextTick(() => {
271
+ process.nextTick(async () => {
240
272
  console.log("")
241
273
  console.log(`number of files: \x1B[36m${count[0]}\x1B[0m`)
242
274
  console.log(`Number of Obfuscated Files: \x1B[36m${count[1]}\x1B[0m`)
@@ -248,5 +280,6 @@ module.exports = async ({
248
280
  │ build success √ │
249
281
  └─────────────────┘
250
282
  \x1B[0m\x1B[0m`)
283
+ safeDelete(dst)
251
284
  })
252
285
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zyd-server-build2",
3
- "version": "1.0.15",
3
+ "version": "1.0.17",
4
4
  "description": "基于terser的js混淆build库,通过babel支持es6+",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -23,6 +23,6 @@
23
23
  "@babel/node": "^7.20.7",
24
24
  "@babel/plugin-proposal-decorators": "^7.21.0",
25
25
  "@babel/preset-env": "^7.21.4",
26
- "terser": "^5.16.8"
26
+ "terser": "^5.39.0"
27
27
  }
28
28
  }