/** * 构建进程(独立 worker)加载的钩子脚本;custom-builder 的 configs.*.hooks 指向本文件。 * custom-builder.ts 会 re-export 本文件的钩子,供编辑器校验通过。 */ import fs from 'fs'; import path from 'path'; import lz4 from 'lz4js'; import { minify } from 'terser'; export const throwError = true; function readJson(filePath: string) { const raw = fs.readFileSync(filePath, 'utf8'); return JSON.parse(raw); } /** 解析 game.json;若尾部被旧内容污染则截取首个完整 JSON 对象 */ function readGameJsonSafe(filePath: string): any { const raw = fs.readFileSync(filePath, 'utf8').trim(); try { return JSON.parse(raw); } catch (err) { const start = raw.indexOf('{'); if (start < 0) throw err; let depth = 0; let end = -1; for (let i = start; i < raw.length; i++) { const ch = raw[i]; if (ch === '{') depth++; else if (ch === '}') { depth--; if (depth === 0) { end = i; break; } } } if (end > start) { const recovered = raw.slice(start, end + 1); console.warn(`[tools] game.json 含脏数据,已自动截取有效 JSON: ${filePath}`); return JSON.parse(recovered); } throw err; } } function writeJsonFile(filePath: string, data: unknown): void { const content = `${JSON.stringify(data, null, 2)}\n`; const tmp = `${filePath}.tmp`; fs.writeFileSync(tmp, content, 'utf8'); fs.renameSync(tmp, filePath); } function resolveConfigNameVersion(projectPath: string) { const sdkConfigPath = path.join(projectPath, 'assets', 'script', 'sdk', 'sdkConfig.ts'); const sdkConfigContent = fs.readFileSync(sdkConfigPath, 'utf8'); const importRegex = /import\s+\{\s*(\w+)\s*\}\s+from\s+["']\.\/config\/([^"']+)["'];?/g; const importMap = new Map(); let m: RegExpExecArray | null = null; while ((m = importRegex.exec(sdkConfigContent))) { importMap.set(m[1], m[2]); } const configAssign = sdkConfigContent.match(/static\s+readonly\s+config\s*:\s*IConfigData\s*=\s*(\w+)\s*;/); const symbol = configAssign?.[1] ?? 'DefaultConfig'; const relConfig = importMap.get(symbol) ?? 'DefaultConfig'; const configPath = path.join(projectPath, 'assets', 'script', 'sdk', 'config', `${relConfig}.ts`); const configContent = fs.readFileSync(configPath, 'utf8'); const name = configContent.match(/name\s*:\s*["']([^"']+)["']/)?.[1] ?? 'config'; const vsion = configContent.match(/vsion\s*:\s*["']([^"']+)["']/)?.[1] ?? '0.0.0'; return { name, vsion }; } function encodeForRuntime(jsonObj: any) { const jsonString = JSON.stringify(jsonObj); const uint8 = new TextEncoder().encode(jsonString); const compressed = Uint8Array.from(lz4.compress(uint8)); const binary = Buffer.from(compressed).toString('latin1'); const base64 = Buffer.from(binary, 'latin1').toString('base64'); return Buffer.from(base64, 'latin1'); } const HOT_UPDATE_TABLE_FILES: { tableKey: string; fileName: string }[] = [ { tableKey: 'Chapter', fileName: 'Chapter.json' }, { tableKey: 'BattleCube', fileName: 'BattleCube.json' }, { tableKey: 'Skill_pool', fileName: 'Skill_pool.json' }, { tableKey: 'skill_pool_use', fileName: 'skill_pool_use.json' }, { tableKey: 'Const_weight', fileName: 'Const_weight.json' }, { tableKey: 'TetriWaveWeight', fileName: 'TetriWaveWeight.json' }, { tableKey: 'Weapon2', fileName: 'Weapon2.json' }, { tableKey: 'Monster', fileName: 'Monster.json' }, { tableKey: 'Monster2', fileName: 'Monster2.json' }, ]; function generateConfigBin() { const projectPath = Editor.Project.path; const configDir = path.join(projectPath, 'assets', 'bundles', 'first', 'config'); const mergeJson: Record = {}; for (const { tableKey, fileName } of HOT_UPDATE_TABLE_FILES) { const fp = path.join(configDir, fileName); if (!fs.existsSync(fp)) { console.warn(`[tools] skip bin generate: missing ${fileName}`); return; } mergeJson[tableKey] = readJson(fp); } const { name, vsion } = resolveConfigNameVersion(projectPath); const safeName = `${name}${vsion}`.replace(/[<>:"/\\|?*]+/g, '_'); const outDir = path.join(projectPath, 'bin'); const outFile = path.join(outDir, `${safeName}.bin`); fs.mkdirSync(outDir, { recursive: true }); fs.writeFileSync(outFile, encodeForRuntime(mergeJson)); console.log(`[tools] generated config bin: ${outFile}`); } function collectJsFiles(dir: string, acc: string[]) { if (!fs.existsSync(dir)) return; const st = fs.statSync(dir); if (!st.isDirectory()) return; const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const e of entries) { const full = path.join(dir, e.name); if (e.isDirectory()) { collectJsFiles(full, acc); } else if (e.isFile() && e.name.endsWith('.js')) { acc.push(full); } } } function collectStripRoots(options: any, result: any): string[] { const roots = new Set(); const add = (p: unknown) => { if (p == null || p === '') return; const s = path.normalize(String(p).replace(/\//g, path.sep)); try { if (fs.existsSync(s)) { const st = fs.statSync(s); if (st.isDirectory()) roots.add(s); } } catch { /* ignore */ } }; add(result?.dest); add(result?.paths?.dir); add(result?.paths?.assets); add(result?.paths?.bundleScripts); add(result?.paths?.subpackages); const projectPath = Editor.Project.path; if (projectPath && options?.buildPath && options?.outputName) { let bp = String(options.buildPath); if (bp.includes('project:')) { bp = path.join(projectPath, bp.replace(/^project:\/\//, '').replace(/^project:/, '')); } add(path.join(bp, options.outputName)); } return [...roots]; } function collectAllJsFiles(roots: string[]): string[] { const files = new Set(); for (const root of roots) { const acc: string[] = []; collectJsFiles(root, acc); for (const f of acc) files.add(path.normalize(f)); } return [...files]; } async function minifyStripConsole(src: string): Promise { const base = { compress: { drop_console: true, drop_debugger: true, passes: 2, }, mangle: false, format: { comments: 'some' as const }, ecma: 2020 as const, }; let out = await minify(src, base); if (out.code != null) return out.code; out = await minify(src, { ...base, module: true }); if (out.code != null) return out.code; throw new Error('terser returned empty'); } async function stripConsoleFromBuildOutput(roots: string[]) { const files = collectAllJsFiles(roots); if (files.length === 0) { console.warn('[tools] stripConsole: no .js under roots', roots); return; } let ok = 0; let fail = 0; for (const file of files) { try { const src = fs.readFileSync(file, 'utf8'); const code = await minifyStripConsole(src); fs.writeFileSync(file, code, 'utf8'); ok++; } catch (err) { fail++; console.warn(`[tools] stripConsole skip (terser error): ${file}`, err); } } console.log(`[tools] stripConsole done: ok=${ok}, fail=${fail}, roots=${roots.join('; ')}`); } const PARALLEL_PRELOAD_SUBPACKAGES = [ { name: 'main' }, { name: 'first' }, { name: 'comm' }, ]; /** 远程资源包:体积大,不计入微信 30M 包体,不得写入 subpackages */ const REMOTE_BUNDLE_NAMES = new Set(['audio', 'tetriMap']); function resolveBuildDest(options: any, result: any): string | null { const candidates: string[] = []; if (result?.dest) candidates.push(String(result.dest)); const projectPath = Editor.Project.path; if (projectPath && options?.buildPath && options?.outputName) { let bp = String(options.buildPath); if (bp.includes('project:')) { bp = path.join(projectPath, bp.replace(/^project:\/\//, '').replace(/^project:/, '')); } candidates.push(path.join(bp, options.outputName)); } for (const c of candidates) { const normalized = path.normalize(c); const gameJson = path.join(normalized, 'game.json'); if (fs.existsSync(gameJson)) return normalized; } return null; } function isWeChatGameJson(gameJson: any): boolean { const provider = gameJson?.plugins?.cocos?.provider; return typeof provider === 'string' && provider.startsWith('wx'); } /** 构建后校正 game.json:仅保留启动三分包并行预下载 */ function patchWeChatGameJson(buildDest: string): void { const gameJsonPath = path.join(buildDest, 'game.json'); if (!fs.existsSync(gameJsonPath)) return; const gameJson = readGameJsonSafe(gameJsonPath); gameJson.parallelPreloadSubpackages = PARALLEL_PRELOAD_SUBPACKAGES; if (Array.isArray(gameJson.subpackages)) { const before = gameJson.subpackages.length; gameJson.subpackages = gameJson.subpackages.filter( (sp: { name?: string }) => !REMOTE_BUNDLE_NAMES.has(sp?.name ?? ''), ); if (gameJson.subpackages.length < before) { console.log('[tools] removed remote bundles from subpackages:', [...REMOTE_BUNDLE_NAMES]); } } // 未使用开放数据域时不要写 openDataContext;空字符串会导致微信开发者工具编译失败 const openDataContext = gameJson.openDataContext; if ( openDataContext == null || (typeof openDataContext === 'string' && !openDataContext.trim()) ) { delete gameJson.openDataContext; } writeJsonFile(gameJsonPath, gameJson); readGameJsonSafe(gameJsonPath); console.log('[tools] patched game.json → parallelPreloadSubpackages main/first/comm, removed empty openDataContext'); } function shouldStripConsole(options: any): boolean { const v = options?.packages?.tools?.stripConsole; if (v === true) return true; if (v === 'true' || v === 1) return true; return false; } export function onBeforeBuild(_options: any, _result: any) { try { console.log('[tools] onBeforeBuild: generate config bin'); generateConfigBin(); } catch (err) { console.error('[tools] onBeforeBuild generate config bin failed:', err); } return true; } export async function onAfterBuild(options: any, result: any) { try { const buildDest = resolveBuildDest(options, result); if (buildDest) { const gameJsonPath = path.join(buildDest, 'game.json'); if (fs.existsSync(gameJsonPath)) { if (options?.platform === 'wechatgame' || isWeChatGameJson(readGameJsonSafe(gameJsonPath))) { patchWeChatGameJson(buildDest); } } } else if (options?.platform === 'wechatgame') { console.warn('[tools] wechatgame build finished but build output dir was not resolved'); } } catch (err) { console.error('[tools] onAfterBuild patch game.json failed:', err); } try { if (shouldStripConsole(options)) { const roots = collectStripRoots(options, result); if (roots.length === 0) { console.warn( '[tools] stripConsole 已勾选但未能解析构建输出目录(检查 result.dest / paths / buildPath+outputName)', ); } else { console.log('[tools] onAfterBuild stripConsole →', roots.join(' | ')); await stripConsoleFromBuildOutput(roots); } } } catch (err) { console.error('[tools] onAfterBuild stripConsole failed:', err); } try { console.log('[tools] onAfterBuild: generate config bin'); generateConfigBin(); } catch (err) { console.error('[tools] onAfterBuild generate config bin failed:', err); } return true; }