Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
311 lines (272 loc) · 10.1 KB
/
Copy pathbuild.js
File metadata and controls
311 lines (272 loc) · 10.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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// 导入压缩库
const Terser = require('terser');
const CleanCSS = require('clean-css');
const htmlMinifier = require('html-minifier');
// 配置
const SOURCE_DIR = 'source';
const BUILD_ROOT_DIR = 'build';
const IGNORE_FILES = ['README.md', '.DS_Store'];
const STORE_CHANNEL_PLACEHOLDER = '__GZP_STORE_CHANNEL__';
const VALID_STORE_CHANNELS = new Set(['chrome', 'firefox', 'edge']);
const CHROME_LIKE_STORE_CHANNELS = new Set(['chrome', 'edge']);
function resolveStoreChannel() {
const channelArg = process.argv.find(arg => arg.startsWith('--channel='));
const channel = (channelArg ? channelArg.split('=')[1] : process.env.GZP_STORE_CHANNEL || 'chrome').toLowerCase();
if (!VALID_STORE_CHANNELS.has(channel)) {
throw new Error(`Invalid store channel "${channel}". Expected one of: ${Array.from(VALID_STORE_CHANNELS).join(', ')}`);
}
return channel;
}
const STORE_CHANNEL = resolveStoreChannel();
const BUILD_DIR = path.join(BUILD_ROOT_DIR, STORE_CHANNEL);
// 先清空当前渠道的build目录(跨平台兼容)
if (fs.existsSync(BUILD_DIR)) {
fs.rmSync(BUILD_DIR, { recursive: true, force: true });
console.log(`Cleaned existing build directory: ${BUILD_DIR}`);
}
// 创建新的渠道build目录
fs.mkdirSync(BUILD_DIR, { recursive: true });
// 复制icons目录
const iconsDir = path.join(SOURCE_DIR, 'icons');
const buildIconsDir = path.join(BUILD_DIR, 'icons');
if (fs.existsSync(iconsDir)) {
if (!fs.existsSync(buildIconsDir)) {
fs.mkdirSync(buildIconsDir, { recursive: true });
}
const iconFiles = fs.readdirSync(iconsDir);
for (const file of iconFiles) {
const srcPath = path.join(iconsDir, file);
const destPath = path.join(buildIconsDir, file);
fs.copyFileSync(srcPath, destPath);
console.log(`Copied: ${file}`);
}
}
// 处理文件
function processFile(filePath, relativePath) {
const ext = path.extname(filePath).toLowerCase();
const destPath = path.join(BUILD_DIR, relativePath);
// 确保目标目录存在
const destDir = path.dirname(destPath);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}
// 根据文件类型处理
if (ext === '.js') {
return processJavaScript(filePath, destPath, relativePath);
} else if (ext === '.css') {
processCSS(filePath, destPath);
} else if (ext === '.html') {
processHTML(filePath, destPath);
} else if (ext === '.json') {
processJSON(filePath, destPath);
} else {
// 直接复制其他文件
fs.copyFileSync(filePath, destPath);
console.log(`Copied: ${relativePath}`);
}
return Promise.resolve();
}
// 处理JavaScript文件
async function processJavaScript(srcPath, destPath, relativePath) {
try {
let code = fs.readFileSync(srcPath, 'utf8');
// 如果是jszip.min.js,已经是压缩过的,直接复制
if (path.basename(srcPath) === 'jszip.min.js') {
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (minified): ${path.relative(BUILD_DIR, destPath)}`);
return;
}
if (relativePath === 'constants.js') {
if (!code.includes(STORE_CHANNEL_PLACEHOLDER)) {
throw new Error(`Missing store channel placeholder in ${srcPath}`);
}
code = code.replaceAll(STORE_CHANNEL_PLACEHOLDER, STORE_CHANNEL);
console.log(`Injected store channel: ${STORE_CHANNEL}`);
}
if (relativePath === 'i18n.js') {
const localeDir = path.join(SOURCE_DIR, 'locales');
const bundledLocales = {};
for (const locale of ['en', 'zh-CN']) {
const localePath = path.join(localeDir, `${locale}.json`);
bundledLocales[locale] = JSON.parse(fs.readFileSync(localePath, 'utf8'));
}
const marker = '/*__GZP_BUNDLED_LOCALES__*/ {}';
if (!code.includes(marker)) {
throw new Error(`Missing locale bundle marker in ${srcPath}`);
}
code = code.replace(marker, JSON.stringify(bundledLocales));
console.log('Bundled locale JSON into i18n.js');
}
// 使用terser压缩
const result = await Terser.minify(code, {
compress: {
drop_console: false, // 保留console语句用于调试
drop_debugger: true,
ecma: 2020,
},
mangle: {
toplevel: true,
reserved: ['chrome', 'browser', 'window', 'document', 'console']
},
format: {
comments: false,
ecma: 2020
},
sourceMap: false
});
if (result.error) {
console.error(`Error minifying ${srcPath}:`, result.error);
if (relativePath === 'i18n.js') {
throw result.error;
}
// 如果压缩失败,直接复制
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (fallback): ${path.relative(BUILD_DIR, destPath)}`);
} else {
fs.writeFileSync(destPath, result.code);
console.log(`Minified: ${path.relative(BUILD_DIR, destPath)} (${code.length} → ${result.code.length} bytes, ${Math.round((1 - result.code.length / code.length) * 100)}% reduction)`);
}
} catch (error) {
console.error(`Error processing JavaScript ${srcPath}:`, error);
// A Firefox package without bundled i18n data can silently fall back to
// displaying raw translation keys. Do not emit such a package.
if (relativePath === 'i18n.js') {
throw error;
}
// 出错时直接复制
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (error fallback): ${path.relative(BUILD_DIR, destPath)}`);
}
}
// 处理CSS文件
function processCSS(srcPath, destPath) {
try {
const css = fs.readFileSync(srcPath, 'utf8');
const minified = new CleanCSS({
level: 2,
compatibility: '*'
}).minify(css);
if (minified.errors && minified.errors.length > 0) {
console.error(`Error minifying CSS ${srcPath}:`, minified.errors);
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (fallback): ${path.relative(BUILD_DIR, destPath)}`);
} else {
fs.writeFileSync(destPath, minified.styles);
console.log(`Minified CSS: ${path.relative(BUILD_DIR, destPath)} (${css.length} → ${minified.styles.length} bytes, ${Math.round((1 - minified.styles.length / css.length) * 100)}% reduction)`);
}
} catch (error) {
console.error(`Error processing CSS ${srcPath}:`, error);
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (error fallback): ${path.relative(BUILD_DIR, destPath)}`);
}
}
// 处理HTML文件
function processHTML(srcPath, destPath) {
try {
const html = fs.readFileSync(srcPath, 'utf8');
const minified = htmlMinifier.minify(html, {
collapseWhitespace: true,
removeComments: true,
removeRedundantAttributes: false,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyCSS: true,
minifyJS: true
});
fs.writeFileSync(destPath, minified);
console.log(`Minified HTML: ${path.relative(BUILD_DIR, destPath)} (${html.length} → ${minified.length} bytes, ${Math.round((1 - minified.length / html.length) * 100)}% reduction)`);
} catch (error) {
console.error(`Error processing HTML ${srcPath}:`, error);
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (error fallback): ${path.relative(BUILD_DIR, destPath)}`);
}
}
// 处理JSON文件(主要是manifest.json)
function processJSON(srcPath, destPath) {
try {
const jsonContent = fs.readFileSync(srcPath, 'utf8');
const json = JSON.parse(jsonContent);
if (
path.basename(srcPath) === 'manifest.json' &&
json.manifest_version === 3 &&
json.background &&
CHROME_LIKE_STORE_CHANNELS.has(STORE_CHANNEL)
) {
delete json.background.scripts;
json.background.service_worker = 'background.js';
console.log(`Removed background.scripts for ${STORE_CHANNEL} MV3 package`);
}
// Firefox uses an event page for MV3 background scripts and did not
// reliably start that page when service_worker was also present before
// Firefox 121. Keep the Firefox package compatible with its declared
// minimum version by selecting the scripts implementation explicitly.
if (
path.basename(srcPath) === 'manifest.json' &&
json.manifest_version === 3 &&
json.background &&
STORE_CHANNEL === 'firefox'
) {
delete json.background.service_worker;
console.log('Removed background.service_worker for Firefox MV3 package');
}
// 对于JSON文件,我们可以确保格式正确
const formatted = JSON.stringify(json, null, 2);
fs.writeFileSync(destPath, formatted);
console.log(`Processed JSON: ${path.relative(BUILD_DIR, destPath)}`);
} catch (error) {
console.error(`Error processing JSON ${srcPath}:`, error);
fs.copyFileSync(srcPath, destPath);
console.log(`Copied (error fallback): ${path.relative(BUILD_DIR, destPath)}`);
}
}
// 遍历source目录
function walkDir(dir, callback) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
const relativePath = path.relative(SOURCE_DIR, filePath);
// 跳过忽略的文件
if (IGNORE_FILES.includes(file)) {
continue;
}
if (stat.isDirectory()) {
// 跳过icons目录(已经处理过)
if (file === 'icons') {
continue;
}
walkDir(filePath, callback);
} else {
callback(filePath, relativePath);
}
}
}
// 主函数
async function main() {
console.log('Starting build process...');
console.log(`Source: ${SOURCE_DIR}`);
console.log(`Build: ${BUILD_DIR}`);
console.log(`Store channel: ${STORE_CHANNEL}`);
console.log('---');
// 遍历并处理所有文件
const tasks = [];
walkDir(SOURCE_DIR, (filePath, relativePath) => {
tasks.push(processFile(filePath, relativePath));
});
await Promise.all(tasks);
console.log('---');
console.log('Build completed!');
// 显示构建统计
const buildFiles = fs.readdirSync(BUILD_DIR, { recursive: true });
console.log(`Total files in build directory: ${buildFiles.length}`);
}
// 运行主函数
main().catch(error => {
console.error('Build failed:', error);
process.exit(1);
});