sapdon 3.5.3 → 3.6.0

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/prod/cli/start.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{program as e}from"commander";import n from"inquirer";import o from"path";import{fileURLToPath as t}from"url";import i from"fs";import{randomUUID as r}from"crypto";import{fileURLToPath as s}from"node:url";import c from"child_process";import a from"fs/promises";import l from"http";import{rollup as p}from"rollup";import u from"@rollup/plugin-commonjs";import{nodeResolve as d}from"@rollup/plugin-node-resolve";import m from"@rollup/plugin-typescript";import{typescriptPaths as f}from"rollup-plugin-typescript-paths";import g from"@rollup/plugin-json";import"rollup-plugin-visualizer";import y from"@rollup/plugin-terser";import h from"os";import j from"lodash";import b from"archiver";const S=()=>r();function v(e,n){try{i.copyFileSync(e,n)}catch(e){console.error("文件复制失败:",e)}}const w=e=>!i.existsSync(e),_=e=>{try{return i.readFileSync(e,"utf8")}catch(e){console.log(e)}return null},O=(e,n)=>{i.mkdirSync(o.dirname(e),{recursive:!0}),i.writeFileSync(e,n)},k=(e,n)=>{if(i.mkdirSync(o.dirname(n),{recursive:!0}),!i.existsSync(e))return void console.log(`Source path ${e} does not exist.`);i.existsSync(n)||i.mkdirSync(n);i.readdirSync(e).forEach(t=>{const r=o.join(e,t),s=o.join(n,t);i.lstatSync(r).isDirectory()?k(r,s):i.copyFileSync(r,s)})};function x(e){const n=s(e.url);return o.dirname(n)}const $=new Map;function N(e,n){let o=$.get(e);return o||(o=n(e),$.set(e,o),o)}function J(){const e=E(),n=o.join(e,"build.config");if(!i.existsSync(n))throw new Error("未找到项目配置文件,请先初始化项目");return N(n,e=>function(e){const n=(o=i.readFileSync(e),JSON.parse(String(o).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/g,"$1")));var o;if(2===n.formatVersion)return n;const t=function({defaultConfig:e,resources:n,scripts:o}){const t={formatVersion:2,buildOptions:{useHMR:!0,buildMode:"dev",buildEntry:e.buildEntry,scriptEntry:e.scriptEntry,scriptOutput:e.scriptEntry.replace(".ts",".js"),useJs:"ts"!==o[0].type,buildDir:e.buildDir,dependencies:e.dependencies,resource:{path:n[0].path,resourceHints:!0}},versionType:"release"};return t}(n);return i.writeFileSync(e,JSON.stringify(t,null,2)),t}(e))}const R=t(import.meta.url),F=o.dirname(R),P={js:"js_sapdon",ts:"ts_sapdon"},D=e=>{const n=o.join(e,"package.json");if(!i.existsSync(n))return null;try{const t=JSON.parse(i.readFileSync(n,"utf-8"));return{name:o.basename(e),description:t.description||"A new sapdon project",author:t.author||"Sapdon",version:t.version||"1.0.0"}}catch(e){return console.error("读取package.json文件时出错:",e),null}},M={};function E(){const e=M.projectPath??process.cwd();if(!i.existsSync(o.join(e,"build.config")))throw new Error("无效的项目路径");return e}function B(){const{buildDir:e}=J().buildOptions,n=N("projectName",()=>o.basename(E()));return o.join(E(),e,n+"_bp")}const H=async(e,n,t="")=>{const i={};try{await a.access(e)}catch{return i}const r=await a.readdir(e);for(const s of r){const r=o.join(e,s);if((await a.stat(r)).isDirectory()){const e=await H(r,n,t);Object.assign(i,e)}else if(s.endsWith(".png")){const e=o.basename(s,".png"),c=`${t}${o.relative(n,r).replace(/\.png$/,"").replace(/\\/g,"/")}`;i[e]={textures:c}}}return i},L=async(e,n,o)=>{try{const t=JSON.stringify(n,null,2);await a.writeFile(e,t),console.log(o)}catch(e){console.error("Error writing JSON file:",e)}};Symbol.metadata||(Symbol.metadata=Symbol("[[metadata]]"));const A=Symbol("isRawJSON");const I=["boolean","number"],C=["string","undefined"];function W(e,n){const o=typeof n;if(null===o)return null;if(C.includes(o))return n;if(I.includes(o))return JSON.rawJSON(n);if("object"===o)return JSON.isRawJSON(n)?n:function(e){return!0===e?.[A]}(n)?JSON.rawJSON(n.rawJSON):n;if("bigint"===o)return JSON.rawJSON(n.toString());throw new Error("Unexpected value")}const T={encode:e=>JSON.stringify(e,W),decode:JSON.parse};const{port:U}={port:49037};const z=new class{cliServerHandlers=new Map;listening=!1;isListening(){return this.listening}bootstrap(){this.listening=!0;const e=l.createServer(async(e,n)=>{const o=this.cliServerHandlers.get((e.url??"/").slice(1));if(o){try{const{promise:n,resolve:t,reject:i}=Promise.withResolvers();let r=Buffer.alloc(0);e.on("data",e=>r=Buffer.concat([r,e])),e.on("end",()=>{try{t(function(e,n=T){return n.decode(e)}(r))}catch(e){i(e)}}),await o(...await n)}catch(e){return console.error(e),n.writeHead(500),void n.end()}n.writeHead(200),n.end()}else n.writeHead(404),n.end()}).listen(U,()=>console.log(`Dev Server listening on port ${U}`));return e.on("error",e=>{throw this.listening=!1,function(e){return"object"==typeof e&&null!==e&&"EADDRINUSE"===e.code}(e)&&(console.error(`[sapdon] Dev Server 端口 ${U} 已被其他 sapdon 进程占用。`),console.error("[sapdon] 请先结束残留的 sapdon 进程,再重新构建,否则本次构建的数据可能被写入错误的包目录。"),process.exit(1)),e}),e}handle(e,n){this.cliServerHandlers.set(e,n)}getHandler(e){return this.cliServerHandlers.get(e)}interceptHandler(e,n){const o=n(this.getHandler(e)??Function.prototype);return this.cliServerHandlers.set(e,o),o}};async function V({level:e,message:n,timeStamp:o,stack:t}){console[e](n,t,`\nat ${new Date(o).toLocaleString()}`)}class G{static dataList=[];static getDataList(){return[...this.dataList]}static startServer(){z.handle("submitGregistry",e=>{this.dataList=e}),z.handle("remote-logger",V)}}const q=async(e,n,t)=>{try{o.join(n,`${t}_BP`);const r=o.join(n,`${t}_RP`),s=(...e)=>o.join(r,...e),c=G.getDataList(),a={item:null,block:null,flipbook:[]},l=[];for(const{name:r,root:s,path:p,data:u}of c){switch(console.log("处理数据:",r,s,p),r){case"item_texture":a.item=u,console.log("用户物品贴图数据:",a.item);continue;case"terrain_texture":a.block=u,console.log("用户方块贴图数据:",a.block);continue;case"flipbook_textures":a.flipbook=u,console.log("用户翻书贴图数据:",a.flipbook);continue}if(u._scriptSource){const n=o.dirname(e),t=o.join(n,p,`${r}.js`);i.existsSync(t)?console.log(`自定义组件脚本已存在,跳过: ${t}`):(O(t,u.source),console.log(`已生成自定义组件脚本: ${t}`)),l.push({safeName:r,componentId:u.componentId});continue}const c="behavior"===s?`${t}_BP`:`${t}_RP`,d=o.join(n,c),m=o.join(d,p,`${r}.json`);O(m,JSON.stringify(u,null,2))}if(l.length>0){const n=o.dirname(e),t=o.join(n,"scripts","custom_components"),r=o.join(t,"index.js");if(i.existsSync(r))console.log(`自定义组件注册索引已存在,跳过: ${r}`);else{const e=l.map(({safeName:e})=>`import { ${e} } from './${e}.js';`),n=l.map(({safeName:e,componentId:n})=>` init.blockComponentRegistry.registerCustomComponent('${n}', ${e});`),o=["// Auto-generated by sapdon.","import { system } from '@minecraft/server';","",...e,"","system.beforeEvents.startup.subscribe((init) => {",...n,"});",""].join("\n");O(r,o),console.log(`已生成自定义组件注册索引: ${r}`)}}await async function(e,n,o){const t=e("textures/items"),i=e("textures/item_texture.json");await async function(e,n,o,t){try{const i=await H(e,e,"textures/items/");t&&Object.assign(i,t);const r={resource_pack_name:o,texture_name:"atlas.items",texture_data:i};await L(n,r,"Item texture JSON file generated successfully.")}catch(e){console.error("Error generating item texture JSON:",e)}}(t,i,n,o.item);const r=e("textures/blocks"),s=e("textures/terrain_texture.json");await async function(e,n,o,t){try{const i=await H(e,e,"textures/blocks/");t&&Object.assign(i,t);const r={texture_name:"atlas.terrain",resource_pack_name:o,padding:8,num_mip_levels:4,texture_data:i};await L(n,r,"Block texture JSON file generated successfully.")}catch(e){console.error("Error generating block texture JSON:",e)}}(r,s,n,o.block);const c=e("textures/flipbook_textures.json");O(c,JSON.stringify(o.flipbook,null,2))}(s,t,a),console.log(`已加载并执行 ${e} 文件!`)}catch(n){console.error(`加载或执行 ${e} 失败:${n.message}`),console.error(n.stack)}};class K{name;description;version;uuid;allow_random_seed;lock_template_options;pack_scope;base_game_version;min_engine_version;constructor(e,n,o,t,i={}){this.name=e,this.description=n,this.version=o,this.uuid=t,this.allow_random_seed=i.allow_random_seed,this.lock_template_options=i.lock_template_options,this.pack_scope=i.pack_scope,this.base_game_version=i.base_game_version,this.min_engine_version=i.min_engine_version}}class Q{description;type;uuid;version;constructor(e,n,o,t){this.description=e,this.type=n,this.uuid=o,this.version=t}}class X{authors;license;generated_with;product_type;url;constructor(e,n,o,t,i){this.authors=e,this.license=n,this.generated_with=o,this.product_type=t,this.url=i}}class Y{format_version;header;modules;dependencies;capabilities;metadata;constructor(e,n,o,t,i=null,r=null){this.format_version=e,this.header=n,this.modules=o,this.dependencies=t,null!=i&&(this.capabilities=i),null!=r&&(this.metadata=r)}}const Z=process.env.MC_PATH,ee=process.env.MC_BETA_PATH,ne="AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang",oe="AppData/Local/Packages/Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe/LocalState/games/com.mojang/";function te(){return"beta"===J().versionType?N("McInstallPath.Beta",()=>ee||o.join(h.homedir(),oe)):N("McInstallPath.Main",()=>Z||o.join(h.homedir(),ne))}var ie={name:"sapdon",version:"3.5.3",scripts:{build:"node scripts/build.cjs",test:'tsc && tsc-alias && node --test "tests/*.test.mjs"',"build:demo":"cd examples/block_demo && npm run build",pub:"npm run build && npm publish"},keywords:["bedrock","tools","addon"],author:"Meteage",license:"ISC",type:"module",bin:{sapdon:"prod/cli/start.js"},description:"Sapdon is a Node.js toolkit designed for building Bedrock Edition Minecraft addon packs.",devDependencies:{"@minecraft/server":"^2.0.0-beta.1.21.80-preview.20","@minecraft/server-ui":"^1.3.0","@types/archiver":"^6.0.0","@types/d3-array":"^3.2.1","@types/lodash":"^4.17.16","@types/node":"^22.14.0","tsc-alias":"^1.8.13"},dependencies:{"@rollup/plugin-commonjs":"^28.0.2","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^16.0.0","@rollup/plugin-terser":"^0.4.4","@rollup/plugin-typescript":"^12.1.2",chalk:"^5.4.1",commander:"^13.0.0","d3-array":"^3.2.4",archiver:"^7.0.0","download-git-repo":"^3.0.2",inquirer:"^12.3.1",lodash:"^4.17.21",ora:"^8.1.1",rollup:"^4.39.0","rollup-plugin-dts":"^6.2.1","rollup-plugin-typescript-paths":"^1.5.0","rollup-plugin-visualizer":"^5.14.0","tsconfig-paths":"^4.2.0",tslib:"^2.8.1",typescript:"^5.8.2"},files:["prod/**/*","doc/**/*"]};function re(){return N(o.join(x(import.meta),"../../../package.json"),()=>ie)}async function se(e,n){const t=J(),r=o.join(e,t.buildOptions.buildDir),s=o.join(r,`${n}_BP`),c=o.join(r,`${n}_RP`);i.cpSync(s,o.join(te(),"development_behavior_packs/",`${n}_BP/`),{recursive:!0,force:!0}),i.cpSync(c,o.join(te(),"development_resource_packs/",`${n}_RP/`),{recursive:!0,force:!0})}async function ce(e){const n=o.join(e,"node_modules"),t=o.join(x(import.meta),"../"),r=o.join(t,"core"),s=o.join(t,"cli"),c=o.join(t,"oc"),a=o.join(n,"@sapdon/core"),l=o.join(n,"@sapdon/cli"),p=o.join(n,"@sapdon/runtime"),u=re();i.cpSync(r,a,{recursive:!0,force:!0}),i.cpSync(s,l,{recursive:!0,force:!0}),i.cpSync(c,p,{recursive:!0,force:!0}),i.writeFileSync(o.join(a,"package.json"),JSON.stringify({name:"@sapdon/core",type:"module",main:"index.js",types:"index.d.ts",version:u.version})),i.writeFileSync(o.join(l,"package.json"),JSON.stringify({name:"@sapdon/cli",type:"module",main:"index.js",types:"index.d.ts",version:u.version})),i.writeFileSync(o.join(p,"package.json"),JSON.stringify({name:"@sapdon/runtime",type:"module",main:"index.js",types:"index.d.ts",version:u.version}))}const ae=t(import.meta.url);o.dirname(ae);const le=["rollup","typescript","@sapdon/core","@sapdon/cli","@minecraft"],pe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;const ue={js:async(e,n,o)=>{const t=J();try{const i=await p({input:e,plugins:[d({preferBuiltins:!0}),u(),g(),..."prod"===t.buildOptions.buildMode?[y()]:[]],external(e){for(const n of le)if(e.includes(n))return!0;return!1}});await i.write({file:n,format:"esm",sourcemap:o}),i.close()}catch(e){console.error(e)}},ts:async(e,n,t)=>{const i=E(),r=J(),s={file:n,format:"esm",sourcemap:t};try{const n=await p({input:e,plugins:[f(),d({preferBuiltins:!0}),m({tsconfig:o.join(i,"tsconfig.json"),compilerOptions:{outDir:o.dirname(s.file)}}),u(),g(),..."prod"===r.buildOptions.buildMode?[y()]:[]],external(e){for(const n of le)if(e.includes(n))return!0;return!1}});await n.write(s),n.close()}catch(e){console.error(e)}},any:async(e,n)=>{J().buildOptions.useJs?await ue.js(e,n):await ue.ts(e,n)}};async function de(e){const n="."+crypto.randomUUID()+".js",t=o.join(o.dirname(e),".tmp",n);await ue.any(e,t);try{await async function(e){const{promise:n,resolve:o}=Promise.withResolvers();return c.fork(e,{stdio:"inherit"}).on("exit",o),n}(t)}catch(e){console.error(e)}finally{i.rmSync(t,{force:!0})}}function me(e){return console.log("开始构建项目"),console.log("项目路径:"+e),w(e)?(console.log("项目不存在"),!1):!w(o.join(e,"build.config"))||(console.log("项目没有build.config文件"),!1)}const fe=async(e,n)=>{const t=J(),r=o.join(e,"mod.info"),s=JSON.parse(_(r)),c=ge(s.min_engine_version),a=o.join(e,t.buildOptions.buildDir),l=o.join(a,`${n}_BP/`),p=o.join(a,`${n}_RP/`),u=o.join(e,t.buildOptions.buildEntry);if(!z.isListening()){const i=o.join(l,"manifest.json");if(w(i)){const e=function(e,n){if("string"==typeof n.bp&&pe.test(n.bp)&&"string"==typeof n.rp&&pe.test(n.rp))return{bp:n.bp,rp:n.rp};const o={bp:S(),rp:S()};return O(e,JSON.stringify({...n,...o},null,2)),console.log("已在 mod.info 生成持久化 UUID 用于 BP/RP 交叉绑定"),o}(r,s),n=ge(s.version),i=ye(s.name,s.description,s.version,{min_engine_version:c},t.buildOptions.dependencies,t.buildOptions.scriptOutput,e.bp,e.rp,n),a=he(s.name,s.description,s.version,{min_engine_version:c},[],e.bp,e.rp,n);O(o.join(l,"manifest.json"),i),O(o.join(p,"manifest.json"),a)}const d=o.join(e,"pack_icon.png");v(d,o.join(l,"pack_icon.png")),v(d,o.join(p,"pack_icon.png"));const m=t.buildOptions.resource,f=o.join(e,m.path);k(f,p),z.isListening()||z.bootstrap(),G.startServer(),z.handle("submit",async e=>{"debug"!==t.buildOptions.buildMode&&(G.dataList=e,await q(u,a,n))})}await de(u),await async function(e=!1){const n=e?"js":"ts",t=E(),r=J(),{scriptEntry:s,scriptOutput:c,buildMode:a}=r.buildOptions,l=o.join(B(),c);i.mkdirSync(o.dirname(l),{recursive:!0}),await ue[n](o.join(t,s),l,"dev"===a)}(t.buildOptions.useJs),await se(e,n),J().buildOptions.keepServer||(console.log("[sapdon] 构建完成,开发服务器已自动退出。"),console.log('[sapdon] 如需保持服务器常开(HMR / 热更新),请在 build.config 中设置 "buildOptions.keepServer": true'),process.exit(0))};function ge(e){return e.split(".").map(e=>Number(e))}const ye=(e,n,o,t={},i=[],r,s,c,a)=>{console.log("开始生成behavior_packs/manifest.json"),console.log("Entry:",r);const l=new K(e+"_BP",n,a,s,t),p=new Q("行为模块","data",S(),a),u=new Q("脚本模块","script",S(),a);r&&(u.entry=r);const d=new X(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),m=new Y(2,l,[p,u],[...i,{uuid:c,version:a}],null,d);return JSON.stringify(m,null,2)},he=(e,n,o,t={},i=[],r,s,c)=>{const a=new K(e+"_RP",n,c,s,t),l=new Q("资源模块","resources",S(),c),p=new X(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),u=new Y(2,a,[l],[...i,{uuid:r,version:c}],null,p);return JSON.stringify(u,null,2)},je="import fs from 'fs'\nexport class FileResource {\n static cache: Record<string, FileResource> = {}\n static fileSystemLoader = (uri: string) => fs.readFileSync(uri)\n\n private _res: any\n\n /**\n * 不要调用构造器!\n * 使用 FileResource.get(uri) 方法获取实例\n * @param origin \n */\n constructor(public origin: string) {\n this.origin = origin\n FileResource.cache[origin] = this\n }\n\n /**\n * @param uri \n * @returns {FileResource}\n */\n static get(uri: string) {\n if (uri in FileResource.cache) {\n return FileResource.cache[uri]\n }\n return new FileResource(uri)\n }\n\n load(loader=FileResource.fileSystemLoader) {\n if (this._res) {\n return this._res\n }\n const content = loader(this.origin)\n this._res = content\n return content\n }\n\n clear() {\n delete FileResource.cache[this.origin]\n }\n\n loadWithoutCache(loader=FileResource.fileSystemLoader) {\n return loader(this.origin)\n }\n\n ptr() {\n const func = () => this.load()\n return Object.assign(func, this)\n }\n}",be=j.debounce;function Se(e,n,t){i.readdirSync(e).forEach(r=>{const s=o.join(e,r);i.statSync(s).isDirectory()?(t(r,e),Se(s,n,t)):n(r,e)})}var ve;function we(e){return e.replaceAll(".","_").replaceAll("-","_").replaceAll("@","$")}function _e(e){const n={type:ve.Dir,name:e,children:{}},t={[e]:n};let i=n;return Se(e,(e,n)=>{const t=o.basename(e),r=we(t.slice(0,t.lastIndexOf("."))),s={type:ve.File,name:r,origin:o.join(n,e)};i.children[r]=s},(e,n)=>{const r=we(e),s=t[n],c={type:ve.Dir,name:r,children:{}};s.children[r]=c,t[o.join(n,e)]=c,i=c}),n}function Oe(e){return!!i.existsSync(o.join(e,"build.config"))||(console.log("无法生成资源目录,请 cd 到项目根目录下执行 sapdon res"),!1)}function ke(){const{buildOptions:e}=J();if(e.buildEntry.endsWith("js"))return;const n=process.cwd(),t=o.join(n,"res");if(!Oe(n))return;i.existsSync(t)||i.mkdirSync(t);!function(e,n){const o={};!function e(n,o){for(const t in n.children){const i=n.children[t];if(i.type===ve.File)o[i.name]=`<fn>${i.origin}</fn>`;else{const n={};o[i.name]=n,e(i,n)}}}(e,o);const t=[je].join(";\n"),r=`\n;export default ${JSON.stringify(o,null,2)}`.replace(/"\<fn\>(.*)\<\/fn\>"/g,"FileResource.get('$1').ptr()");i.writeFileSync(n,t+r)}(_e(t),o.join(n,"res.hint.ts"))}!function(e){e[e.File=0]="File",e[e.Dir=1]="Dir"}(ve||(ve={}));const xe=j.debounce;function $e(e,n){const{buildDir:t,useHMR:r}=J().buildOptions;!function(){const e=process.cwd();Oe(e)&&i.watch(o.join(e,"res"),{recursive:!0},be((e,n)=>{c.execSync("sapdon res")},3e3))}(),r&&i.watch(e,{recursive:!0},xe(async(i,r)=>{i&&r&&(r.startsWith(".")||r.startsWith("node_modules")||r.startsWith(o.join(t,"./"))||r.includes(".tmp")||(r.endsWith(".js")||r.endsWith(".ts")||"build.config"===r||"mod.info"===r)&&(process.stdout.write(`File ${r} changed, reloading...\r`),await fe(e,n),await se(e,n),console.log(`Reloaded ${r}`)))}),1e3)}const Ne=t(import.meta.url),Je=o.dirname(Ne);process.removeAllListeners("warning"),e.command("init").description("初始化一个基于NodeJS的项目").action(()=>{const e=process.cwd(),t=o.join(e,"package.json");let r;if(i.existsSync(t)){try{r=JSON.parse(i.readFileSync(t,"utf-8"))}catch(e){return console.error("读取package.json文件时出错:",e),void console.log("请使改用create命令进行创建。")}r.scripts={...r.scripts,init:"sapdon init",compile:"sapdon compile",config:"sapdon config"};try{i.writeFileSync(t,JSON.stringify(r,null,2),"utf-8")}catch(e){return void console.error("写入package.json文件时出错:",e)}n.prompt([{type:"input",name:"min_engine_version",message:"最低引擎版本:",default:"1.19.50"}]).then(n=>{((e,n)=>{if(!(w(o.join(e,"mod.info"))&&w(o.join(e,"main.mjs"))&&w(o.join(e,"scripts"))&&w(o.join(e,"build.config"))))return void console.log("项目已存在...");const t=o.join(F,"../templates/js_sapdon");k(t,e),O(o.join(e,"mod.info"),JSON.stringify({...n,bp:S(),rp:S()},null,2))})(e,{...D(e),...n}),console.log("请使用命令sapdon config配置框架的build.config文件。")})}else console.error("没有找到package.json文件,请使改用create命令进行创建。")}),e.command("create <project-name>").description("Create a new project").action(e=>{n.prompt([{type:"input",name:"name",message:"Project Name:",default:o.basename(e)},{type:"input",name:"description",message:"Project Description:",default:"A new sapdon project"},{type:"input",name:"author",message:"Author Name:",default:"Sapdon"},{type:"input",name:"version",message:"Project Version:",default:"1.0.0"},{type:"input",name:"min_engine_version",message:"Minimum Engine Version:",default:"1.19.50"},{type:"input",name:"language",message:"Language:(js/ts)",default:"ts"}]).then(n=>{const t=o.join(process.cwd(),e);console.log("项目路径:",t),((e,n)=>{if(console.log(1,n),!w(e))return void console.log("项目名称已存在,创建项目目录失败");const t=o.join(F,`../templates/${P[n.language||"js"]}`);k(t,e),O(o.join(e,"mod.info"),JSON.stringify({...n,bp:S(),rp:S()},null,2)),c.execSync("npm i",{cwd:e,stdio:"inherit"})})(t,n),ce(t)})}),e.command("build <project-name>").description("Build the project").action(e=>{console.log("Building the project...");const n=o.join(process.cwd(),e),t=o.basename(n);M.projectPath=n,ke(),me(n)&&(fe(n,t),$e(n,t))}),e.command("compile").description("Compile the current project (build without HMR)").action(()=>{console.log("Compiling the current project...");const e=process.cwd();me(e)&&fe(e,o.basename(e))}),e.command("pack").description("Package build output into .mcaddon file").action(async()=>{const e=process.cwd(),n=o.basename(e);M.projectPath=e,await(async e=>{const n=E(),t=J(),r=o.join(n,t.buildOptions.buildDir),s=o.join(r,`${e}_BP`),c=o.join(r,`${e}_RP`);if(!i.existsSync(s)||!i.existsSync(c))return void console.error("构建输出目录不存在,请先运行 sapdon compile");const a=o.join(r,`${e}.mcaddon`),l=i.createWriteStream(a),p=b("zip",{zlib:{level:9}});l.on("close",()=>{console.log(`打包完成: ${a} (${p.pointer()} bytes)`)}),p.on("error",e=>{throw e}),p.pipe(l),p.directory(s,`${e}_BP`),p.directory(c,`${e}_RP`),await p.finalize()})(n)}),e.command("lib").description("Generate lib files for development server.").action(()=>{ce(process.cwd())}),e.command("res").description("Generate resource hints.").action(()=>{ke()}),e.command("config").description("Configure build.config file").action(()=>{const e=o.join(Je,"./build.config");let n;try{n=JSON.parse(_(e))}catch(e){return void console.error("读取build.config文件时出错:",e)}}),e.parse(e.argv);
2
+ import{program as e}from"commander";import n from"inquirer";import o from"path";import{fileURLToPath as t}from"url";import i from"fs";import{randomUUID as s}from"crypto";import{fileURLToPath as r}from"node:url";import c from"child_process";import a from"fs/promises";import l from"http";import{rollup as u}from"rollup";import p from"@rollup/plugin-commonjs";import{nodeResolve as d}from"@rollup/plugin-node-resolve";import m from"@rollup/plugin-typescript";import{typescriptPaths as f}from"rollup-plugin-typescript-paths";import g from"@rollup/plugin-json";import"rollup-plugin-visualizer";import y from"@rollup/plugin-terser";import h from"os";import j from"lodash";import b from"archiver";const S=()=>s();function _(e,n){try{i.copyFileSync(e,n)}catch(e){console.error("文件复制失败:",e)}}const v=e=>!i.existsSync(e),w=e=>{try{return i.readFileSync(e,"utf8")}catch(e){console.log(e)}return null},$=(e,n)=>{i.mkdirSync(o.dirname(e),{recursive:!0}),i.writeFileSync(e,n)},O=(e,n)=>{if(i.mkdirSync(o.dirname(n),{recursive:!0}),!i.existsSync(e))return void console.log(`Source path ${e} does not exist.`);i.existsSync(n)||i.mkdirSync(n);i.readdirSync(e).forEach(t=>{const s=o.join(e,t),r=o.join(n,t);i.lstatSync(s).isDirectory()?O(s,r):i.copyFileSync(s,r)})};function x(e){const n=r(e.url);return o.dirname(n)}const k=new Map;function N(e,n){let o=k.get(e);return o||(o=n(e),k.set(e,o),o)}function J(){const e=B(),n=o.join(e,"build.config");if(!i.existsSync(n))throw new Error("未找到项目配置文件,请先初始化项目");return N(n,e=>function(e){const n=(o=i.readFileSync(e),JSON.parse(String(o).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/g,"$1")));var o;if(2===n.formatVersion)return n;const t=function({defaultConfig:e,resources:n,scripts:o}){const t={formatVersion:2,buildOptions:{useHMR:!0,buildMode:"dev",buildEntry:e.buildEntry,scriptEntry:e.scriptEntry,scriptOutput:e.scriptEntry.replace(".ts",".js"),useJs:"ts"!==o[0].type,buildDir:e.buildDir,dependencies:e.dependencies,resource:{path:n[0].path,resourceHints:!0}},versionType:"release"};return t}(n);return i.writeFileSync(e,JSON.stringify(t,null,2)),t}(e))}const P=t(import.meta.url),R=o.dirname(P),F={js:"js_sapdon",ts:"ts_sapdon"},D=e=>{const n=o.join(e,"package.json");if(!i.existsSync(n))return null;try{const t=JSON.parse(i.readFileSync(n,"utf-8"));return{name:o.basename(e),description:t.description||"A new sapdon project",author:t.author||"Sapdon",version:t.version||"1.0.0"}}catch(e){return console.error("读取package.json文件时出错:",e),null}},E={};function B(){const e=E.projectPath??process.cwd();if(!i.existsSync(o.join(e,"build.config")))throw new Error("无效的项目路径");return e}function M(){const{buildDir:e}=J().buildOptions,n=N("projectName",()=>o.basename(B()));return o.join(B(),e,n+"_BP")}const A=async(e,n,t="")=>{const i={};try{await a.access(e)}catch{return i}const s=await a.readdir(e);for(const r of s){const s=o.join(e,r);if((await a.stat(s)).isDirectory()){const e=await A(s,n,t);Object.assign(i,e)}else if(r.endsWith(".png")){const e=o.basename(r,".png"),c=`${t}${o.relative(n,s).replace(/\.png$/,"").replace(/\\/g,"/")}`;i[e]={textures:c}}}return i},L=async(e,n,o)=>{try{const t=JSON.stringify(n,null,2);await a.writeFile(e,t),console.log(o)}catch(e){console.error("Error writing JSON file:",e)}};const H={port:function(){const e=process.env.SAPDON_DEV_SERVER_PORT,n=e?parseInt(e,10):NaN;return Number.isInteger(n)&&n>0?n:49037}()};Symbol.metadata||(Symbol.metadata=Symbol("[[metadata]]"));const I=Symbol("isRawJSON");const W=["boolean","number"],C=["string","undefined"];function T(e,n){const o=typeof n;if(null===o)return null;if(C.includes(o))return n;if(W.includes(o))return JSON.rawJSON(n);if("object"===o)return JSON.isRawJSON(n)?n:function(e){return!0===e?.[I]}(n)?JSON.rawJSON(n.rawJSON):n;if("bigint"===o)return JSON.rawJSON(n.toString());throw new Error("Unexpected value")}const U={encode:e=>JSON.stringify(e,T),decode:JSON.parse};const{port:V}=H;const z=new class{cliServerHandlers=new Map;listening=!1;isListening(){return this.listening}bootstrap(){this.listening=!0;const e=l.createServer(async(e,n)=>{const o=this.cliServerHandlers.get((e.url??"/").slice(1));if(o){try{const{promise:n,resolve:t,reject:i}=Promise.withResolvers();let s=Buffer.alloc(0);e.on("data",e=>s=Buffer.concat([s,e])),e.on("end",()=>{try{t(function(e,n=U){return n.decode(e)}(s))}catch(e){i(e)}}),await o(...await n)}catch(e){return console.error(e),n.writeHead(500),void n.end()}n.writeHead(200),n.end()}else n.writeHead(404),n.end()}).listen(V,()=>console.log(`Dev Server listening on port ${V}`));return e.on("error",e=>{throw this.listening=!1,function(e){return"object"==typeof e&&null!==e&&"EADDRINUSE"===e.code}(e)&&(console.error(`[sapdon] Dev Server 端口 ${V} 已被其他 sapdon 进程占用。`),console.error("[sapdon] 请先结束残留的 sapdon 进程,再重新构建,否则本次构建的数据可能被写入错误的包目录。"),process.exit(1)),e}),e}handle(e,n){this.cliServerHandlers.set(e,n)}getHandler(e){return this.cliServerHandlers.get(e)}interceptHandler(e,n){const o=n(this.getHandler(e)??Function.prototype);return this.cliServerHandlers.set(e,o),o}};async function G({level:e,message:n,timeStamp:o,stack:t}){console[e](n,t,`\nat ${new Date(o).toLocaleString()}`)}class q{static dataList=[];static getDataList(){return[...this.dataList]}static startServer(){z.handle("submitGregistry",e=>{this.dataList=e}),z.handle("remote-logger",G)}}const X=(e,n)=>o.join(e,`.sapdon_generated_${n}.json`);function K(e,n){const o=n.map(({safeName:e})=>`import { ${e} } from './${e}.js';`),t=n.map(({safeName:e,componentId:n})=>` init.blockComponentRegistry.registerCustomComponent('${n}', ${e});`),s=[Q,`import { system as ${ee} } from '@minecraft/server';`,"",...o,"",`${ee}.beforeEvents.startup.subscribe((init) => {`,...t,"});",Y].join("\n");if(!i.existsSync(e))return $(e,s+"\n"),void console.log(`已生成自定义组件注册索引: ${e}`);const r=i.readFileSync(e,"utf-8"),c=function(e){const n=[],o=(e,o)=>{o>e&&n.push({start:e,end:o})},t=e.indexOf(Q);if(-1!==t){const n=e.indexOf(Y,t);n>t&&o(t,n+Y.length)}const i=e.indexOf(Z);if(-1!==i&&!n.some(e=>i>=e.start&&i<e.end)){const n=e.indexOf("system.beforeEvents.startup.subscribe(",i);let t=-1;if(-1!==n){const o=e.indexOf("\n});",n);-1!==o&&(t=o+4)}o(i,-1===t?e.length:t)}return n.sort((e,n)=>e.start-n.start)}(r);if(0===c.length){const n=r.endsWith("\n")?"":"\n";return $(e,`${r}${n}\n${s}\n`),void console.log(`已在既有注册索引末尾追加自动注册块(原内容保留): ${e}`)}let a="",l=0,u=!1;for(const e of c)a+=r.slice(l,e.start),u||(a+=ne,u=!0),l=e.end;a+=r.slice(l),a=a.replace(ne,s),a=a.replace(/\n{3,}/g,"\n\n").replace(/^\n+/,""),a.endsWith("\n")||(a+="\n"),a!==r?($(e,a),console.log(`已更新自定义组件注册索引(保留手写部分,共 ${n.length} 个组件): ${e}`)):console.log(`自定义组件注册索引已是最新,未改动: ${e}`)}const Q="// >>> sapdon:custom-component-registry (auto-generated, 请勿手改本块) >>>",Y="// <<< sapdon:custom-component-registry <<<",Z="// Auto-generated by sapdon.",ee="__sapdon_system",ne="\0SAPDON_INDEX_SLOT\0",oe=async(e,n,t)=>{try{o.join(n,`${t}_BP`);const s=o.join(n,`${t}_RP`),r=(...e)=>o.join(s,...e),c=function(e,n){const o=X(e,n);try{const e=JSON.parse(i.readFileSync(o,"utf-8"));if(e&&1===e.v&&Array.isArray(e.files))return{files:e.files,existed:!0}}catch{}return{files:[],existed:!1}}(n,t);!function(e,n){const t=`${n}_BP/blocks.json`,s=o.join(e,t);i.existsSync(s)&&(i.rmSync(s,{force:!0}),console.log(`已删除历史误放产物 ${t}(blocks.json 规范属资源包 RP,框架不会再往 BP 写)`))}(n,t);const a=[],l=e=>{a.push(o.relative(n,e))},u=q.getDataList(),p={item:null,block:null,flipbook:[]},d=[];for(const{name:s,root:r,path:c,data:a}of u){switch(console.log("处理数据:",s,r,c),s){case"item_texture":p.item=a,console.log("用户物品贴图数据:",p.item);continue;case"terrain_texture":p.block=a,console.log("用户方块贴图数据:",p.block);continue;case"flipbook_textures":p.flipbook=a,console.log("用户翻书贴图数据:",p.flipbook);continue}if(a._scriptSource){const n=o.dirname(e),t=o.join(n,c,`${s}.js`);i.existsSync(t)?console.log(`自定义组件脚本已存在,跳过: ${t}`):($(t,a.source),console.log(`已生成自定义组件脚本: ${t}`)),d.push({safeName:s,componentId:a.componentId});continue}const u="behavior"===r?`${t}_BP`:`${t}_RP`,m=o.join(n,u),f=o.join(m,c,`${s}.json`);$(f,JSON.stringify(a,null,2)),l(f)}if(d.length>0){const n=o.dirname(e),t=o.join(n,"scripts","custom_components");K(o.join(t,"index.js"),d)}await async function(e,n,o,t=()=>{}){const i=e("textures/items"),s=e("textures/item_texture.json");await async function(e,n,o,t){try{const i=await A(e,e,"textures/items/");t&&Object.assign(i,t);const s={resource_pack_name:o,texture_name:"atlas.items",texture_data:i};await L(n,s,"Item texture JSON file generated successfully.")}catch(e){console.error("Error generating item texture JSON:",e)}}(i,s,n,o.item),t(s);const r=e("textures/blocks"),c=e("textures/terrain_texture.json");await async function(e,n,o,t){try{const i=await A(e,e,"textures/blocks/");t&&Object.assign(i,t);const s={texture_name:"atlas.terrain",resource_pack_name:o,padding:8,num_mip_levels:4,texture_data:i};await L(n,s,"Block texture JSON file generated successfully.")}catch(e){console.error("Error generating block texture JSON:",e)}}(r,c,n,o.block),t(c);const a=e("textures/flipbook_textures.json");$(a,JSON.stringify(o.flipbook,null,2)),t(a)}(r,t,p,l),function(e,n,t){const s=new Set(t);let r=0;for(const t of n){if(s.has(t))continue;const n=o.join(e,t);i.existsSync(n)&&(i.rmSync(n,{force:!0}),r++,console.log(`已清理陈旧产物: ${t}`))}}(n,c.files,a),function(e,n,o){$(X(e,n),JSON.stringify({v:1,note:"sapdon 生成物清单:本次构建写出的产物文件(相对 dev/ 的路径)。下次构建据此删除不再生成的旧文件。请勿手工编辑。",files:[...o].sort()},null,2))}(n,t,a),console.log(`已加载并执行 ${e} 文件!`)}catch(n){console.error(`加载或执行 ${e} 失败:${n.message}`),console.error(n.stack)}};class te{name;description;version;uuid;allow_random_seed;lock_template_options;pack_scope;base_game_version;min_engine_version;constructor(e,n,o,t,i={}){this.name=e,this.description=n,this.version=o,this.uuid=t,this.allow_random_seed=i.allow_random_seed,this.lock_template_options=i.lock_template_options,this.pack_scope=i.pack_scope,this.base_game_version=i.base_game_version,this.min_engine_version=i.min_engine_version}}class ie{description;type;uuid;version;constructor(e,n,o,t){this.description=e,this.type=n,this.uuid=o,this.version=t}}class se{authors;license;generated_with;product_type;url;constructor(e,n,o,t,i){this.authors=e,this.license=n,this.generated_with=o,this.product_type=t,this.url=i}}class re{format_version;header;modules;dependencies;capabilities;metadata;constructor(e,n,o,t,i=null,s=null){this.format_version=e,this.header=n,this.modules=o,this.dependencies=t,null!=i&&(this.capabilities=i),null!=s&&(this.metadata=s)}}const ce=process.env.MC_PATH,ae=process.env.MC_BETA_PATH,le="AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang",ue="AppData/Local/Packages/Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe/LocalState/games/com.mojang/";function pe(){return"beta"===J().versionType?N("McInstallPath.Beta",()=>ae||o.join(h.homedir(),ue)):N("McInstallPath.Main",()=>ce||o.join(h.homedir(),le))}var de={name:"sapdon",version:"3.6.0",scripts:{build:"node scripts/build.cjs",test:'tsc && tsc-alias && node --test "tests/*.test.mjs"',"build:demo":"cd examples/block_demo && npm run build",pub:"npm run build && npm publish"},keywords:["bedrock","tools","addon"],author:"Meteage",license:"ISC",type:"module",bin:{sapdon:"prod/cli/start.js"},description:"Sapdon is a Node.js toolkit designed for building Bedrock Edition Minecraft addon packs.",devDependencies:{"@minecraft/server":"^2.0.0-beta.1.21.80-preview.20","@minecraft/server-ui":"^1.3.0","@types/archiver":"^6.0.0","@types/d3-array":"^3.2.1","@types/lodash":"^4.17.16","@types/node":"^22.14.0","tsc-alias":"^1.8.13"},dependencies:{"@rollup/plugin-commonjs":"^28.0.2","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^16.0.0","@rollup/plugin-terser":"^0.4.4","@rollup/plugin-typescript":"^12.1.2",chalk:"^5.4.1",commander:"^13.0.0","d3-array":"^3.2.4",archiver:"^7.0.0","download-git-repo":"^3.0.2",inquirer:"^12.3.1",lodash:"^4.17.21",ora:"^8.1.1",rollup:"^4.39.0","rollup-plugin-dts":"^6.2.1","rollup-plugin-typescript-paths":"^1.5.0","rollup-plugin-visualizer":"^5.14.0","tsconfig-paths":"^4.2.0",tslib:"^2.8.1",typescript:"^5.8.2"},files:["prod/**/*","doc/**/*"]};function me(){return N(o.join(x(import.meta),"../../../package.json"),()=>de)}function fe(e,n=""){const t=[];let s;try{s=i.readdirSync(e,{withFileTypes:!0})}catch{return t}for(const i of s){const s=n?`${n}/${i.name}`:i.name;i.isDirectory()?t.push(...fe(o.join(e,i.name),s)):t.push(s)}return t}function ge(e,n){let t=n;for(;t&&t!==e&&t.startsWith(e);){let e=!1;try{e=0===i.readdirSync(t).length}catch{return}if(!e)return;try{i.rmdirSync(t)}catch{return}t=o.dirname(t)}}async function ye(e,n){const t=J(),s=o.join(e,t.buildOptions.buildDir),r=pe(),c=[{name:`${n}_BP`,src:o.join(s,`${n}_BP`),destRoot:o.join(r,"development_behavior_packs")},{name:`${n}_RP`,src:o.join(s,`${n}_RP`),destRoot:o.join(r,"development_resource_packs")}],a=((e,n,t)=>o.join(e,n,`.sapdon_synced_${t}.json`))(e,t.buildOptions.buildDir,n),l=function(e){try{const n=JSON.parse(i.readFileSync(e,"utf-8"));if(n&&1===n.v&&Array.isArray(n.files))return{files:n.files,existed:!0}}catch{}return{files:[],existed:!1}}(a),u=[];for(const e of c){const n=o.join(e.destRoot,e.name),t=fe(e.src);if(l.existed){const s=l.files.filter(n=>n.startsWith(`${e.name}/`));if(0===t.length&&s.length>0)console.warn(`[sapdon] ${e.name} 的 dev/ 目录为空,跳过本次陈旧产物清理(疑似构建中断)。如需清空游戏里的旧包,请手工删除 ${n}`);else{const r=new Set(t.map(n=>`${e.name}/${n}`));for(const t of s){if(r.has(t))continue;const s=o.join(n,o.relative(e.name,t));i.existsSync(s)&&(i.rmSync(s,{force:!0}),console.log(`已清理游戏目录中的陈旧产物: ${t}`),ge(n,o.dirname(s)))}}}for(const n of t)u.push(`${e.name}/${n}`)}i.cpSync(o.join(s,`${n}_BP`),o.join(r,"development_behavior_packs/",`${n}_BP/`),{recursive:!0,force:!0}),i.cpSync(o.join(s,`${n}_RP`),o.join(r,"development_resource_packs/",`${n}_RP/`),{recursive:!0,force:!0}),function(e,n){i.mkdirSync(o.dirname(e),{recursive:!0}),i.writeFileSync(e,JSON.stringify({v:1,note:"sapdon 部署清单:上一次同步到「游戏开发包目录」的文件(相对 dev/ 的路径)。下次同步据此删除不再生成的旧文件。请勿手工编辑。",files:[...n].sort()},null,2))}(a,u)}function he(e,n,t,s){const r=((e,n,t)=>o.join(e,n,`.sapdon_res_${t}.json`))(e,J().buildOptions.buildDir,n),c=fe(t),a=new Set(c);let l={files:[],existed:!1};try{const e=JSON.parse(i.readFileSync(r,"utf-8"));e&&1===e.v&&Array.isArray(e.files)&&(l={files:e.files,existed:!0})}catch{}if(l.existed)for(const e of l.files){if(a.has(e))continue;const n=o.join(s,e);i.existsSync(n)&&(i.rmSync(n,{force:!0}),console.log(`已清理 res/ 中已删除的资源: ${e}`),ge(s,o.dirname(n)))}O(t,s),i.mkdirSync(o.dirname(r),{recursive:!0}),i.writeFileSync(r,JSON.stringify({v:1,note:"sapdon 资源清单:上一次从项目 res/ 复制到 dev/<项目>_RP/ 的文件(相对 res/ 的路径)。下次据此删除 res/ 里已不存在的旧文件。请勿手工编辑。",files:[...c].sort()},null,2))}async function je(e){const n=o.join(e,"node_modules"),t=o.join(x(import.meta),"../"),s=o.join(t,"core"),r=o.join(t,"cli"),c=o.join(t,"oc"),a=o.join(n,"@sapdon/core"),l=o.join(n,"@sapdon/cli"),u=o.join(n,"@sapdon/runtime"),p=me();i.cpSync(s,a,{recursive:!0,force:!0}),i.cpSync(r,l,{recursive:!0,force:!0}),i.cpSync(c,u,{recursive:!0,force:!0}),i.writeFileSync(o.join(a,"package.json"),JSON.stringify({name:"@sapdon/core",type:"module",main:"index.js",types:"index.d.ts",version:p.version})),i.writeFileSync(o.join(l,"package.json"),JSON.stringify({name:"@sapdon/cli",type:"module",main:"index.js",types:"index.d.ts",version:p.version})),i.writeFileSync(o.join(u,"package.json"),JSON.stringify({name:"@sapdon/runtime",type:"module",main:"index.js",types:"index.d.ts",version:p.version}))}const be=t(import.meta.url);o.dirname(be);const Se=["rollup","typescript","@sapdon/core","@sapdon/cli","@minecraft"],_e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;const ve={js:async(e,n,o)=>{const t=J();try{const i=await u({input:e,plugins:[d({preferBuiltins:!0}),p(),g(),..."prod"===t.buildOptions.buildMode?[y()]:[]],external(e){for(const n of Se)if(e.includes(n))return!0;return!1}});await i.write({file:n,format:"esm",sourcemap:o}),i.close()}catch(n){throw new Error(`脚本打包失败(${e}):${n?.message??n}`)}},ts:async(e,n,t)=>{const i=B(),s=J(),r={file:n,format:"esm",sourcemap:t};try{const n=await u({input:e,plugins:[f(),d({preferBuiltins:!0}),m({tsconfig:o.join(i,"tsconfig.json"),compilerOptions:{outDir:o.dirname(r.file)}}),p(),g(),..."prod"===s.buildOptions.buildMode?[y()]:[]],external(e){for(const n of Se)if(e.includes(n))return!0;return!1}});await n.write(r),n.close()}catch(n){throw new Error(`脚本打包失败(${e}):${n?.message??n}`)}},any:async(e,n)=>{J().buildOptions.useJs?await ve.js(e,n):await ve.ts(e,n)}};async function we(e){const n="."+crypto.randomUUID()+".js",t=o.join(o.dirname(e),".tmp",n);await ve.any(e,t);try{await async function(e){const n=await new Promise((n,o)=>{const t=c.spawn(process.execPath,[e],{stdio:"inherit"});t.on("error",o),t.on("exit",(e,o)=>n(o?`signal ${o}`:e))});if(0!==n)throw new Error(`构建脚本执行失败(退出代码 ${n}):${e}`)}(t)}finally{i.rmSync(t,{force:!0})}}function $e(e){return console.log("开始构建项目"),console.log("项目路径:"+e),v(e)?(console.log("项目不存在"),!1):!v(o.join(e,"build.config"))||(console.log("项目没有build.config文件"),!1)}const Oe=async(e,n)=>{const t=J(),s=o.join(e,"mod.info"),r=JSON.parse(w(s)),c=xe(r.min_engine_version),a=o.join(e,t.buildOptions.buildDir),l=o.join(a,`${n}_BP/`),u=o.join(a,`${n}_RP/`),p=o.join(e,t.buildOptions.buildEntry);if(!z.isListening()){const i=o.join(l,"manifest.json");if(v(i)){const e=function(e,n){if("string"==typeof n.bp&&_e.test(n.bp)&&"string"==typeof n.rp&&_e.test(n.rp))return{bp:n.bp,rp:n.rp};const o={bp:S(),rp:S()};return $(e,JSON.stringify({...n,...o},null,2)),console.log("已在 mod.info 生成持久化 UUID 用于 BP/RP 交叉绑定"),o}(s,r),n=xe(r.version),i=ke(r.name,r.description,r.version,{min_engine_version:c},t.buildOptions.dependencies,t.buildOptions.scriptOutput,e.bp,e.rp,n),a=Ne(r.name,r.description,r.version,{min_engine_version:c},[],e.bp,e.rp,n);$(o.join(l,"manifest.json"),i),$(o.join(u,"manifest.json"),a)}const d=o.join(e,"pack_icon.png");_(d,o.join(l,"pack_icon.png")),_(d,o.join(u,"pack_icon.png"));const m=t.buildOptions.resource,f=o.join(e,m.path);he(e,n,f,u),z.isListening()||z.bootstrap(),q.startServer(),z.handle("submit",async e=>{"debug"!==t.buildOptions.buildMode&&(q.dataList=e,await oe(p,a,n))})}await we(p),await async function(e=!1){const n=e?"js":"ts",t=B(),s=J(),{scriptEntry:r,scriptOutput:c,buildMode:a}=s.buildOptions,l=o.join(M(),c);i.mkdirSync(o.dirname(l),{recursive:!0}),await ve[n](o.join(t,r),l,"dev"===a)}(t.buildOptions.useJs),await ye(e,n),J().buildOptions.keepServer||(console.log("[sapdon] 构建完成,开发服务器已自动退出。"),console.log('[sapdon] 如需保持服务器常开(HMR / 热更新),请在 build.config 中设置 "buildOptions.keepServer": true'),process.exit(0))};function xe(e){return e.split(".").map(e=>Number(e))}const ke=(e,n,o,t={},i=[],s,r,c,a)=>{console.log("开始生成behavior_packs/manifest.json"),console.log("Entry:",s);const l=new te(e+"_BP",n,a,r,t),u=new ie("行为模块","data",S(),a),p=new ie("脚本模块","script",S(),a);s&&(p.entry=s);const d=new se(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),m=new re(2,l,[u,p],[...i,{uuid:c,version:a}],null,d);return JSON.stringify(m,null,2)},Ne=(e,n,o,t={},i=[],s,r,c)=>{const a=new te(e+"_RP",n,c,r,t),l=new ie("资源模块","resources",S(),c),u=new se(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),p=new re(2,a,[l],[...i,{uuid:s,version:c}],null,u);return JSON.stringify(p,null,2)},Je="import fs from 'fs'\nexport class FileResource {\n static cache: Record<string, FileResource> = {}\n static fileSystemLoader = (uri: string) => fs.readFileSync(uri)\n\n private _res: any\n\n /**\n * 不要调用构造器!\n * 使用 FileResource.get(uri) 方法获取实例\n * @param origin \n */\n constructor(public origin: string) {\n this.origin = origin\n FileResource.cache[origin] = this\n }\n\n /**\n * @param uri \n * @returns {FileResource}\n */\n static get(uri: string) {\n if (uri in FileResource.cache) {\n return FileResource.cache[uri]\n }\n return new FileResource(uri)\n }\n\n load(loader=FileResource.fileSystemLoader) {\n if (this._res) {\n return this._res\n }\n const content = loader(this.origin)\n this._res = content\n return content\n }\n\n clear() {\n delete FileResource.cache[this.origin]\n }\n\n loadWithoutCache(loader=FileResource.fileSystemLoader) {\n return loader(this.origin)\n }\n\n ptr() {\n const func = () => this.load()\n return Object.assign(func, this)\n }\n}",Pe=j.debounce;function Re(e,n,t){i.readdirSync(e).forEach(s=>{const r=o.join(e,s);i.statSync(r).isDirectory()?(t(s,e),Re(r,n,t)):n(s,e)})}var Fe;function De(e){return e.replaceAll(".","_").replaceAll("-","_").replaceAll("@","$")}function Ee(e){const n={type:Fe.Dir,name:e,children:{}},t={[e]:n};let i=n;return Re(e,(e,n)=>{const t=o.basename(e),s=De(t.slice(0,t.lastIndexOf("."))),r={type:Fe.File,name:s,origin:o.join(n,e)};i.children[s]=r},(e,n)=>{const s=De(e),r=t[n],c={type:Fe.Dir,name:s,children:{}};r.children[s]=c,t[o.join(n,e)]=c,i=c}),n}function Be(e){return!!i.existsSync(o.join(e,"build.config"))||(console.log("无法生成资源目录,请 cd 到项目根目录下执行 sapdon res"),!1)}function Me(){const{buildOptions:e}=J();if(e.buildEntry.endsWith("js"))return;const n=process.cwd(),t=o.join(n,"res");if(!Be(n))return;i.existsSync(t)||i.mkdirSync(t);!function(e,n){const o={};!function e(n,o){for(const t in n.children){const i=n.children[t];if(i.type===Fe.File)o[i.name]=`<fn>${i.origin}</fn>`;else{const n={};o[i.name]=n,e(i,n)}}}(e,o);const t=[Je].join(";\n"),s=`\n;export default ${JSON.stringify(o,null,2)}`.replace(/"\<fn\>(.*)\<\/fn\>"/g,"FileResource.get('$1').ptr()");i.writeFileSync(n,t+s)}(Ee(t),o.join(n,"res.hint.ts"))}!function(e){e[e.File=0]="File",e[e.Dir=1]="Dir"}(Fe||(Fe={}));const Ae=j.debounce;function Le(e,n){const{buildDir:t,useHMR:s}=J().buildOptions;!function(){const e=process.cwd();Be(e)&&i.watch(o.join(e,"res"),{recursive:!0},Pe((e,n)=>{c.execSync("sapdon res")},3e3))}(),s&&i.watch(e,{recursive:!0},Ae(async(i,s)=>{i&&s&&(s.startsWith(".")||s.startsWith("node_modules")||s.startsWith(o.join(t,"./"))||s.includes(".tmp")||(s.endsWith(".js")||s.endsWith(".ts")||"build.config"===s||"mod.info"===s)&&(process.stdout.write(`File ${s} changed, reloading...\r`),await Oe(e,n),await ye(e,n),console.log(`Reloaded ${s}`)))}),1e3)}const He=t(import.meta.url),Ie=o.dirname(He);process.removeAllListeners("warning"),e.command("init").description("初始化一个基于NodeJS的项目").action(()=>{const e=process.cwd(),t=o.join(e,"package.json");let s;if(i.existsSync(t)){try{s=JSON.parse(i.readFileSync(t,"utf-8"))}catch(e){return console.error("读取package.json文件时出错:",e),void console.log("请使改用create命令进行创建。")}s.scripts={...s.scripts,init:"sapdon init",compile:"sapdon compile",config:"sapdon config"};try{i.writeFileSync(t,JSON.stringify(s,null,2),"utf-8")}catch(e){return void console.error("写入package.json文件时出错:",e)}n.prompt([{type:"input",name:"min_engine_version",message:"最低引擎版本:",default:"1.19.50"}]).then(n=>{((e,n)=>{if(!(v(o.join(e,"mod.info"))&&v(o.join(e,"main.mjs"))&&v(o.join(e,"scripts"))&&v(o.join(e,"build.config"))))return void console.log("项目已存在...");const t=o.join(R,"../templates/js_sapdon");O(t,e),$(o.join(e,"mod.info"),JSON.stringify({...n,bp:S(),rp:S()},null,2))})(e,{...D(e),...n}),console.log("请使用命令sapdon config配置框架的build.config文件。")})}else console.error("没有找到package.json文件,请使改用create命令进行创建。")}),e.command("create <project-name>").description("Create a new project").action(e=>{n.prompt([{type:"input",name:"name",message:"Project Name:",default:o.basename(e)},{type:"input",name:"description",message:"Project Description:",default:"A new sapdon project"},{type:"input",name:"author",message:"Author Name:",default:"Sapdon"},{type:"input",name:"version",message:"Project Version:",default:"1.0.0"},{type:"input",name:"min_engine_version",message:"Minimum Engine Version:",default:"1.19.50"},{type:"input",name:"language",message:"Language:(js/ts)",default:"ts"}]).then(n=>{const t=o.join(process.cwd(),e);console.log("项目路径:",t),((e,n)=>{if(console.log(1,n),!v(e))return void console.log("项目名称已存在,创建项目目录失败");const t=o.join(R,`../templates/${F[n.language||"js"]}`);O(t,e),$(o.join(e,"mod.info"),JSON.stringify({...n,bp:S(),rp:S()},null,2)),c.execSync("npm i",{cwd:e,stdio:"inherit"})})(t,n),je(t)})}),e.command("build <project-name>").description("Build the project").action(e=>{console.log("Building the project...");const n=o.join(process.cwd(),e),t=o.basename(n);E.projectPath=n,Me(),$e(n)&&Oe(n,t).then(()=>Le(n,t)).catch(e=>{console.error(`[sapdon] 构建失败:${e?.message??e}`),process.exit(1)})}),e.command("compile").description("Compile the current project (build without HMR)").action(()=>{console.log("Compiling the current project...");const e=process.cwd();$e(e)&&Oe(e,o.basename(e)).catch(e=>{console.error(`[sapdon] 构建失败:${e?.message??e}`),process.exit(1)})}),e.command("pack").description("Package build output into .mcaddon file").action(async()=>{const e=process.cwd(),n=o.basename(e);E.projectPath=e,await(async e=>{const n=B(),t=J(),s=o.join(n,t.buildOptions.buildDir),r=o.join(s,`${e}_BP`),c=o.join(s,`${e}_RP`);if(!i.existsSync(r)||!i.existsSync(c))return void console.error("构建输出目录不存在,请先运行 sapdon compile");const a=o.join(s,`${e}.mcaddon`),l=i.createWriteStream(a),u=b("zip",{zlib:{level:9}});l.on("close",()=>{console.log(`打包完成: ${a} (${u.pointer()} bytes)`)}),u.on("error",e=>{throw e}),u.pipe(l),u.directory(r,`${e}_BP`),u.directory(c,`${e}_RP`),await u.finalize()})(n)}),e.command("lib").description("Generate lib files for development server.").action(()=>{je(process.cwd())}),e.command("res").description("Generate resource hints.").action(()=>{Me()}),e.command("config").description("Configure build.config file").action(()=>{const e=o.join(Ie,"./build.config");let n;try{n=JSON.parse(w(e))}catch(e){return void console.error("读取build.config文件时出错:",e)}}),e.parse(e.argv);