@playcraft/devkit 1.0.31-beta.1 → 1.0.31-beta.2
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.
- package/cli/commands/pack.js +8 -6
- package/core/engines/cocos/constants.js +1 -1
- package/core/engines/cocos/dev-server.js +2 -2
- package/core/engines/cocos/fs.js +1 -1
- package/core/engines/cocos/merge.js +2 -2
- package/core/engines/cocos/pack.js +1 -1
- package/core/engines/cocos/preview-concat.js +8 -0
- package/core/engines/cocos/preview-concat.test.js +1 -0
- package/core/engines/cocos/preview-json-hook.js +1 -0
- package/core/engines/cocos/preview-json-pack.js +5 -0
- package/core/engines/cocos/preview-json-pack.test.js +2 -0
- package/core/engines/cocos/theme-assets.js +1 -1
- package/core/engines/web/webpack.common.js +1 -1
- package/core/index.d.ts +1 -0
- package/core/options.js +1 -1
- package/package.json +1 -1
package/cli/commands/pack.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"use strict";const fs=require("fs");const path=require("path");const yazl=require("yazl");// ==================== 配置 ====================
|
|
2
2
|
const projectRoot=process.cwd();/**
|
|
3
|
+
* 内置忽略:即使已提交且未写进 .gitignore / .playcraftignore,打包时也排除。
|
|
4
|
+
*/const BUILTIN_IGNORE_PATTERNS=["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lock","bun.lockb"];/**
|
|
3
5
|
* 解析 appName,依次从 builds.config.js、build.json 或 CLI 参数中获取。
|
|
4
6
|
* 优先级: CLI --app-name > builds.config.js > build.json > 文件夹名称
|
|
5
7
|
* @returns {string}
|
|
@@ -24,10 +26,10 @@ if(line.startsWith("!")){console.log(`\x1b[33m⚠️ 不支持取反模式,
|
|
|
24
26
|
// - 移除前导 ./(gitignore 中 ./foo 等同于 foo)
|
|
25
27
|
let normalized=line.replace(/\/+$/,"");normalized=normalized.replace(/^\.\//g,"");patterns.push(normalized)}return patterns}/**
|
|
26
28
|
* 解析 .gitignore 和 .playcraftignore 文件,合并并去重。
|
|
27
|
-
*
|
|
28
|
-
* @returns {{ patterns: string[], sources: { gitignore: number, playcraftignore: number } }}
|
|
29
|
-
*/function parseIgnoreFiles(){const gitignorePath=path.join(projectRoot,".gitignore");const playcraftignorePath=path.join(projectRoot,".playcraftignore");const gitignorePatterns=parseSingleIgnoreFile(gitignorePath);const playcraftPatterns=parseSingleIgnoreFile(playcraftignorePath);if(gitignorePatterns.length===0&&playcraftPatterns.length===0){console.log("\x1B[33m\u26A0\uFE0F \u672A\u627E\u5230 .gitignore \u6216 .playcraftignore \u6587\u4EF6\uFF0C\u5C06\
|
|
30
|
-
const seen=new Set;const merged=[];for(const p of[...gitignorePatterns,...playcraftPatterns]){if(!seen.has(p)){seen.add(p);merged.push(p)}}return{patterns:merged,sources:{gitignore:gitignorePatterns.length,playcraftignore:playcraftPatterns.length}}}/**
|
|
29
|
+
* 内置规则始终生效;.gitignore 提供基础忽略,.playcraftignore 再补充。
|
|
30
|
+
* @returns {{ patterns: string[], sources: { builtin: number, gitignore: number, playcraftignore: number } }}
|
|
31
|
+
*/function parseIgnoreFiles(){const gitignorePath=path.join(projectRoot,".gitignore");const playcraftignorePath=path.join(projectRoot,".playcraftignore");const gitignorePatterns=parseSingleIgnoreFile(gitignorePath);const playcraftPatterns=parseSingleIgnoreFile(playcraftignorePath);if(gitignorePatterns.length===0&&playcraftPatterns.length===0){console.log("\x1B[33m\u26A0\uFE0F \u672A\u627E\u5230 .gitignore \u6216 .playcraftignore \u6587\u4EF6\uFF0C\u5C06\u4EC5\u5E94\u7528\u5185\u7F6E\u5FFD\u7565\u89C4\u5219\u3002\x1B[0m")}// 合并并去重(内置 → .gitignore → .playcraftignore)
|
|
32
|
+
const seen=new Set;const merged=[];for(const p of[...BUILTIN_IGNORE_PATTERNS,...gitignorePatterns,...playcraftPatterns]){if(!seen.has(p)){seen.add(p);merged.push(p)}}return{patterns:merged,sources:{builtin:BUILTIN_IGNORE_PATTERNS.length,gitignore:gitignorePatterns.length,playcraftignore:playcraftPatterns.length}}}/**
|
|
31
33
|
* 将 gitignore 风格的模式转换为正则表达式。
|
|
32
34
|
*
|
|
33
35
|
* gitignore 语义:
|
|
@@ -75,7 +77,7 @@ const outputDir=path.dirname(outputPath);if(!fs.existsSync(outputDir)){fs.mkdirS
|
|
|
75
77
|
* @returns {string}
|
|
76
78
|
*/function formatSize(bytes){if(bytes<1024)return`${bytes} B`;if(bytes<1024*1024)return`${(bytes/1024).toFixed(2)} KB`;return`${(bytes/(1024*1024)).toFixed(2)} MB`}// ==================== 主流程 ====================
|
|
77
79
|
async function main(){console.log("\x1B[36m\uD83D\uDCE6 playable-scripts \u6253\u5305\x1B[0m\n");// 1. 解析 appName
|
|
78
|
-
const appName=resolveAppName();console.log(` 应用名称: \x1b[1m${appName}\x1b[0m`);// 2.
|
|
79
|
-
const{patterns,sources}=parseIgnoreFiles();const ignoreRegexes=patterns.map(patternToRegex);if(patterns.length>0){const parts=[];if(sources.gitignore>0)parts.push(`${sources.gitignore} 条来自 .gitignore`);if(sources.playcraftignore>0)parts.push(`${sources.playcraftignore} 条来自 .playcraftignore`);console.log(` 忽略规则: \x1b[33m${patterns.length}\x1b[0m 条模式 (${parts.join(", ")})`)}// 3. 收集文件
|
|
80
|
+
const appName=resolveAppName();console.log(` 应用名称: \x1b[1m${appName}\x1b[0m`);// 2. 解析忽略规则(内置 lock 文件 + .gitignore + .playcraftignore)
|
|
81
|
+
const{patterns,sources}=parseIgnoreFiles();const ignoreRegexes=patterns.map(patternToRegex);if(patterns.length>0){const parts=[];if(sources.builtin>0)parts.push(`${sources.builtin} 条内置`);if(sources.gitignore>0)parts.push(`${sources.gitignore} 条来自 .gitignore`);if(sources.playcraftignore>0)parts.push(`${sources.playcraftignore} 条来自 .playcraftignore`);console.log(` 忽略规则: \x1b[33m${patterns.length}\x1b[0m 条模式 (${parts.join(", ")})`)}// 3. 收集文件
|
|
80
82
|
console.log(` 正在扫描项目文件...`);const files=collectFiles(projectRoot,projectRoot,ignoreRegexes);if(files.length===0){console.error("\x1B[31m\u274C \u6CA1\u6709\u53EF\u6253\u5305\u7684\u6587\u4EF6\uFF01\u8BF7\u68C0\u67E5 .playcraftignore \u89C4\u5219\u3002\x1B[0m");process.exit(1)}console.log(` 文件数量: \x1b[32m${files.length}\x1b[0m 个待打包文件`);// 4. 创建 zip 压缩包
|
|
81
83
|
const outDir=resolveOutputDir();const outputPath=path.resolve(projectRoot,outDir,`${appName}.zip`);console.log(` 输出路径: ${outputPath}\n`);console.log(" \u6B63\u5728\u6253\u5305...");try{const{fileCount,zipSize}=await createZip(files,appName,outputPath);console.log(`\n\x1b[32m✅ 打包完成!\x1b[0m`);console.log(` 文件数: ${fileCount}`);console.log(` 大小: ${formatSize(zipSize)}`);console.log(` 输出: ${outputPath}`)}catch(err){console.error(`\n\x1b[31m❌ 打包失败: ${err.message}\x1b[0m`);process.exit(1)}}main();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const ADAPTER_FETCH="adapterFetch";const TO_STRING_EXTNAME=[".txt",".xml",".vsh",".fsh",".atlas",".tmx",".tsx",".json",".ExportJson",".plist",".fnt",".js",".zip"];const TO_SKIP_EXTNAME=[".ico",".html",".css"];const TRANSPARENT_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";const FILE_MAX_SIZE=2*1024*1024*0.8;const THEME_ASSET_EXT=/\.(png|webp|jpe?g|gif|svg|mp3|wav|m4a|ogg|mp4)$/i;module.exports={ADAPTER_FETCH,TO_STRING_EXTNAME,TO_SKIP_EXTNAME,TRANSPARENT_GIF,FILE_MAX_SIZE,THEME_ASSET_EXT};
|
|
1
|
+
"use strict";const ADAPTER_FETCH="adapterFetch";const TO_STRING_EXTNAME=[".txt",".xml",".vsh",".fsh",".atlas",".tmx",".tsx",".json",".ExportJson",".plist",".fnt",".js",".zip"];const TO_SKIP_EXTNAME=[".ico",".html",".css"];const TRANSPARENT_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";const FILE_MAX_SIZE=2*1024*1024*0.8;const THEME_ASSET_EXT=/\.(png|webp|jpe?g|gif|svg|mp3|mpeg|wav|m4a|aac|ogg|mp4)$/i;module.exports={ADAPTER_FETCH,TO_STRING_EXTNAME,TO_SKIP_EXTNAME,TRANSPARENT_GIF,FILE_MAX_SIZE,THEME_ASSET_EXT};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";const fs=require("fs");const http=require("http");const path=require("path");const{spawnCocos,needsXvfb}=require("./cli.js");const{syncGeneratedTheme}=require("./theme-assets.js");const{refreshAssets}=require("./mcp-refresh.js");const{stripAdsdkCjsImport}=require("./strip-social-share.js");function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function request(url,{method="GET",timeout=8000}={}){return new Promise((resolve,reject)=>{const req=http.request(url,{method,timeout},res=>{const chunks=[];res.on("data",c=>chunks.push(c));res.on("end",()=>{resolve({status:res.statusCode||0,body:Buffer.concat(chunks).toString("utf8")})})});req.on("timeout",()=>{req.destroy();reject(new Error(`timeout ${url}`))});req.on("error",reject);req.end()})}function resolvePreviewScene(projectRoot,explicit){if(explicit)return explicit;if(process.env.PREVIEW_SCENE)return process.env.PREVIEW_SCENE;try{const cfgPath=path.join(projectRoot,"settings/cocos.config.json");if(fs.existsSync(cfgPath)){const cfg=JSON.parse(fs.readFileSync(cfgPath,"utf8"));const fromConfig=cfg.builder&&cfg.builder.common&&cfg.builder.common.startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-desktop"]&&cfg.builder.platforms["web-desktop"].startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-mobile"]&&cfg.builder.platforms["web-mobile"].startScene;if(fromConfig)return fromConfig}}catch(_){}const scenesDir=path.join(projectRoot,"assets/scenes");if(fs.existsSync(scenesDir)){const first=fs.readdirSync(scenesDir).find(name=>name.endsWith(".scene"));if(first)return`db://assets/scenes/${first}`}return""}function killSocialShareForDev(projectRoot){const result=stripAdsdkCjsImport(projectRoot);if(result.skipped&&result.reason==="missing"){console.warn("[dev] adsdk CJS missing, skip social-share strip");return}if(result.skipped&&result.reason==="already"){console.log("[dev] social-share import() already stripped");return}if(result.skipped){console.warn("[dev] social-share import() not found in CJS");return}console.log("[dev] stripped social-share import() from adsdk CJS")}function shouldIgnoreWatch(file){if(!file)return false;const base=path.basename(file);if(base===".DS_Store"||base==="theme.generated.ts")return true;if(base.startsWith(".")&&base!==".json5")return true;const ext=path.extname(file).toLowerCase();return ext===".meta"}/**
|
|
1
|
+
"use strict";const fs=require("fs");const http=require("http");const path=require("path");const{spawnCocos,needsXvfb}=require("./cli.js");const{syncGeneratedTheme}=require("./theme-assets.js");const{refreshAssets}=require("./mcp-refresh.js");const{stripAdsdkCjsImport}=require("./strip-social-share.js");const{concatPreviewScripts}=require("./preview-concat.js");const{packPreviewJson}=require("./preview-json-pack.js");function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function request(url,{method="GET",timeout=8000}={}){return new Promise((resolve,reject)=>{const req=http.request(url,{method,timeout},res=>{const chunks=[];res.on("data",c=>chunks.push(c));res.on("end",()=>{resolve({status:res.statusCode||0,body:Buffer.concat(chunks).toString("utf8")})})});req.on("timeout",()=>{req.destroy();reject(new Error(`timeout ${url}`))});req.on("error",reject);req.end()})}function resolvePreviewScene(projectRoot,explicit){if(explicit)return explicit;if(process.env.PREVIEW_SCENE)return process.env.PREVIEW_SCENE;try{const cfgPath=path.join(projectRoot,"settings/cocos.config.json");if(fs.existsSync(cfgPath)){const cfg=JSON.parse(fs.readFileSync(cfgPath,"utf8"));const fromConfig=cfg.builder&&cfg.builder.common&&cfg.builder.common.startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-desktop"]&&cfg.builder.platforms["web-desktop"].startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-mobile"]&&cfg.builder.platforms["web-mobile"].startScene;if(fromConfig)return fromConfig}}catch(_){}const scenesDir=path.join(projectRoot,"assets/scenes");if(fs.existsSync(scenesDir)){const first=fs.readdirSync(scenesDir).find(name=>name.endsWith(".scene"));if(first)return`db://assets/scenes/${first}`}return""}function killSocialShareForDev(projectRoot){const result=stripAdsdkCjsImport(projectRoot);if(result.skipped&&result.reason==="missing"){console.warn("[dev] adsdk CJS missing, skip social-share strip");return}if(result.skipped&&result.reason==="already"){console.log("[dev] social-share import() already stripped");return}if(result.skipped){console.warn("[dev] social-share import() not found in CJS");return}console.log("[dev] stripped social-share import() from adsdk CJS")}function shouldIgnoreWatch(file){if(!file)return false;const base=path.basename(file);if(base===".DS_Store"||base==="theme.generated.ts")return true;if(base.startsWith(".")&&base!==".json5")return true;const ext=path.extname(file).toLowerCase();return ext===".meta"}/**
|
|
2
2
|
* 常驻官方 cocos CLI 预览:start-mcp-server(同一端口既有 / 也有 /mcp)。
|
|
3
|
-
*/async function runCocosDev(opts={}){const projectRoot=opts.projectRoot||process.cwd();const port=Number(opts.port||process.env.PREVIEW_PORT||3000);const timeoutMs=Number(opts.timeoutMs||process.env.DEV_TIMEOUT_MS||180000);const debounceMs=Number(opts.debounceMs||process.env.DEV_DEBOUNCE_MS||400);const cmd=opts.cmd||process.argv[2]||"start";const scene=resolvePreviewScene(projectRoot,opts.scene);const previewUrl=scene?`http://127.0.0.1:${port}/?scene=${encodeURIComponent(scene)}`:`http://127.0.0.1:${port}/`;const watchDirs=["assets","src/theme"].filter(dir=>fs.existsSync(path.join(projectRoot,dir)));async function isPreviewUp(){try{const res=await request(previewUrl,{timeout:1500});return res.status>0&&res.status<500}catch{return false}}async function waitForPreview(){const start=Date.now();let lastLog=0;while(Date.now()-start<timeoutMs){if(await isPreviewUp())return;if(Date.now()-lastLog>=5000){console.log(`[dev] waiting for ${previewUrl}`);lastLog=Date.now()}await sleep(1000)}throw new Error(`preview not ready after ${timeoutMs}ms: ${previewUrl}`)}function printBanner(reused){console.log(`[dev] ${reused?"reusing cocos CLI":"cocos CLI ready"}`);console.log(`[dev] iframe → ${previewUrl}`);console.log(`[dev] mcp → http://127.0.0.1:${port}/mcp`);console.log(`[dev] watch ${watchDirs.map(d=>`${d}/`).join(" ")}`)}function syncThemeOnce(){try{const result=syncGeneratedTheme(projectRoot);if(!result){console.log("[dev] no theme entry; skip generated module");return false}console.log(`[dev] synced theme ${result.themeName}${result.changed===false?" (unchanged)":""}`);return result.changed!==false}catch(syncErr){console.warn(`[dev] theme sync skipped: ${syncErr.message}`);return false}}async function compile({fatal=true}={}){if(!(await isPreviewUp())){console.error(`[dev] preview is down: ${previewUrl}`);if(fatal){console.error("[dev] Run npm run dev first.");process.exit(1)}return}console.log(`[dev] assets-refresh db://assets`);try{const res=await refreshAssets(port,"db://assets");const err=res.parsed&&(res.parsed.error||res.parsed.result&&res.parsed.result.isError);console.log(`[dev] ${res.status}${err?" error":""}`);if(res.status===404){console.error("[dev] /mcp \u4E0D\u5B58\u5728\u3002\u8BF7\u505C\u6389\u5F53\u524D\u9884\u89C8\uFF0C\u91CD\u65B0 npm run dev\uFF08\u4F1A\u8D77 start-mcp-server\uFF09")}if((res.status>=400||err)&&fatal)process.exit(1)}catch(err){console.error(`[dev] compile failed: ${err.message}`);if(fatal)process.exit(1)}}function watchAndCompile(){let timer=null;let compiling=false;let pending=null;const queue=rel=>{pending=rel;if(timer)clearTimeout(timer);timer=setTimeout(()=>{timer=null;run()},debounceMs)};const run=async()=>{if(compiling)return;const rel=pending;pending=null;compiling=true;if(rel)console.log(`[dev] change ${rel}`);try{if(!rel||rel.startsWith("src/theme")){syncThemeOnce()}await compile({fatal:false})}finally{compiling=false;if(pending)queue(pending)}};for(const dir of watchDirs){const abs=path.join(projectRoot,dir);fs.watch(abs,{recursive:true},(_event,file)=>{if(shouldIgnoreWatch(file))return;const rel=path.join(dir,file||"").replace(/\\/g,"/");queue(rel)})}}function holdUntilExit(child){const stop=()=>{if(child&&child.exitCode==null){child.kill("SIGTERM")}process.exit(0)};process.on("SIGINT",stop);process.on("SIGTERM",stop);if(child){child.on("exit",(code,signal)=>{console.log(`[dev] cocos CLI exited (${signal||code})`);process.exit(code==null?1:code)});return}console.log("[dev] CLI already running; Ctrl+C leaves it open");setInterval(()=>{},60*1000)}async function start(){if(await isPreviewUp()){printBanner(true);const synced=syncThemeOnce();if(synced)await compile({fatal:false});watchAndCompile();holdUntilExit(null);return}if(needsXvfb()){console.log("[dev] linux, wrapping xvfb-run -a")}const args=["--no-interactive","start-mcp-server","--project",projectRoot,"--port",String(port)];if(scene){console.log(`[dev] start scene ${scene}`)}console.log(`[dev] cocos ${args.join(" ")}`);const child=spawnCocos(args,{cwd:projectRoot,env:process.env,stdio:"inherit"});child.on("error",err=>{console.error(err);process.exit(1)});try{await waitForPreview()}catch(err){console.error(`[dev] ${err.message}`);child.kill("SIGTERM");process.exit(1)}printBanner(false);const synced=syncThemeOnce();if(synced)await compile({fatal:false});watchAndCompile();holdUntilExit(child)}killSocialShareForDev(projectRoot);if(cmd==="compile"||cmd==="refresh"){await compile();return}if(cmd==="start"||cmd==="dev"){await start();return}console.error(`[dev] unknown command: ${cmd}`);console.error("[dev] usage: playable-scripts dev [start|compile]");process.exit(1)}module.exports={runCocosDev};
|
|
3
|
+
*/async function runCocosDev(opts={}){const projectRoot=opts.projectRoot||process.cwd();const port=Number(opts.port||process.env.PREVIEW_PORT||3000);const timeoutMs=Number(opts.timeoutMs||process.env.DEV_TIMEOUT_MS||180000);const debounceMs=Number(opts.debounceMs||process.env.DEV_DEBOUNCE_MS||400);const cmd=opts.cmd||process.argv[2]||"start";const scene=resolvePreviewScene(projectRoot,opts.scene);const previewUrl=scene?`http://127.0.0.1:${port}/?scene=${encodeURIComponent(scene)}`:`http://127.0.0.1:${port}/`;const watchDirs=["assets","src/theme"].filter(dir=>fs.existsSync(path.join(projectRoot,dir)));async function isPreviewUp(){try{const res=await request(previewUrl,{timeout:1500});return res.status>0&&res.status<500}catch{return false}}async function waitForPreview(){const start=Date.now();let lastLog=0;while(Date.now()-start<timeoutMs){if(await isPreviewUp())return;if(Date.now()-lastLog>=5000){console.log(`[dev] waiting for ${previewUrl}`);lastLog=Date.now()}await sleep(1000)}throw new Error(`preview not ready after ${timeoutMs}ms: ${previewUrl}`)}function printBanner(reused){console.log(`[dev] ${reused?"reusing cocos CLI":"cocos CLI ready"}`);console.log(`[dev] iframe → ${previewUrl}`);console.log(`[dev] mcp → http://127.0.0.1:${port}/mcp`);console.log(`[dev] watch ${watchDirs.map(d=>`${d}/`).join(" ")}`)}function syncThemeOnce(){try{const result=syncGeneratedTheme(projectRoot);if(!result){console.log("[dev] no theme entry; skip generated module");return false}console.log(`[dev] synced theme ${result.themeName}${result.changed===false?" (unchanged)":""}`);return result.changed!==false}catch(syncErr){console.warn(`[dev] theme sync skipped: ${syncErr.message}`);return false}}async function compile({fatal=true}={}){if(!(await isPreviewUp())){console.error(`[dev] preview is down: ${previewUrl}`);if(fatal){console.error("[dev] Run npm run dev first.");process.exit(1)}return}console.log(`[dev] assets-refresh db://assets`);try{const res=await refreshAssets(port,"db://assets");const err=res.parsed&&(res.parsed.error||res.parsed.result&&res.parsed.result.isError);console.log(`[dev] ${res.status}${err?" error":""}`);if(res.status===404){console.error("[dev] /mcp \u4E0D\u5B58\u5728\u3002\u8BF7\u505C\u6389\u5F53\u524D\u9884\u89C8\uFF0C\u91CD\u65B0 npm run dev\uFF08\u4F1A\u8D77 start-mcp-server\uFF09")}if((res.status>=400||err)&&fatal)process.exit(1)}catch(err){console.error(`[dev] compile failed: ${err.message}`);if(fatal)process.exit(1)}await bundlePreviewAssets()}async function bundlePreviewAssets(){bundlePreviewScripts();try{const result=await packPreviewJson(projectRoot,{previewOrigin:`http://127.0.0.1:${port}`});if(!result)return;const kb=Math.max(1,Math.round(result.bytes/1024));console.log(`[dev] preview json ${result.files} → 1 pack (${kb} kB)`)}catch(err){console.warn(`[dev] preview json pack skipped: ${err.message}`)}}function bundlePreviewScripts(){try{const result=concatPreviewScripts(projectRoot);if(!result)return;const kb=Math.max(1,Math.round(result.bytes/1024));console.log(`[dev] preview scripts ${result.modules} → 1 bundle (${kb} kB)`)}catch(err){console.warn(`[dev] preview script concat skipped: ${err.message}`)}}function watchAndCompile(){let timer=null;let compiling=false;let pending=null;const queue=rel=>{pending=rel;if(timer)clearTimeout(timer);timer=setTimeout(()=>{timer=null;run()},debounceMs)};const run=async()=>{if(compiling)return;const rel=pending;pending=null;compiling=true;if(rel)console.log(`[dev] change ${rel}`);try{if(!rel||rel.startsWith("src/theme")){syncThemeOnce()}await compile({fatal:false})}finally{compiling=false;if(pending)queue(pending)}};for(const dir of watchDirs){const abs=path.join(projectRoot,dir);fs.watch(abs,{recursive:true},(_event,file)=>{if(shouldIgnoreWatch(file))return;const rel=path.join(dir,file||"").replace(/\\/g,"/");queue(rel)})}}function holdUntilExit(child){const stop=()=>{if(child&&child.exitCode==null){child.kill("SIGTERM")}process.exit(0)};process.on("SIGINT",stop);process.on("SIGTERM",stop);if(child){child.on("exit",(code,signal)=>{console.log(`[dev] cocos CLI exited (${signal||code})`);process.exit(code==null?1:code)});return}console.log("[dev] CLI already running; Ctrl+C leaves it open");setInterval(()=>{},60*1000)}async function start(){if(await isPreviewUp()){printBanner(true);const synced=syncThemeOnce();if(synced)await compile({fatal:false});else await bundlePreviewAssets();watchAndCompile();holdUntilExit(null);return}if(needsXvfb()){console.log("[dev] linux, wrapping xvfb-run -a")}const args=["--no-interactive","start-mcp-server","--project",projectRoot,"--port",String(port)];if(scene){console.log(`[dev] start scene ${scene}`)}console.log(`[dev] cocos ${args.join(" ")}`);const child=spawnCocos(args,{cwd:projectRoot,env:process.env,stdio:"inherit"});child.on("error",err=>{console.error(err);process.exit(1)});try{await waitForPreview()}catch(err){console.error(`[dev] ${err.message}`);child.kill("SIGTERM");process.exit(1)}printBanner(false);const synced=syncThemeOnce();if(synced)await compile({fatal:false});else await bundlePreviewAssets();watchAndCompile();holdUntilExit(child)}killSocialShareForDev(projectRoot);if(cmd==="compile"||cmd==="refresh"){await compile();return}if(cmd==="start"||cmd==="dev"){await start();return}console.error(`[dev] unknown command: ${cmd}`);console.error("[dev] usage: playable-scripts dev [start|compile]");process.exit(1)}module.exports={runCocosDev};
|
package/core/engines/cocos/fs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const fs=require("fs");const path=require("path");const{lookup}=require("mime-types");const{ADAPTER_FETCH,TO_STRING_EXTNAME,TO_SKIP_EXTNAME}=require("./constants");function getRealPath(pathStr){return pathStr.indexOf("\\")!==-1?pathStr.replace(/\\/g,"/"):pathStr}function getAllFilesFromDir(dirPath){let files=[];if(!fs.existsSync(dirPath))return files;for(const fileName of fs.readdirSync(dirPath)){const filePath=path.join(dirPath,fileName);const stat=fs.statSync(filePath);if(stat.isDirectory())files=files.concat(getAllFilesFromDir(filePath));else files.push(filePath)}return files}function getBase64FromFile(filePath){const
|
|
1
|
+
"use strict";const fs=require("fs");const path=require("path");const{lookup}=require("mime-types");const{ADAPTER_FETCH,TO_STRING_EXTNAME,TO_SKIP_EXTNAME}=require("./constants");function getRealPath(pathStr){return pathStr.indexOf("\\")!==-1?pathStr.replace(/\\/g,"/"):pathStr}function getAllFilesFromDir(dirPath){let files=[];if(!fs.existsSync(dirPath))return files;for(const fileName of fs.readdirSync(dirPath)){const filePath=path.join(dirPath,fileName);const stat=fs.statSync(filePath);if(stat.isDirectory())files=files.concat(getAllFilesFromDir(filePath));else files.push(filePath)}return files}function sniffAudioMime(buf){if(!buf||buf.length<4)return"";if(buf[0]===73&&buf[1]===68&&buf[2]===51)return"audio/mpeg";if(buf[0]===255&&(buf[1]&224)===224)return"audio/mpeg";if(buf[0]===79&&buf[1]===103&&buf[2]===103&&buf[3]===83)return"audio/ogg";if(buf[0]===82&&buf[1]===73&&buf[2]===70&&buf[3]===70)return"audio/wav";if(buf[4]===102&&buf[5]===116&&buf[6]===121&&buf[7]===112)return"audio/mp4";return""}function getBase64FromFile(filePath){const buf=fs.readFileSync(filePath);const lookedUp=lookup(filePath)||"";const mime=(lookedUp.startsWith("audio/")?lookedUp:sniffAudioMime(buf)||lookedUp)||"application/octet-stream";return`data:${mime};base64,${buf.toString("base64")}`}function getTargetResData(filePath){const fileExtname=path.extname(filePath);if(!fileExtname)return"";if(TO_STRING_EXTNAME.includes(fileExtname)){return fs.readFileSync(filePath,"utf-8")}return getBase64FromFile(filePath)}function removeXMLHttpRequest(codeStr){return codeStr.replace(/XMLHttpRequest/g,ADAPTER_FETCH)}async function getResourceMapper({dirPath,rmHttp=false,mountCbFn,skipFiles=[]}){const resMapper={};const readPkgPath=getRealPath(`${dirPath}/`);for(const filePath of getAllFilesFromDir(dirPath)){const fileExtname=path.extname(filePath);if(TO_SKIP_EXTNAME.includes(fileExtname))continue;if(skipFiles.includes(filePath))continue;const objKey=getRealPath(filePath).replace(readPkgPath,"");let data=getTargetResData(filePath);if(mountCbFn)data=mountCbFn(objKey,data);if(rmHttp&&fileExtname===".js")data=removeXMLHttpRequest(data);resMapper[objKey]=data}return{resMapper}}module.exports={getRealPath,getAllFilesFromDir,getBase64FromFile,getTargetResData,getResourceMapper,removeXMLHttpRequest,sniffAudioMime};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";const fs=require("fs");const path=require("path");const{load}=require("cheerio");const{deflate}=require("pako");const{getResourceMapper,getBase64FromFile}=require("./fs");const{TRANSPARENT_GIF}=require("./constants");function readInject(rel){return fs.readFileSync(path.join(__dirname,rel),"utf8")}function paddingStyleTags($,originPkgPath,enableSplash){$("link[type=\"text/css\"]").toArray().forEach(item=>{const href=$(item).attr("href");if(!href)return;const cssPath=path.join(originPkgPath,href);if(!fs.existsSync(cssPath))return;const cssStr=fs.readFileSync(cssPath,"utf-8");$(`<style>${cssStr}</style>`).appendTo("head")});if(!enableSplash){$("<style>#splash .progress-bar{opacity:0;visibility:hidden}</style>").appendTo("head")}$("link[type=\"text/css\"]").remove();$("head").find("style").each((_index,elem)=>{const cssUrlReg=/url\("?'?.*"?'?\)/g;let styleTagStr=$(elem).html()||"";const matchStrList=styleTagStr.match(cssUrlReg);if(!matchStrList)return;matchStrList.forEach(str=>{const imgUrl=str.replace(/"|'|url|\(|\)/g,"");const imgPath=path.join(originPkgPath,imgUrl);const imgBase64=enableSplash&&fs.existsSync(imgPath)?getBase64FromFile(imgPath):TRANSPARENT_GIF;styleTagStr=styleTagStr.replace(str,`url(${imgBase64})`)});$(elem).html(styleTagStr)})}function paddingScriptTags($,originPkgPath){let scriptTags="";$("script[type=\"systemjs-importmap\"]").toArray().forEach(item=>{const href=$(item).attr("src");if(!href)return;const srcPath=path.join(originPkgPath,href);if(!fs.existsSync(srcPath))return;scriptTags+=`<script type="systemjs-importmap">${fs.readFileSync(srcPath,"utf-8")}</script>`});$("head link").remove();$("body script").remove();if(scriptTags)$(scriptTags).appendTo("body")}function getJsListFromSettingsJson(data){const jsonData=JSON.parse(data);jsonData.plugins={jsList:[],...jsonData.plugins};const jsList=[...jsonData.plugins.jsList];jsonData.plugins.jsList=[];return{jsList,settingsData:jsonData}}function getJsListFromSettingsJs(data){const originData={jsList:[],settingsData:data};const settingsStrList=data.split("jsList:");if(settingsStrList.length<2)return originData;const settingsStr=settingsStrList.pop()||"";const jsListStrRegExp=/\[[^\]]*\]/.exec(settingsStr);if(!jsListStrRegExp)return originData;const jsListStr=jsListStrRegExp[0];return{jsList:JSON.parse(jsListStr),settingsData:data.replace(jsListStr,"[]")}}/**
|
|
1
|
+
"use strict";const fs=require("fs");const path=require("path");const{load}=require("cheerio");const{deflate}=require("pako");const{getResourceMapper,getBase64FromFile}=require("./fs");const{TRANSPARENT_GIF}=require("./constants");function readInject(rel){return fs.readFileSync(path.join(__dirname,rel),"utf8")}function paddingStyleTags($,originPkgPath,enableSplash){$("link[type=\"text/css\"]").toArray().forEach(item=>{const href=$(item).attr("href");if(!href)return;const cssPath=path.join(originPkgPath,href);if(!fs.existsSync(cssPath))return;const cssStr=fs.readFileSync(cssPath,"utf-8");$(`<style>${cssStr}</style>`).appendTo("head")});if(!enableSplash){$("<style>#splash,#splash .progress-bar{display:none!important;opacity:0;visibility:hidden}</style>").appendTo("head")}$("link[type=\"text/css\"]").remove();$("head").find("style").each((_index,elem)=>{const cssUrlReg=/url\("?'?.*"?'?\)/g;let styleTagStr=$(elem).html()||"";const matchStrList=styleTagStr.match(cssUrlReg);if(!matchStrList)return;matchStrList.forEach(str=>{const imgUrl=str.replace(/"|'|url|\(|\)/g,"");const imgPath=path.join(originPkgPath,imgUrl);const imgBase64=enableSplash&&fs.existsSync(imgPath)?getBase64FromFile(imgPath):TRANSPARENT_GIF;styleTagStr=styleTagStr.replace(str,`url(${imgBase64})`)});$(elem).html(styleTagStr)})}function paddingScriptTags($,originPkgPath){let scriptTags="";$("script[type=\"systemjs-importmap\"]").toArray().forEach(item=>{const href=$(item).attr("src");if(!href)return;const srcPath=path.join(originPkgPath,href);if(!fs.existsSync(srcPath))return;scriptTags+=`<script type="systemjs-importmap">${fs.readFileSync(srcPath,"utf-8")}</script>`});$("head link").remove();$("body script").remove();if(scriptTags)$(scriptTags).appendTo("body")}function getJsListFromSettingsJson(data){const jsonData=JSON.parse(data);jsonData.plugins={jsList:[],...jsonData.plugins};const jsList=[...jsonData.plugins.jsList];jsonData.plugins.jsList=[];return{jsList,settingsData:jsonData}}function stripSplashScreen(settingsData){if(!settingsData||!settingsData.splashScreen)return settingsData;settingsData.splashScreen.totalTime=0;settingsData.splashScreen.logo={type:"none",base64:""};return settingsData}function getJsListFromSettingsJs(data){const originData={jsList:[],settingsData:data};const settingsStrList=data.split("jsList:");if(settingsStrList.length<2)return originData;const settingsStr=settingsStrList.pop()||"";const jsListStrRegExp=/\[[^\]]*\]/.exec(settingsStr);if(!jsListStrRegExp)return originData;const jsListStr=jsListStrRegExp[0];return{jsList:JSON.parse(jsListStr),settingsData:data.replace(jsListStr,"[]")}}/**
|
|
2
2
|
* Inline a Creator 3.x web-mobile folder into a single HTML file.
|
|
3
3
|
* @param {string} originPkgPath - Absolute path to build/web-mobile
|
|
4
4
|
* @param {string} singleFilePath - Output html path
|
|
5
5
|
* @param {{ enableSplash?: boolean, isZip?: boolean }} [opts]
|
|
6
|
-
*/async function mergeWebMobile(originPkgPath,singleFilePath,opts={}){const enableSplash=opts.enableSplash
|
|
6
|
+
*/async function mergeWebMobile(originPkgPath,singleFilePath,opts={}){const enableSplash=opts.enableSplash===true;const isZip=opts.isZip!==false;const htmlPath=path.join(originPkgPath,"index.html");if(!fs.existsSync(htmlPath)){throw new Error(`[cocos] web-mobile index.html not found: ${htmlPath}`)}const $=load(fs.readFileSync(htmlPath,"utf-8"));paddingStyleTags($,originPkgPath,enableSplash);paddingScriptTags($,originPkgPath);let pluginJsList=[];const{resMapper}=await getResourceMapper({dirPath:originPkgPath,rmHttp:true,mountCbFn:(objKey,data)=>{if(objKey.indexOf("src/settings.json")!==-1){const{jsList,settingsData}=getJsListFromSettingsJson(data);pluginJsList=jsList;if(!enableSplash)stripSplashScreen(settingsData);return JSON.stringify(settingsData)}if(objKey.indexOf("src/settings.js")!==-1){const{jsList,settingsData}=getJsListFromSettingsJs(data);pluginJsList=jsList;return settingsData}return data}});let resStr=JSON.stringify(resMapper);let compDiff=0;if(isZip){const zip=deflate(resStr);const zipStr=Buffer.from(zip).toString("base64");console.log("[cocos] origin pkg",resStr.length,"compressed",zipStr.length);if(zipStr.length<resStr.length){compDiff=resStr.length-zipStr.length;resStr=zipStr}}if(compDiff>0){$(`<script data-id="jszip">${readInject("injects/libs/pako.js")}</script>`).appendTo("body");$(`<script data-id="adapter-zip-0">window.__adapter_zip__="${resStr}";</script>`).appendTo("body")}else{$(`<script data-id="adapter-resource-0">window.__adapter_resource__=${resStr}</script>`).appendTo("body")}$(`<script data-id="adapter-plugins">window.__adapter_plugins__=${JSON.stringify(pluginJsList)}</script>`).appendTo("body");$(`<script data-id="adapter-init">${readInject("injects/3x/init.js")}</script>`).appendTo("body");$(`<script data-id="adapter-main">${readInject("injects/3x/main.js")}</script>`).appendTo("body");fs.mkdirSync(path.dirname(singleFilePath),{recursive:true});fs.writeFileSync(singleFilePath,$.html());const kb=(fs.statSync(singleFilePath).size/1024).toFixed(1);console.log(`[cocos] single-file template ${kb}kb → ${singleFilePath}`);return{resMapper,compDiff,singleFilePath}}module.exports={mergeWebMobile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const fs=require("fs");const path=require("path");const{options}=require("../../options.js");const{mergeOptions}=require("../../utils/mergeOptions.js");const{logOptions}=require("../../utils/logOptions.js");const{resolveCreatorOutputDir}=require("./creator-cli");const{runCocosEngineBuild}=require("./cli-build");const{mergeWebMobile}=require("./merge");const{detectCurrentTheme,loadThemePayload,writeGeneratedThemeModule}=require("./theme-assets");const{emitChannel}=require("../../artifacts/emit");const{isSocialMediaNetwork,stripSocialShareFromDir}=require("./strip-social-share");function resolveWebMobileDir(root,buildOptions){const cocos=buildOptions.cocos||{};const fromCreator=resolveCreatorOutputDir(root,cocos.buildConfig||"build-configs/web-mobile.json");const explicit=cocos.webMobileDir?path.resolve(root,cocos.webMobileDir):null;if(cocos.skipEngineBuild){return explicit||fromCreator||path.resolve(root,"dist/web-mobile")}if(fromCreator){if(explicit&&explicit!==fromCreator){console.warn(`[cocos] webMobileDir (${path.relative(root,explicit)}) != Creator output (${path.relative(root,fromCreator)}); using Creator buildPath/outputName`)}return fromCreator}return explicit||path.resolve(root,"dist/web-mobile")}async function mergeTemplate(root,buildOptions){const webMobileDir=resolveWebMobileDir(root,buildOptions);const singleFilePath=path.join(root,"build","single-file-3x.html");await mergeWebMobile(webMobileDir,singleFilePath);return fs.readFileSync(singleFilePath,"utf8")}function resolveThemeName(root,buildOptions,themeConfig){return buildOptions.themeName||detectCurrentTheme(root,themeConfig)||"default"}function loadBuildsThemeConfig(root){const configPath=path.join(root,"builds.config.js");if(!fs.existsSync(configPath))return{sourceDir:"src/theme",entryFile:"src/theme/index.ts"};try{delete require.cache[configPath];const config=require(configPath);return{sourceDir:"src/theme",entryFile:"src/theme/index.ts",...(config.themes||{})}}catch{return{sourceDir:"src/theme",entryFile:"src/theme/index.ts"}}}function stripPackedChannel(outDir,network){if(isSocialMediaNetwork(network)){console.log("[cocos] social_media: keep AiX hooks (inject IIFE later)");return}const packed=stripSocialShareFromDir(outDir);console.log(`[cocos] stripped social-share from ${packed.changed}/${packed.files} files in ${path.relative(process.cwd(),outDir)||"."}`)}async function prepareCocosTemplate(customOptions){const buildOptions=mergeOptions(options,customOptions);const root=process.cwd();await runCocosEngineBuild(root,buildOptions);return mergeTemplate(root,buildOptions)}async function emitCocosChannel(templateHtml,customOptions){const buildOptions=mergeOptions(options,customOptions);const root=process.cwd();const themeConfig=loadBuildsThemeConfig(root);const themeName=resolveThemeName(root,buildOptions,themeConfig);let themePayload={themeName,mergedData:{},i18nOverride:{},assetRecordByPath:{}};try{themePayload=loadThemePayload(root,themeName,themeConfig)}catch(err){console.warn(`[cocos] theme payload skipped: ${err.message}`)}const generated=buildOptions.cocos&&buildOptions.cocos.generatedThemeFile||"assets/scripts/platform/theme.generated.ts";writeGeneratedThemeModule(path.join(root,generated),themePayload);const outDir=path.resolve(root,buildOptions.outDir);await emitChannel({templateHtml,buildOptions,themePayload,outDir});stripPackedChannel(outDir,buildOptions.network)}async function runCocosBuild(customOptions){const buildOptions=mergeOptions(options,customOptions);logOptions(buildOptions);const templateHtml=await prepareCocosTemplate(buildOptions);await emitCocosChannel(templateHtml,customOptions)}async function packCocosBatch({config,themes,tasks,outputDir,projectRoot,isChannelFold2Zip}){const buildOptionsBase=mergeOptions(options,{engine:"cocos",googlePlayUrl:config.googlePlayUrl,appStoreUrl:config.appStoreUrl,isChannelFold2Zip,obfuscateLevel:config.obfuscateLevel,fflateCompression:config.fflateCompression});if(config.cocos)Object.assign(buildOptionsBase.cocos,config.cocos);await runCocosEngineBuild(projectRoot,buildOptionsBase);const templateHtml=await mergeTemplate(projectRoot,buildOptionsBase);const themeConfig=config.themes||loadBuildsThemeConfig(projectRoot);const results=[];for(const theme of themes){let themePayload;try{themePayload=loadThemePayload(projectRoot,theme,themeConfig)}catch(err){console.error(`[cocos] theme ${theme}: ${err.message}`);for(const task of tasks){results.push({success:false,theme,channel:task.channel,orientation:task.orientation,error:err.message})}continue}for(const task of tasks){const orientationValue=task.orientation||"both";const fileName=config.naming&&typeof config.naming.generator==="function"?config.naming.generator(theme,task.channel):`${theme}-${task.channel}`;const tempDir=path.join(projectRoot,`${config.build.tempDirPrefix||"dist-temp"}-cocos-${theme}-${task.channel}-${orientationValue}`);try{const channelOptions=mergeOptions(buildOptionsBase,{network:task.channel,playcraftOrientationValue:orientationValue,filename:fileName||options.filename,outDir:tempDir,isChannelFold2Zip});await emitChannel({templateHtml,buildOptions:channelOptions,themePayload,outDir:tempDir});stripPackedChannel(tempDir,task.channel);const themeDir=path.join(outputDir,theme);fs.mkdirSync(themeDir,{recursive:true});for(const file of fs.readdirSync(tempDir)){const src=path.join(tempDir,file);if(fs.statSync(src).isDirectory())continue;fs.copyFileSync(src,path.join(themeDir,file))}results.push({success:true,theme,channel:task.channel,orientation:orientationValue})}catch(error){results.push({success:false,theme,channel:task.channel,orientation:orientationValue,error:error.message})}finally{if(config.build.cleanTemp!==false&&fs.existsSync(tempDir)){fs.rmSync(tempDir,{recursive:true,force:true})}}}}return results}async function syncThemeForPreview(projectRoot,themeName,themeConfig,generatedRel){const payload=loadThemePayload(projectRoot,themeName,themeConfig);writeGeneratedThemeModule(path.join(projectRoot,generatedRel),payload);return payload}module.exports={runCocosBuild,prepareCocosTemplate,emitCocosChannel,packCocosBatch,mergeTemplate,syncThemeForPreview};
|
|
1
|
+
"use strict";const fs=require("fs");const path=require("path");const{options}=require("../../options.js");const{mergeOptions}=require("../../utils/mergeOptions.js");const{logOptions}=require("../../utils/logOptions.js");const{resolveCreatorOutputDir}=require("./creator-cli");const{runCocosEngineBuild}=require("./cli-build");const{mergeWebMobile}=require("./merge");const{detectCurrentTheme,loadThemePayload,writeGeneratedThemeModule}=require("./theme-assets");const{emitChannel}=require("../../artifacts/emit");const{isSocialMediaNetwork,stripSocialShareFromDir}=require("./strip-social-share");function resolveWebMobileDir(root,buildOptions){const cocos=buildOptions.cocos||{};const fromCreator=resolveCreatorOutputDir(root,cocos.buildConfig||"build-configs/web-mobile.json");const explicit=cocos.webMobileDir?path.resolve(root,cocos.webMobileDir):null;if(cocos.skipEngineBuild){return explicit||fromCreator||path.resolve(root,"dist/web-mobile")}if(fromCreator){if(explicit&&explicit!==fromCreator){console.warn(`[cocos] webMobileDir (${path.relative(root,explicit)}) != Creator output (${path.relative(root,fromCreator)}); using Creator buildPath/outputName`)}return fromCreator}return explicit||path.resolve(root,"dist/web-mobile")}async function mergeTemplate(root,buildOptions){const webMobileDir=resolveWebMobileDir(root,buildOptions);const singleFilePath=path.join(root,"build","single-file-3x.html");await mergeWebMobile(webMobileDir,singleFilePath,{enableSplash:!!(buildOptions.cocos&&buildOptions.cocos.enableSplash)});return fs.readFileSync(singleFilePath,"utf8")}function resolveThemeName(root,buildOptions,themeConfig){return buildOptions.themeName||detectCurrentTheme(root,themeConfig)||"default"}function loadBuildsThemeConfig(root){const configPath=path.join(root,"builds.config.js");if(!fs.existsSync(configPath))return{sourceDir:"src/theme",entryFile:"src/theme/index.ts"};try{delete require.cache[configPath];const config=require(configPath);return{sourceDir:"src/theme",entryFile:"src/theme/index.ts",...(config.themes||{})}}catch{return{sourceDir:"src/theme",entryFile:"src/theme/index.ts"}}}function stripPackedChannel(outDir,network){if(isSocialMediaNetwork(network)){console.log("[cocos] social_media: keep AiX hooks (inject IIFE later)");return}const packed=stripSocialShareFromDir(outDir);console.log(`[cocos] stripped social-share from ${packed.changed}/${packed.files} files in ${path.relative(process.cwd(),outDir)||"."}`)}async function prepareCocosTemplate(customOptions){const buildOptions=mergeOptions(options,customOptions);const root=process.cwd();await runCocosEngineBuild(root,buildOptions);return mergeTemplate(root,buildOptions)}async function emitCocosChannel(templateHtml,customOptions){const buildOptions=mergeOptions(options,customOptions);const root=process.cwd();const themeConfig=loadBuildsThemeConfig(root);const themeName=resolveThemeName(root,buildOptions,themeConfig);let themePayload={themeName,mergedData:{},i18nOverride:{},assetRecordByPath:{}};try{themePayload=loadThemePayload(root,themeName,themeConfig)}catch(err){console.warn(`[cocos] theme payload skipped: ${err.message}`)}const generated=buildOptions.cocos&&buildOptions.cocos.generatedThemeFile||"assets/scripts/platform/theme.generated.ts";writeGeneratedThemeModule(path.join(root,generated),themePayload);const outDir=path.resolve(root,buildOptions.outDir);await emitChannel({templateHtml,buildOptions,themePayload,outDir});stripPackedChannel(outDir,buildOptions.network)}async function runCocosBuild(customOptions){const buildOptions=mergeOptions(options,customOptions);logOptions(buildOptions);const templateHtml=await prepareCocosTemplate(buildOptions);await emitCocosChannel(templateHtml,customOptions)}async function packCocosBatch({config,themes,tasks,outputDir,projectRoot,isChannelFold2Zip}){const buildOptionsBase=mergeOptions(options,{engine:"cocos",googlePlayUrl:config.googlePlayUrl,appStoreUrl:config.appStoreUrl,isChannelFold2Zip,obfuscateLevel:config.obfuscateLevel,fflateCompression:config.fflateCompression});if(config.cocos)Object.assign(buildOptionsBase.cocos,config.cocos);await runCocosEngineBuild(projectRoot,buildOptionsBase);const templateHtml=await mergeTemplate(projectRoot,buildOptionsBase);const themeConfig=config.themes||loadBuildsThemeConfig(projectRoot);const results=[];for(const theme of themes){let themePayload;try{themePayload=loadThemePayload(projectRoot,theme,themeConfig)}catch(err){console.error(`[cocos] theme ${theme}: ${err.message}`);for(const task of tasks){results.push({success:false,theme,channel:task.channel,orientation:task.orientation,error:err.message})}continue}for(const task of tasks){const orientationValue=task.orientation||"both";const fileName=config.naming&&typeof config.naming.generator==="function"?config.naming.generator(theme,task.channel):`${theme}-${task.channel}`;const tempDir=path.join(projectRoot,`${config.build.tempDirPrefix||"dist-temp"}-cocos-${theme}-${task.channel}-${orientationValue}`);try{const channelOptions=mergeOptions(buildOptionsBase,{network:task.channel,playcraftOrientationValue:orientationValue,filename:fileName||options.filename,outDir:tempDir,isChannelFold2Zip});await emitChannel({templateHtml,buildOptions:channelOptions,themePayload,outDir:tempDir});stripPackedChannel(tempDir,task.channel);const themeDir=path.join(outputDir,theme);fs.mkdirSync(themeDir,{recursive:true});for(const file of fs.readdirSync(tempDir)){const src=path.join(tempDir,file);if(fs.statSync(src).isDirectory())continue;fs.copyFileSync(src,path.join(themeDir,file))}results.push({success:true,theme,channel:task.channel,orientation:orientationValue})}catch(error){results.push({success:false,theme,channel:task.channel,orientation:orientationValue,error:error.message})}finally{if(config.build.cleanTemp!==false&&fs.existsSync(tempDir)){fs.rmSync(tempDir,{recursive:true,force:true})}}}}return results}async function syncThemeForPreview(projectRoot,themeName,themeConfig,generatedRel){const payload=loadThemePayload(projectRoot,themeName,themeConfig);writeGeneratedThemeModule(path.join(projectRoot,generatedRel),payload);return payload}module.exports={runCocosBuild,prepareCocosTemplate,emitCocosChannel,packCocosBatch,mergeTemplate,syncThemeForPreview};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";const fs=require("fs");const path=require("path");const ENTRY="cce:/internal/x/prerequisite-imports";const SKIP=new Set(["cce:/internal/x/cc"]);const GLOBAL_DEPS=new Set(["cc","cc/env","cc/userland/macro"]);const BUNDLE_FILE="playcraft-bundle.js";const BUNDLE_URL=`./chunks/${BUNDLE_FILE}`;const REGISTER_RE=/^System\.register\(\s*(\[[\s\S]*?\])\s*,\s*function/;function previewDir(projectRoot){return path.join(projectRoot,"temp/programming/packer-driver/targets/preview")}function normalizeChunkUrl(url){const raw=String(url||"").replace(/\\/g,"/");if(raw.startsWith("./chunks/"))return raw;if(raw.startsWith("chunks/"))return`./${raw}`;return raw}function isChunkUrl(url){return normalizeChunkUrl(url).startsWith("./chunks/")&&normalizeChunkUrl(url).endsWith(".js")}function packChunkName(chunkUrl){return`pack-chunk:${path.basename(normalizeChunkUrl(chunkUrl),".js")}`}function isBundledImportMap(map){const imports=map&&map.imports||{};return imports[ENTRY]===BUNDLE_URL&&Object.keys(imports).length===1}function loadSourceImportMap(dir){const livePath=path.join(dir,"import-map.json");const backupPath=path.join(dir,"import-map.quickpack.json");if(!fs.existsSync(livePath))return null;const live=JSON.parse(fs.readFileSync(livePath,"utf8"));if(isBundledImportMap(live)){if(!fs.existsSync(backupPath))return null;return JSON.parse(fs.readFileSync(backupPath,"utf8"))}fs.writeFileSync(backupPath,`${JSON.stringify(live,null,2)}\n`);return live}function skipChunkUrls(map){const skip=new Set;const imports=map.imports||{};for(const spec of SKIP){if(isChunkUrl(imports[spec]))skip.add(normalizeChunkUrl(imports[spec]))}return skip}function collectChunkUrls(map){const skipUrls=skipChunkUrls(map);const urls=new Set;const queue=[];const add=url=>{if(!isChunkUrl(url))return;const normalized=normalizeChunkUrl(url);if(skipUrls.has(normalized)||urls.has(normalized))return;urls.add(normalized);queue.push(normalized)};const imports=map.imports||{};for(const[spec,url]of Object.entries(imports)){if(SKIP.has(spec))continue;add(url)}while(queue.length){const scopeUrl=queue.shift();for(const target of Object.values((map.scopes||{})[scopeUrl]||{})){add(target)}}return urls}function rewriteDep(dep,chunkUrl,map,nameOf){if(GLOBAL_DEPS.has(dep))return dep;const mapped=((map.scopes||{})[chunkUrl]||{})[dep]||(map.imports||{})[dep];if(!mapped)return dep;if(typeof mapped==="string"&&mapped.startsWith("cce:/internal/x/cc-fu"))return"cc";if(SKIP.has(mapped)||mapped===(map.imports||{})["cce:/internal/x/cc"])return"cc";if(isChunkUrl(mapped))return nameOf(normalizeChunkUrl(mapped));return mapped}function rewriteChunk(source,name,chunkUrl,map,nameOf,anonymous){const stripped=source.replace(/\n\/\/# sourceMappingURL=.*$/m,"");const match=stripped.match(REGISTER_RE);if(!match){throw new Error(`no System.register in ${chunkUrl}`)}const deps=JSON.parse(match[1]).map(dep=>rewriteDep(dep,chunkUrl,map,nameOf));const head=anonymous?`System.register(${JSON.stringify(deps)}, function`:`System.register(${JSON.stringify(name)}, ${JSON.stringify(deps)}, function`;return`${head}${stripped.slice(match[0].length)}`}/**
|
|
2
|
+
* Fold QuickPack's per-file chunks into one named-register bundle and
|
|
3
|
+
* point prerequisite-imports at it. Original chunks stay on disk for
|
|
4
|
+
* incremental compile; import-map.quickpack.json keeps the pre-rewrite map.
|
|
5
|
+
*/function concatPreviewScripts(projectRoot){const dir=previewDir(projectRoot);const map=loadSourceImportMap(dir);if(!map)return null;const imports=map.imports||{};const chunkToSpecifier=new Map;for(const[spec,url]of Object.entries(imports)){if(SKIP.has(spec)||!isChunkUrl(url))continue;chunkToSpecifier.set(normalizeChunkUrl(url),spec)}const entryChunk=imports[ENTRY]&&isChunkUrl(imports[ENTRY])?normalizeChunkUrl(imports[ENTRY]):null;const nameOf=chunkUrl=>{if(entryChunk&&chunkUrl===entryChunk)return ENTRY;return chunkToSpecifier.get(chunkUrl)||packChunkName(chunkUrl)};const chunkUrls=[...collectChunkUrls(map)];if(!chunkUrls.length)return null;// Named modules first; anonymous entry last so script-tag onload getRegister()
|
|
6
|
+
// binds prerequisite-imports (named-register's firstNamedDefine is cleared
|
|
7
|
+
// before the load event).
|
|
8
|
+
const ordered=[];for(const url of chunkUrls){if(url!==entryChunk)ordered.push(url)}if(entryChunk&&chunkUrls.includes(entryChunk))ordered.push(entryChunk);const parts=[];for(const chunkUrl of ordered){const abs=path.join(dir,chunkUrl.replace(/^\.\//,""));if(!fs.existsSync(abs)){throw new Error(`missing chunk ${chunkUrl}`)}parts.push(rewriteChunk(fs.readFileSync(abs,"utf8"),nameOf(chunkUrl),chunkUrl,map,nameOf,chunkUrl===entryChunk))}const bundle=`${parts.join("\n")}\n`;const bundleAbs=path.join(dir,"chunks",BUNDLE_FILE);fs.mkdirSync(path.dirname(bundleAbs),{recursive:true});fs.writeFileSync(bundleAbs,bundle);const bundledMap={imports:{[ENTRY]:BUNDLE_URL}};const tmp=path.join(dir,"import-map.json.tmp");fs.writeFileSync(tmp,`${JSON.stringify(bundledMap)}\n`);fs.renameSync(tmp,path.join(dir,"import-map.json"));return{modules:ordered.length,bytes:Buffer.byteLength(bundle),bundle:BUNDLE_URL}}module.exports={concatPreviewScripts,ENTRY,BUNDLE_URL,BUNDLE_FILE,isBundledImportMap};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const{describe,it,before,after}=require("node:test");const assert=require("node:assert/strict");const fs=require("fs");const os=require("os");const path=require("path");const{concatPreviewScripts,BUNDLE_URL,ENTRY}=require("./preview-concat.js");describe("concatPreviewScripts",()=>{let root;let preview;before(()=>{root=fs.mkdtempSync(path.join(os.tmpdir(),"preview-concat-"));preview=path.join(root,"temp/programming/packer-driver/targets/preview");fs.mkdirSync(path.join(preview,"chunks/aa"),{recursive:true});fs.mkdirSync(path.join(preview,"chunks/bb"),{recursive:true});fs.writeFileSync(path.join(preview,"chunks/aa/aaa111.js"),"System.register([\"__unresolved_0\", \"cc\", \"@playcraft/adsdk/cjs\"], function (_export, _context) {\n return { setters: [], execute() {} };\n});\n//# sourceMappingURL=aaa111.js.map\n");fs.writeFileSync(path.join(preview,"chunks/bb/bbb222.js"),"System.register([], function (_export, _context) {\n return { setters: [], execute() {} };\n});\n");fs.writeFileSync(path.join(preview,"import-map.json"),JSON.stringify({imports:{[ENTRY]:"./chunks/aa/aaa111.js","cce:/internal/x/cc":"./chunks/cc/skip-me.js"},scopes:{"./chunks/aa/aaa111.js":{__unresolved_0:"./chunks/bb/bbb222.js","@playcraft/adsdk/cjs":"./chunks/bb/bbb222.js",cc:"./chunks/cc/skip-me.js"}}}))});after(()=>{fs.rmSync(root,{recursive:true,force:true})});it("writes one named-register bundle and a single import-map entry",()=>{const result=concatPreviewScripts(root);assert.equal(result.modules,2);assert.equal(result.bundle,BUNDLE_URL);const map=JSON.parse(fs.readFileSync(path.join(preview,"import-map.json"),"utf8"));assert.deepEqual(map,{imports:{[ENTRY]:BUNDLE_URL}});const bundle=fs.readFileSync(path.join(preview,"chunks/playcraft-bundle.js"),"utf8");assert.equal(bundle.includes("sourceMappingURL"),false);assert.equal(bundle.includes(`System.register("${ENTRY}"`),false);assert.match(bundle,/System\.register\("pack-chunk:bbb222"/);assert.match(bundle,/System\.register\(\["pack-chunk:bbb222","cc","pack-chunk:bbb222"\], function \(_export/);assert.equal(bundle.includes("\"@playcraft/adsdk/cjs\""),false);const last=bundle.trim().split("System.register").pop();assert.match(last,/^\(\[/);assert.equal(bundle.includes("functionfunction"),false);assert.equal(bundle.includes("cce:/internal/x/cc"),false)});it("is idempotent using the quickpack backup",()=>{const again=concatPreviewScripts(root);assert.equal(again.modules,2)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";/* playcraft-json-pack:start */(function(){var pack=null;var pending=[];var packUrl="/scripting/systemjs/playcraft-json-pack.json";try{var entries=performance.getEntriesByType("resource");for(var i=entries.length-1;i>=0;--i){var name=entries[i].name;if(name.indexOf("/systemjs/system.js")!==-1){packUrl=name.replace(/system\.js(\?.*)?$/,"playcraft-json-pack.json");break}}}catch(err){}function uuidFromUrl(url){var match=String(url||"").match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:@[^.\\/?]+)?)\.json(?:\?|$)/i);return match?match[1].toLowerCase():""}function configNameFromUrl(url){var match=String(url||"").match(/\/(?:assets|remote)\/([^/]+)\/(?:config|cc\.config)\.json(?:\?|$)/i);return match?match[1]:""}function lookup(url){if(!pack)return null;var uuid=uuidFromUrl(url);if(uuid&&pack.assets&&Object.prototype.hasOwnProperty.call(pack.assets,uuid)){return pack.assets[uuid]}var configName=configNameFromUrl(url);if(configName&&pack.configs&&Object.prototype.hasOwnProperty.call(pack.configs,configName)){return pack.configs[configName]}return null}function serve(xhr,data){var text=typeof data==="string"?data:JSON.stringify(data);var json=typeof data==="string"?JSON.parse(data):data;Object.defineProperty(xhr,"readyState",{configurable:true,get:function(){return 4}});Object.defineProperty(xhr,"status",{configurable:true,get:function(){return 200}});Object.defineProperty(xhr,"response",{configurable:true,get:function(){return xhr.responseType==="json"?json:text}});Object.defineProperty(xhr,"responseText",{configurable:true,get:function(){return text}});if(typeof xhr.onreadystatechange==="function")xhr.onreadystatechange();if(typeof xhr.onload==="function")xhr.onload()}function flush(){var queue=pending.splice(0);for(var i=0;i<queue.length;i++)queue[i]()}var xhrOpen=XMLHttpRequest.prototype.open;var xhrSend=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(method,url){this.__pcUrl=url;return xhrOpen.apply(this,arguments)};XMLHttpRequest.prototype.send=function(body){var xhr=this;var url=xhr.__pcUrl;if(url&&String(url).indexOf("playcraft-json-pack.json")!==-1){return xhrSend.apply(xhr,arguments)}var run=function(){var data=lookup(url);if(data!=null){serve(xhr,data);return}xhrSend.call(xhr,body)};if(pack){run();return}pending.push(run)};var req=new XMLHttpRequest;req.open("GET",packUrl,true);req.responseType="json";req.onload=function(){pack=req.response&&typeof req.response==="object"?req.response:{assets:{},configs:{}};flush()};req.onerror=function(){pack={assets:{},configs:{}};flush()};req.send(null)})();/* playcraft-json-pack:end */
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";const fs=require("fs");const http=require("http");const https=require("https");const path=require("path");const{resolveCocosBin}=require("./cli.js");const HOOK_START="/* playcraft-json-pack:start */";const HOOK_END="/* playcraft-json-pack:end */";const PACK_FILE="playcraft-json-pack.json";const UUID_RE=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:@[0-9a-z]+)?/gi;const UUID_FILE_RE=/^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:@.+)?)\.json$/i;const FALLBACK_MAX_BYTES=200*1024;const FILE_MAX_BYTES=5*1024*1024;function systemJsDir(projectRoot){return path.join(projectRoot,"temp/programming/preview/systemjs")}function hookSource(){return fs.readFileSync(path.join(__dirname,"preview-json-hook.js"),"utf8").trim()+"\n"}function uuidFromUrl(url){const match=String(url||"").match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:@[^.\\/?]+)?)\.json(?:\?|$)/i);return match?match[1].toLowerCase():""}function configNameFromUrl(url){const match=String(url||"").match(/\/(?:assets|remote)\/([^/]+)\/(?:config|cc\.config)\.json(?:\?|$)/i);return match?match[1]:""}function addUuid(set,value){if(typeof value!=="string"||!value)return;const inner=value.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:@[0-9a-z]+)?/i);if(inner)set.add(inner[0].toLowerCase())}function collectFromSettings(settings,seeds){if(!settings||typeof settings!=="object")return;const builtins=settings.engine&&settings.engine.builtinAssets;if(Array.isArray(builtins)){for(const uuid of builtins)addUuid(seeds,uuid)}addUuid(seeds,settings.launch&&settings.launch.launchScene);addUuid(seeds,settings.launchScene);const scenes=settings.scenes||settings.launch&&settings.launch.scenes;if(Array.isArray(scenes)){for(const scene of scenes){if(scene&&typeof scene==="object")addUuid(seeds,scene.uuid);else addUuid(seeds,scene)}}}function collectFromConfig(config,seeds){if(!config||typeof config!=="object")return;for(const uuid of config.uuids||[])addUuid(seeds,String(uuid));for(const uuid of Object.keys(config.paths||{}))addUuid(seeds,uuid);const scenes=config.scenes||{};if(typeof scenes==="object"){for(const value of Object.values(scenes)){if(Array.isArray(value)){for(const item of value)addUuid(seeds,String(item))}else{addUuid(seeds,String(value))}}}}function parseSettings(text){const match=String(text||"").match(/window\._CCSettings\s*=\s*(\{[\s\S]*\});\s*$/);if(!match)return null;return JSON.parse(match[1])}function fetchText(url,timeout=8000){return new Promise((resolve,reject)=>{const client=String(url).startsWith("https:")?https:http;const req=client.get(url,{timeout},res=>{const chunks=[];res.on("data",chunk=>chunks.push(chunk));res.on("end",()=>{const body=Buffer.concat(chunks).toString("utf8");if((res.statusCode||0)>=400){reject(new Error(`${res.statusCode} ${url}`));return}resolve(body)})});req.on("timeout",()=>{req.destroy();reject(new Error(`timeout ${url}`))});req.on("error",reject)})}function startSceneUuid(projectRoot){try{const cfg=JSON.parse(fs.readFileSync(path.join(projectRoot,"settings/cocos.config.json"),"utf8"));return cfg.builder&&cfg.builder.common&&cfg.builder.common.startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-mobile"]&&cfg.builder.platforms["web-mobile"].startScene||cfg.builder&&cfg.builder.platforms&&cfg.builder.platforms["web-desktop"]&&cfg.builder.platforms["web-desktop"].startScene||""}catch{return""}}function resolveEngineLibraryDirs(){const dirs=[];const add=dir=>{if(dir&&fs.existsSync(dir)&&!dirs.includes(dir))dirs.push(dir)};if(process.env.COCOS_ENGINE){add(path.join(process.env.COCOS_ENGINE,"editor/library"))}const bin=resolveCocosBin();const starts=[];if(bin&&path.isAbsolute(bin))starts.push(bin);try{const{execSync}=require("child_process");const which=execSync("command -v cocos",{encoding:"utf8"}).trim();if(which)starts.push(which)}catch{}for(const start of starts){try{let current=fs.realpathSync(start);for(let i=0;i<8;i++){add(path.join(current,"packages/engine/editor/library"));add(path.join(current,"engine/editor/library"));add(path.join(current,"editor/library"));current=path.dirname(current)}}catch{}}add("/usr/local/lib/node_modules/cocos-cli/packages/engine/editor/library");return dirs}function libraryDirs(projectRoot,extraDirs){const dirs=[];const projectLib=path.join(projectRoot,"library");if(fs.existsSync(projectLib))dirs.push(projectLib);for(const dir of extraDirs||resolveEngineLibraryDirs()){if(dir&&fs.existsSync(dir)&&!dirs.includes(dir))dirs.push(dir)}return dirs}function findLibraryJson(uuid,dirs){const name=`${uuid}.json`;const prefix=uuid.slice(0,2);for(const dir of dirs){const abs=path.join(dir,prefix,name);if(fs.existsSync(abs))return abs}return""}function scanFallbackUuids(dirs){const seeds=new Set;for(const dir of dirs){if(!fs.existsSync(dir))continue;for(const bucket of fs.readdirSync(dir)){const absBucket=path.join(dir,bucket);let stat;try{stat=fs.statSync(absBucket)}catch{continue}if(!stat.isDirectory())continue;for(const name of fs.readdirSync(absBucket)){const match=name.match(UUID_FILE_RE);if(!match)continue;const abs=path.join(absBucket,name);try{if(fs.statSync(abs).size>FALLBACK_MAX_BYTES)continue}catch{continue}seeds.add(match[1].toLowerCase())}}}return seeds}function closeUuidJson(seeds,dirs){const assets={};const queue=[...seeds];const seen=new Set(seeds);while(queue.length){const uuid=queue.pop();const abs=findLibraryJson(uuid,dirs);if(!abs)continue;let stat;try{stat=fs.statSync(abs)}catch{continue}if(stat.size>FILE_MAX_BYTES)continue;let json;try{json=JSON.parse(fs.readFileSync(abs,"utf8"))}catch{continue}assets[uuid]=json;const text=JSON.stringify(json);UUID_RE.lastIndex=0;let match;while(match=UUID_RE.exec(text)){const next=match[0].toLowerCase();if(seen.has(next))continue;seen.add(next);queue.push(next)}}return assets}function injectJsonPackHook(projectRoot){const dir=systemJsDir(projectRoot);const systemJsPath=path.join(dir,"system.js");if(!fs.existsSync(systemJsPath))return false;let source=fs.readFileSync(systemJsPath,"utf8");const start=source.indexOf(HOOK_START);const end=source.indexOf(HOOK_END);if(start!==-1&&end!==-1&&end>start){source=`${source.slice(0,start)}${source.slice(end+HOOK_END.length)}`.replace(/^\n/,"")}fs.writeFileSync(systemJsPath,`${hookSource()}${source}`);return true}async function loadPreviewMeta(options){if(options.settings||options.bundleConfigs){return{settings:options.settings||null,configs:options.bundleConfigs||{}}}const origin=options.previewOrigin;if(!origin)return{settings:null,configs:{}};const fetch=options.fetchText||fetchText;const settings=parseSettings(await fetch(`${origin.replace(/\/$/,"")}/preview/settings.js`));const bundles=settings&&settings.assets&&settings.assets.projectBundles||["internal","main","resources"];const configs={};for(const name of bundles){try{configs[name]=JSON.parse(await fetch(`${origin.replace(/\/$/,"")}/assets/${name}/config.json`))}catch{}}return{settings,configs}}/**
|
|
2
|
+
* Pack preview UUID JSON + bundle configs into one file and intercept XHR
|
|
3
|
+
* from system.js (before builtin assets load). Official merge_all_json is
|
|
4
|
+
* builder-only and uses a compiled format preview cannot feed.
|
|
5
|
+
*/async function packPreviewJson(projectRoot,options={}){const dirs=libraryDirs(projectRoot,options.engineLibraryDirs);const{settings,configs}=await loadPreviewMeta(options);const seeds=new Set;collectFromSettings(settings,seeds);for(const config of Object.values(configs||{}))collectFromConfig(config,seeds);addUuid(seeds,startSceneUuid(projectRoot));if(!seeds.size){for(const uuid of scanFallbackUuids(dirs))seeds.add(uuid)}const assets=closeUuidJson(seeds,dirs);const pack={assets,configs:configs||{}};const json=`${JSON.stringify(pack)}\n`;const dir=systemJsDir(projectRoot);fs.mkdirSync(dir,{recursive:true});const abs=path.join(dir,PACK_FILE);const tmp=`${abs}.tmp`;fs.writeFileSync(tmp,json);fs.renameSync(tmp,abs);const hooked=injectJsonPackHook(projectRoot);return{files:Object.keys(assets).length,configs:Object.keys(pack.configs).length,bytes:Buffer.byteLength(json),hooked,pack:`./${PACK_FILE}`}}module.exports={packPreviewJson,injectJsonPackHook,uuidFromUrl,configNameFromUrl,parseSettings,collectFromSettings,collectFromConfig,PACK_FILE,HOOK_START};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const{describe,it,before,after}=require("node:test");const assert=require("node:assert/strict");const fs=require("fs");const os=require("os");const path=require("path");const{packPreviewJson,uuidFromUrl,configNameFromUrl,HOOK_START}=require("./preview-json-pack.js");describe("packPreviewJson",()=>{let root;const scene="0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d";const builtin="970b0598-bcb0-4714-91fb-2e81440dccd8";const extra="11111111-2222-4333-8444-555555555555";before(()=>{root=fs.mkdtempSync(path.join(os.tmpdir(),"preview-json-"));const writeJson=(dir,uuid,json)=>{const abs=path.join(dir,uuid.slice(0,2),`${uuid}.json`);fs.mkdirSync(path.dirname(abs),{recursive:true});fs.writeFileSync(abs,`${JSON.stringify(json)}\n`)};writeJson(path.join(root,"library"),scene,{name:"scene",ref:{__uuid__:extra}});writeJson(path.join(root,"library"),extra,{name:"extra"});writeJson(path.join(root,"engine-lib"),builtin,{name:"effect"});fs.mkdirSync(path.join(root,"temp/programming/preview/systemjs"),{recursive:true});fs.writeFileSync(path.join(root,"temp/programming/preview/systemjs/system.js"),"(function () { 'use strict'; window.System = {}; })();\n");fs.mkdirSync(path.join(root,"settings"),{recursive:true});fs.writeFileSync(path.join(root,"settings/cocos.config.json"),JSON.stringify({builder:{common:{startScene:scene}}}))});after(()=>{fs.rmSync(root,{recursive:true,force:true})});it("parses preview json urls",()=>{assert.equal(uuidFromUrl("/assets/internal/import/97/970b0598-bcb0-4714-91fb-2e81440dccd8.json?t=1"),builtin);assert.equal(uuidFromUrl(`/scene/${scene}.json`),scene);assert.equal(configNameFromUrl("/assets/internal/config.json"),"internal")});it("packs uuid closure + configs and injects the xhr hook",async()=>{const result=await packPreviewJson(root,{engineLibraryDirs:[path.join(root,"engine-lib")],settings:{engine:{builtinAssets:[builtin]},launch:{launchScene:scene},assets:{projectBundles:["internal"]}},bundleConfigs:{internal:{name:"internal",uuids:[builtin],paths:{[builtin]:["db://internal/effect","cc.EffectAsset"]}}}});assert.equal(result.files,3);assert.equal(result.configs,1);assert.equal(result.hooked,true);const pack=JSON.parse(fs.readFileSync(path.join(root,"temp/programming/preview/systemjs/playcraft-json-pack.json"),"utf8"));assert.equal(pack.assets[scene].name,"scene");assert.equal(pack.assets[extra].name,"extra");assert.equal(pack.assets[builtin].name,"effect");assert.equal(pack.configs.internal.name,"internal");const systemJs=fs.readFileSync(path.join(root,"temp/programming/preview/systemjs/system.js"),"utf8");assert.equal(systemJs.includes(HOOK_START),true);assert.equal(systemJs.includes("XMLHttpRequest.prototype.send"),true);assert.match(systemJs,/window\.System = \{\}/);const again=await packPreviewJson(root,{engineLibraryDirs:[path.join(root,"engine-lib")],settings:{engine:{builtinAssets:[builtin]},launch:{launchScene:scene}},bundleConfigs:{internal:{name:"internal",uuids:[builtin],paths:{}}}});assert.equal(again.hooked,true);const injected=fs.readFileSync(path.join(root,"temp/programming/preview/systemjs/system.js"),"utf8");assert.equal(injected.split(HOOK_START).length-1,1)});it("serves packed uuid json from the xhr hook without network",async()=>{await packPreviewJson(root,{engineLibraryDirs:[path.join(root,"engine-lib")],settings:{engine:{builtinAssets:[builtin]},launch:{launchScene:scene}},bundleConfigs:{internal:{name:"internal",uuids:[builtin],paths:{}}}});const hook=fs.readFileSync(path.join(root,"temp/programming/preview/systemjs/system.js"),"utf8").split("(function () { 'use strict'; window.System")[0];const pack=JSON.parse(fs.readFileSync(path.join(root,"temp/programming/preview/systemjs/playcraft-json-pack.json"),"utf8"));const instances=[];function FakeXHR(){instances.push(this);this.readyState=1;this.status=0;this.response=null;this.responseType="json";this.onload=null;this.onreadystatechange=null;this.__network=false}FakeXHR.prototype.open=function(method,url){this.__pcUrl=url};FakeXHR.prototype.send=function(){this.__network=true};global.performance={getEntriesByType:()=>[]};global.XMLHttpRequest=FakeXHR;// eslint-disable-next-line no-eval
|
|
2
|
+
eval(hook.replace(HOOK_START,"").replace("/* playcraft-json-pack:end */",""));const packXhr=instances[0];packXhr.response=pack;packXhr.onload();const asset=new FakeXHR;let loaded=null;asset.onload=function(){loaded=asset.response};XMLHttpRequest.prototype.open.call(asset,"GET",`/scene/${scene}.json`);XMLHttpRequest.prototype.send.call(asset,null);assert.equal(asset.__network,false);assert.equal(asset.status,200);assert.equal(loaded.name,"scene");const config=new FakeXHR;let configLoaded=null;config.onload=function(){configLoaded=config.response};XMLHttpRequest.prototype.open.call(config,"GET","/assets/internal/config.json");XMLHttpRequest.prototype.send.call(config,null);assert.equal(config.__network,false);assert.equal(configLoaded.name,"internal");delete global.XMLHttpRequest;delete global.performance})});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";const fs=require("fs");const path=require("path");const JSON5=require("json5");const{getBase64FromFile,getAllFilesFromDir}=require("./fs");const{THEME_ASSET_EXT}=require("./constants");const{validateThemeData}=require("../../utils/validateThemeData");function detectCurrentTheme(projectRoot,themeConfig){const entryFile=themeConfig&&themeConfig.entryFile||"src/theme/index.ts";const entryPath=path.join(projectRoot,entryFile);if(!fs.existsSync(entryPath))return null;const content=fs.readFileSync(entryPath,"utf8");const match=content.match(/from\s+['"]\.\/([^'"]+)['"]/);return match?match[1]:null}function collectDirAssets(assetsDir,keyPrefix){const map={};if(!fs.existsSync(assetsDir))return map;const root=assetsDir.replace(/\\/g,"/");for(const filePath of getAllFilesFromDir(assetsDir)){if(!
|
|
1
|
+
"use strict";const fs=require("fs");const path=require("path");const JSON5=require("json5");const{getBase64FromFile,getAllFilesFromDir,sniffAudioMime}=require("./fs");const{THEME_ASSET_EXT}=require("./constants");const{validateThemeData}=require("../../utils/validateThemeData");function detectCurrentTheme(projectRoot,themeConfig){const entryFile=themeConfig&&themeConfig.entryFile||"src/theme/index.ts";const entryPath=path.join(projectRoot,entryFile);if(!fs.existsSync(entryPath))return null;const content=fs.readFileSync(entryPath,"utf8");const match=content.match(/from\s+['"]\.\/([^'"]+)['"]/);return match?match[1]:null}function isInlinableThemeAsset(filePath){if(THEME_ASSET_EXT.test(filePath))return true;try{return Boolean(sniffAudioMime(fs.readFileSync(filePath)))}catch{return false}}function collectDirAssets(assetsDir,keyPrefix){const map={};if(!fs.existsSync(assetsDir))return map;const root=assetsDir.replace(/\\/g,"/");for(const filePath of getAllFilesFromDir(assetsDir)){if(!isInlinableThemeAsset(filePath))continue;const rel=filePath.replace(/\\/g,"/").slice(root.length).replace(/^\//,"");map[`${keyPrefix}${rel}`]=getBase64FromFile(filePath)}return map}function collectReferencedFiles(projectRoot,sourceDir,themeName,mergedData,assetRecord){if(!mergedData||typeof mergedData!=="object")return;const themeRoot=path.join(projectRoot,sourceDir,themeName);for(const value of Object.values(mergedData)){if(typeof value==="string"){if(assetRecord[value])continue;const rel=value.replace(/^\.\//,"");const candidates=[path.join(themeRoot,rel),path.join(themeRoot,"assets",path.basename(rel)),path.resolve(projectRoot,rel)];const abs=candidates.find(p=>fs.existsSync(p)&&fs.statSync(p).isFile()&&isInlinableThemeAsset(p));if(abs)assetRecord[value]=getBase64FromFile(abs)}else if(value&&typeof value==="object"&&!Array.isArray(value)){collectReferencedFiles(projectRoot,sourceDir,themeName,value,assetRecord)}}}function loadThemeI18n(projectRoot,sourceDir,themeName){const p=path.join(projectRoot,sourceDir,themeName,"theme.i18n.runtime.json5");if(!fs.existsSync(p))return{};try{return JSON5.parse(fs.readFileSync(p,"utf8"))||{}}catch{return{}}}/**
|
|
2
2
|
* Read src/theme json5 + theme/assets the same way Phaser webpack inlines them.
|
|
3
3
|
*/function loadThemePayload(projectRoot,themeName,themeConfig={}){const sourceDir=themeConfig.sourceDir||"src/theme";const{mergedData,errors}=validateThemeData(themeName,projectRoot,themeConfig);if(errors){throw new Error(`Theme "${themeName}" validation failed:\n${errors.join("\n")}`)}const assetsDir=path.join(projectRoot,sourceDir,themeName,"assets");const assetRecordByPath=collectDirAssets(assetsDir,"./assets/");collectReferencedFiles(projectRoot,sourceDir,themeName,mergedData,assetRecordByPath);return{themeName,mergedData:mergedData||{},i18nOverride:loadThemeI18n(projectRoot,sourceDir,themeName),assetRecordByPath}}function writeGeneratedThemeModule(filePath,payload){const header="/* eslint-disable */\n"+"// Generated from src/theme by playable-scripts. Do not edit.\n";const body=`export const THEME_DATA = ${JSON.stringify(payload.mergedData,null,2)} as Record<string, unknown>;\n`+`export const THEME_I18N_OVERRIDE = ${JSON.stringify(payload.i18nOverride,null,2)} as Record<string, Record<string, string>>;\n`+`export const THEME_ASSETS = ${JSON.stringify(payload.assetRecordByPath)} as Record<string, string>;\n`;const next=header+body;if(fs.existsSync(filePath)&&fs.readFileSync(filePath,"utf8")===next){return false}fs.mkdirSync(path.dirname(filePath),{recursive:true});fs.writeFileSync(filePath,next);return true}function syncGeneratedTheme(projectRoot,options={}){const themeConfig=options.themeConfig||{sourceDir:"src/theme",entryFile:"src/theme/index.ts"};const themeName=options.themeName||detectCurrentTheme(projectRoot,themeConfig);if(!themeName)return null;const payload=loadThemePayload(projectRoot,themeName,themeConfig);const rel=options.generatedRel||"assets/scripts/platform/theme.generated.ts";const changed=writeGeneratedThemeModule(path.join(projectRoot,rel),payload);return{themeName,payload,generatedRel:rel,changed}}module.exports={detectCurrentTheme,loadThemePayload,writeGeneratedThemeModule,syncGeneratedTheme,collectDirAssets};
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
{test:/\.ts?$/,exclude:/node_modules/,use:[{loader:"babel-loader",options:{// presets: ['@babel/preset-env'],
|
|
8
8
|
plugins:options.compilation.allowTemplateLiterals===false?["@babel/plugin-transform-template-literals"]:[]}},{loader:"esbuild-loader",options:{loader:"ts",target:"es2015"}}]},{test:/\.css$/,use:["style-loader","css-loader"]},{test:/\.(js|mjs)$/,// exclude: /node_modules/,
|
|
9
9
|
use:{loader:"babel-loader",options:{// presets: ['@babel/preset-env'],
|
|
10
|
-
plugins:options.compilation.allowTemplateLiterals===false?["@babel/plugin-transform-template-literals"]:[]}}},{test:/\.(gltf)$/,loader:path.join(__dirname,"../../loaders/gltf-loader.js")},{test:/\.(gif|png|jpe?g|webp|mp3|mp4|m4a|ogg|wav|glb|fbx|obj)$/i,type:"asset/inline"},{test:/\.json5$/i,type:"javascript/auto",use:{loader:"json5-loader",options:{esModule:false}}},// 处理 json?url → base64
|
|
10
|
+
plugins:options.compilation.allowTemplateLiterals===false?["@babel/plugin-transform-template-literals"]:[]}}},{test:/\.(gltf)$/,loader:path.join(__dirname,"../../loaders/gltf-loader.js")},{test:/\.(gif|png|jpe?g|webp|mp3|mpeg|mp4|m4a|ogg|wav|glb|fbx|obj)$/i,type:"asset/inline"},{test:/\.json5$/i,type:"javascript/auto",use:{loader:"json5-loader",options:{esModule:false}}},// 处理 json?url → base64
|
|
11
11
|
{test:/\.json$/i,resourceQuery:/url/,type:"asset/inline",generator:{dataUrl:content=>`data:application/json;base64,${content.toString("base64")}`}},{test:/\.(svg|xml)$/i,type:"asset/source"},{test:/\.atlas$/,type:"asset/inline",generator:{dataUrl:content=>{return`data:text/atlas;base64,${content.toString("base64")}`}}},{test:/\.fnt$/i,type:"asset/inline",generator:{dataUrl:content=>{return`data:text/plain;base64,${content.toString("base64")}`}}},{test:/\.(woff|woff2|eot|ttf|otf)$/i,type:"asset/inline"}]},plugins:[new VueLoaderPlugin]};exports.allowedExtensions=allowedExtensions;exports.webpackCommonConfig=webpackConfig;
|
package/core/index.d.ts
CHANGED
package/core/options.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";const{parseArgvOptions,allowedAdProtocols,allowedAdNetworks,allowedPlaycraftOrientations,allowedLanguages,allowedEngines}=require("./utils/parseArgvOptions");const path=require("path");const fs=require("fs");const{name,version}=require("../package.json");const possibleOptions=[{name:"out-dir",alias:"outDir",defaultValue:"dist",hasValue:true,description:"Output directory for build files"},{name:"build-config",alias:"buildConfig",defaultValue:"build.json",hasValue:true,description:"Path to build.json configuration file"},{name:"ts-config",alias:"tsConfig",defaultValue:"tsconfig.json",hasValue:true,description:"For TypeScript projects, path to tsconfig.json file"},{name:"js-config",alias:"jsConfig",defaultValue:"jsconfig.json",hasValue:true,description:"For JavaScript projects, path to jsconfig.json file"},{name:"port",hasValue:true,defaultValue:3000,description:"Development server port number",parser:function(rawValue){const value=+rawValue;if(isNaN(value))throw new Error("--port should be a number");return value}},{name:"open",defaultValue:false,hasValue:false,description:"Open browser automatically when server starts"},{name:"protocol",hasValue:true,defaultValue:"none",description:"Ad protocol to use (none, mraid, or dapi)",parser:function(rawValue){if(!allowedAdProtocols.includes(rawValue)){throw new Error(`--protocol should have one of the value: ${allowedAdProtocols.join(", ")}`)}return rawValue}},{name:"network",defaultValue:"preview",hasValue:true,description:"Target Ad network",parser:function(rawValue){if(!allowedAdNetworks.includes(rawValue)){throw new Error(`--network should have one of the value: ${allowedAdNetworks.join(", ")}`)}return rawValue}},{name:"zip",defaultValue:false,hasValue:false,description:"Should the build be zipped? (only for some ad networks)"},{name:"is-channel-fold2zip",defaultValue:false,hasValue:false,description:"\u5F53\u542F\u7528\u65F6\uFF0C\u6784\u5EFA\u4EA7\u7269\u683C\u5F0F\u4E3A\u300C\u4E3B\u9898\u6587\u4EF6\u540D/\u6E20\u9053.zip\u300D"},{name:"dev",hasValue:true,description:"Enable development mode (true/false)",parser:function(rawValue){if(!(rawValue==="true"||rawValue==="false"))throw new Error("--dev should have either true or false value");return rawValue==="true"}},{name:"filename",defaultValue:"{app}_{name}_{version}_{date}_{language}_{network}",hasValue:true,description:"Specifies the build filename template"},{name:"app",defaultValue:"AppName",hasValue:true,description:"Specifies the application name used in build filename and APP define"},{name:"name",defaultValue:"ConceptName",hasValue:true,description:"Specifies the concept name used in build filename and NAME define"},{name:"version",defaultValue:"v1",hasValue:true,description:"Specifies the version name used in build filename and VERSION define"},{name:"language",defaultValue:"en",hasValue:true,description:"Specifies the language of the build used in LANGUAGE define",parser:function(rawValue){if(!allowedLanguages.includes(rawValue)){throw new Error(`--platform should have one of the value: ${allowedLanguages.join(", ")}`)}return rawValue}},{name:"playcraft-orientation",alias:"playcraftOrientation",defaultValue:["both"],hasValue:true,description:"\u5F53\u524D\u8981\u6253\u5305\u7684\u6A2A\u7AD6\u5C4F\u65B9\u5411\u7248\u672C\u5217\u8868\uFF0C\u53EF\u6307\u5B9A\u591A\u4E2A\uFF08\u9017\u53F7\u5206\u9694\uFF09\uFF0C\u53D6\u503C\uFF1Alandscape/portrait/both\u3002\u7528\u4E8E PLAYCRAFT_ORIENTATION define \u53CA window.playcraftOrientation \u8FD0\u884C\u65F6\u53D8\u91CF",parser:function(rawValue){const values=rawValue.split(",").map(v=>v.trim()).filter(Boolean);for(const value of values){if(!allowedPlaycraftOrientations.includes(value)){throw new Error(`--playcraft-orientation should have one of the value: ${allowedPlaycraftOrientations.join(", ")}`)}}return values}},{name:"playcraft-orientation-channel",alias:"playcraftOrientationChannel",defaultValue:[],hasValue:true,description:"\u54EA\u4E9B\u6E20\u9053\u9700\u8981\u6309 playcraftOrientation \u5206\u522B\u6253\u51FA\u591A\u4E2A\u65B9\u5411\u7248\u672C\u7684\u5305\uFF08\u9017\u53F7\u5206\u9694\u7684\u6E20\u9053\u540D\u5217\u8868\uFF09\u3002\u4E0D\u5728\u6B64\u5217\u8868\u4E2D\u7684\u6E20\u9053\u59CB\u7EC8\u6309 both\uFF08\u81EA\u9002\u5E94\uFF09\u5355\u4E00\u7248\u672C\u6253\u5305",parser:function(rawValue){return rawValue.split(",").map(v=>v.trim()).filter(Boolean)}},{name:"google-play-url",alias:"googlePlayUrl",defaultValue:"https://play.google.com/store/games",hasValue:true,description:"Google Play Store URL for the app"},{name:"app-store-url",alias:"appStoreUrl",defaultValue:"https://www.apple.com/app-store/",hasValue:true,description:"App Store URL for the app"},{name:"skip-recommended-meta",alias:"skipRecommendedMeta",hasValue:false,description:"Don't inject recommended for playable ads META tags"},{name:"debugger",hasValue:true,description:"URL of debugger script to inject into code"},{name:"obfuscate-level",alias:"obfuscateLevel",defaultValue:4,hasValue:true,description:"Code obfuscation level: 0=no minimize/obfuscate, 1=terser only, 2=obfuscator basic(default), 3=obfuscator+dead code, 4=maximum obfuscation",parser:function(rawValue){const value=+rawValue;if(isNaN(value)||value<0||value>4){throw new Error("--obfuscate-level should be a number between 0 and 4")}return value}},{name:"fflate-compression",alias:"fflateCompression",defaultValue:false,hasValue:true,description:"Enable fflate compression for HTML output (level 9, production only)",parser:function(rawValue){// 支持 true/false 字符串和布尔值
|
|
2
2
|
if(rawValue==="true"||rawValue===true||rawValue==="1")return true;if(rawValue==="false"||rawValue===false||rawValue==="0")return false;return Boolean(rawValue)}},{name:"exclude-compress-dirs",alias:"excludeCompressDirs",defaultValue:[],hasValue:true,description:"Directories to exclude from compression (comma-separated list of paths)",parser:function(rawValue){if(!rawValue)return[];return rawValue.split(",").map(dir=>dir.trim()).filter(Boolean)}},{name:"engine",defaultValue:"",hasValue:true,description:"Playable engine: phaser, threejs, or cocos. Empty = original webpack pack",parser:function(rawValue){if(rawValue==null||rawValue==="")return"";if(!allowedEngines.includes(rawValue)){throw new Error(`--engine should have one of the value: ${allowedEngines.join(", ")} (omit or empty = webpack)`)}return rawValue}}];/** @type {import('./index').CLIOptions} */const options=parseArgvOptions(possibleOptions);// Extract CLI explicit keys set, then remove it from options
|
|
3
3
|
const cliExplicitKeys=options._cliExplicitKeys||new Set;delete options._cliExplicitKeys;options.defines={};options.compilation={};options.adNetworkNames={};options.cocos={buildConfig:"build-configs/web-mobile.json",// empty = derive from Creator buildConfig buildPath + outputName
|
|
4
|
-
webMobileDir:"",skipEngineBuild:false,creatorBin:"",generatedThemeFile:"assets/scripts/platform/theme.generated.ts"};// ==================== 配置文件加载 ====================
|
|
4
|
+
webMobileDir:"",skipEngineBuild:false,creatorBin:"",generatedThemeFile:"assets/scripts/platform/theme.generated.ts",enableSplash:false};// ==================== 配置文件加载 ====================
|
|
5
5
|
//
|
|
6
6
|
// 优先级(从低到高):
|
|
7
7
|
// 1. builds.config.js (新配置文件,优先读取)
|