mbler 0.2.1 → 0.2.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/dist/index.js CHANGED
@@ -1,2 +1,1227 @@
1
- "use strict";var e=require("node:process"),n=require("node:fs"),t=require("node:path"),r=require("node:fs/promises"),i=require("node:os"),o=require("readline"),a=require("npm-registry-fetch"),s=require("node:child_process");function c(e){var n=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}}),n.default=e,Object.freeze(n)}var l=c(n),u=c(t),m=c(r),d=c(o);const p=["zh","en"],f=["c","work","help","h","init","version","build","watch","lang","set-work-dir","publish","unpublish","install","uninstall","login"];var h=Object.freeze({__proto__:null,LanguageNames:p,cmdList:f,templateMblerConfig:{name:"demo",description:"demo",version:"0.0.0",mcVersion:"1.21.100",script:{main:""},minify:!1,outdir:{behavior:"",resources:"",dist:""}}}),b="commit da7bebe8ce53a502c75fcc7ad53e510fcb233137\nAuthor: Ruanhor <3915264929@qq.com>\nDate: Sun Apr 19 12:42:06 2026 +0800\n\n feat: use script config when init\n",w="0.2.1",g={description:`MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\n在基岩版我的世界上的 nodejs 构建工具\n命令 : ${f.join(", ")}\n帮助命令 : \n help\n 显示帮助信息\n 第二个参数为要查询的命令名称或空\n 别名: h\ngit https://github.com/RuanhoR/mbler/`,help:{cmds:f,help:"mbler [help/h] [?:查看的命令名称]\n - 查看帮助",h:"$help",work:"mbler [work/c] [?:相对或绝对路径]\n - 没有输入路径:查询当前工作目录\n - 输入路径:设置工作目录",c:"$work",init:"mbler init\n - 初始化当前工作目录,可使用 mbler work 指定工作目录或使用参数一次确定(例: mbler init -in ./)\n - 将会询问选项以完成初始化",build:"mbler build\n - 在工作目录执行构建",watch:"mbler watch\n - 启动构建并开启监视模式,文件变化会自动重新构建",lang:"mbler lang\n- 无参数:显示当前语言\n- 跟 zh 或 en(如 mbler lang en): 设置语言",version:"mbler version - 版本管理命令\n- 无参数:显示当前版本和提交哈希\n- --show=<commit|version>:筛选显示内容\n- <新版本号>:更新package.json和配置文件的版本","set-work-dir":"mbler set-work-dir <on|off>\n - on: 启用工作目录功能\n - off: 禁用工作目录功能,直接使用 process.cwd()",publish:"mbler publish\n - 将你的附加包发布到 pmnx\n- 参数:\n- -tag: 版本标签名称",uninstall:"mbler uninstall @<scope>/<name>@version\n从你的游戏中移除一个包",install:"mbler install @<scope>/<name>@version\n将一个包安装到你的游戏中",unpublish:"mbler unpublish @<scope>/<name>@version\n从 pmnx 取消发布一个包",login:"mbler login <?:token>\n使用 token 登录你的 pmnx 账户\n- 如果没有 token,会向你请求"},init:{useUI:"使用UI模块? (y/n): ",useGIT:"初始化GIT仓库? (y/n): ",name:"项目名称: ",welcome:"欢迎使用Mbler初始化向导 语言:中文 mbler 版本: "+w,description:"项目描述: ",initDes:"初始化依赖? (y/n): ",lang:"选择项目语言: ",betaApi:"使用Beta Api? (y/n): ",mcVersion:"项目使用的mc版本(x.x.x): ",noLanguare:"没有输入项目语言,这是必要的",noName:"没有项目名称,这是必要的",noMCVersion:"输入的 '支持的mc版本' 格式不对"},default:{unexpected:"不正确的命令,",youis:"你是否想说: "},workdir:{set:"[工作目录] 设置为: ",nfound:"找不到输入文件夹(无法创建或不是文件夹)",disabled:"工作目录功能已禁用,将使用当前目录",enabled:"工作目录功能已启用",invalidParam:"参数错误,请使用 on 或 off"}},v={description:"MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\nnodejs build tools on bedrock version of minecraft\nCommands: "+f.join(", ")+"\nHelp command:\n help\n Show help information\n The second parameter is the name of the command to be queried or empty\n Alias: -h, -help\n git https://github.com/RuanhoR/mbler/",help:{cmds:f,help:"mbler [help/h] [?: command name]\n - see tip",h:"$help",work:"mbler [work/c] [?: path]\n - No input path: see current work dir\n - input path: set as current dir",c:"$work",init:"mbler init\n - Init current work dir, you can use `mbler work` command or use command param(like be: mbler init -in ./)",build:"mbler build\n - perform a build using the library API",b:"$build",watch:"mbler watch\n - run build and enter watch mode; changes will trigger rebuilds",lang:'mbler lang [?:languare]\n- No args: show current languare\n- languare = "zh” | “en": set languare',version:"mbler version\n - Version control command\n- No args: Shows version + commit hash\n- --show=<commit|version>: Filters output\n- <new_version>: Updates version in both package.json and config file","set-work-dir":"mbler set-work-dir <on|off>\n - on: Enable work dir feature\n - off: Disable work dir feature, use process.cwd() directly",publish:"mbler publish\n - Publish your package to pmnx\n- Params:\n- -tag: version tag name",uninstall:"mbler uninstall @<scope>/<name>@version\nRemove a package from your game",install:"mbler install @<scope>/<name>@version\nInstall a package to your game",unpublish:"mbler unpublish @<scope>/<name>@version\nUnpublish a package from pmnx",login:"mbler login <?:token>\nUse token login your pmnx account"},init:{useUI:"Use UI? (y/n): ",useGIT:"Initialize GIT repository? (y/n): ",name:"Project name: ",description:"Project description: ",initDes:"Initialize dependencies? (y/n): ",welcome:"Welcome to use Mbler init wizard! Language: English mbler version: "+w,lang:"Project languare: ",betaApi:"use beta api(y/n): ",mcVersion:"Minecraft version(be like: x.x.x): ",noLanguare:"project languare is required",noMCVersion:"project mcVersion format is not right",noName:"project name is required"},default:{unexpected:"Not found this command,",youis:"You want to input: "},workdir:{set:"[path to]: ",nfound:"not found this dir(can't create or not directory)",disabled:"Work dir disabled, will use current directory",enabled:"Work dir enabled",invalidParam:"Invalid parameter, use on or off"}};const y=t.join(require("node:os").homedir(),".cache/mbler/lang.db");const k=new class{currenyLang="zh";init(){try{const t=n.readFileSync(y,"utf-8").toString().trim();if(e=t,!p.includes(e))throw new Error("[setup lang]: set lang error");this.currenyLang=t}catch{this.currenyLang="zh"}var e}set(e){return!!p.includes(e)&&(n.existsSync(y)||n.mkdirSync(t.dirname(y),{recursive:!0}),n.writeFileSync(y,e),this.currenyLang=e,!0)}get(){try{return"zh"==this.currenyLang?g:v}catch{return g}}};let j={};k.init(),function e(n){const t=n.get();Object.setPrototypeOf(j,{...t,__internal:{class:n,set:t=>{n.set(t),e(n)}}})}(k);var x=Object.freeze({__proto__:null,default:j});process.stdin.isTTY&&(process.stdin.setRawMode(!0),d.emitKeypressEvents(process.stdin));const _=[],D=[];process.on("exit",e=>{process.stdout.write("[?25h")});const P=[];function I(e,{ctrl:n=!1,alt:t=!1}){return new Promise(r=>{_.push({name:e,ctrl:n||!1,alt:t||!1,resolve:r})})}I("c",{ctrl:!0}).then(()=>{P.forEach(e=>e()),process.exit(0)});class O{static render(e,n){return e.map((e,t)=>t===n?""+e+"":""+e+"").join(" ")}static select(e,n){let t=0,r=!1;console.log(`${e} (按 b 确认,n 键选择下一个) [?25l`),console.log(O.render(n,t)+"\n");const i=()=>{r||(t++,t>=n.length&&(t=0),console.log(`${O.render(n,t)}\n`),I("n",{ctrl:!1,alt:!1}).then(i))};return new Promise(e=>{I("n",{ctrl:!1,alt:!1}).then(i),I("b",{ctrl:!1,alt:!1}).then(()=>{r=!0,process.stdout.write("[?25h"),e(n[t])})})}static use(e){D.push(e)}}process.stdin.on("keypress",(e,n)=>{!function(e,{ctrl:n,alt:t},r){const i=_.find(r=>r.name===e&&r.ctrl===n&&r.alt===t);i&&(i.resolve(),_.splice(_.indexOf(i),1)),D.forEach(i=>i(e,n,t,r))}(n?.name||"",{ctrl:Boolean(n?.ctrl),alt:Boolean(n?.alt)},e)});var $=Object.freeze({__proto__:null,Input:O,click:I,onEnd:function(e){P.push(e)}});const N={ConfigFile:"mbler.config.js"};async function E(e){try{if(await m.stat(e))return!0}catch{return!1}return!1}async function V(e){try{const n=await m.readFile(e,"utf-8");return JSON.parse(n)}catch(e){throw e instanceof Error?e:new Error(e)}}let A=[],L=!1;async function F(){if(!L&&0!==A.length){L=!0;try{for(;A.length>0;){const e=A.shift();e&&process.stdout.write(e)}}finally{L=!1}}}function S(e,n=!0){A.push(e+(n?"\n":"")),L||Promise.resolve().then(()=>F()).catch(()=>{A=[],L=!1})}async function U(e,n){const t=JSON.stringify(n,null,2);return await E(u.dirname(e))||await m.mkdir(u.dirname(e),{recursive:!0}).catch(()=>{}),await m.writeFile(e,t,"utf-8")}function M(e,n){const t=e.split(".").map(e=>parseInt(e,10)||0),r=n.split(".").map(e=>parseInt(e,10)||0);for(let e=0;e<3;e++){const n=t[e]||0,i=r[e]||0;if(n!==i)return n-i}return 0}process.on("exit",F);const q=function(){let e,n="",t="",r=!0;function i(){const e=`\r${t}${r?n:""}`;process.stdout.write(e)}return O.use(function(t,r,o,a){if("function"==typeof e&&!r&&!o){if(t){if("return"===t||"enter"===t)return e(n),e=null,n="",void console.log("");if("backspace"===t)return n=n.slice(0,-1),void i()}a&&"string"==typeof a&&(n+=a,i())}}),async function(n="",o=!0){return new Promise(a=>{r=o,t=n,i(),e=a})}}();function B(e){const n=e.split("-");return!!n[0]&&3===n[0].split(".").map(Number).filter(e=>!Number.isNaN(e)).length}function C(e,n,t){let r,i="";const o=new Promise(e=>r=e),a=s.spawn(e[0],e.slice(1),{cwd:n,shell:!1,stdio:t,timeout:6e5});return a.on("error",e=>{r(i+"(code: error)")}),a.on("data",(...e)=>{i+=e.join("")}),a.on("exit",e=>{r(e?i:`${i}(code: ${e})`)}),o}const R=t.join(i.homedir(),".cache/mbler/latest.log");function T(e){const n=async function(){try{const e=t.dirname(R);await E(e)||await r.mkdir(e,{recursive:!0}).catch(()=>{}),await E(R)||await r.writeFile(R,"")}catch(e){return void console.error("[logger] unable to prepare log file:",e)}try{await r.appendFile(R,"\n"+e)}catch(e){console.error("[logger] failed to append to log file:",e)}}();var i;z.run.push(n.then((i=n,()=>{z.run=z.run.filter(e=>e!==i)})))}class z{static LogFile=R;static run=[];static _b(e,n,t){const r=new Date;T([`${r.toLocaleDateString()} ${r.toLocaleTimeString()}`,`[${t} ${e}]`,n].join(" "))}static w(e,n){z._b(e,n,"WARN")}static e(e,n){z._b(e,n,"ERROR")}static i(e,n){z._b(e,n,"INFO")}static d(e,n){z._b(e,n,"DEBUG")}}async function W(e){try{return await r.mkdir(e),!0}catch{return!1}}class G{cacheDir;currentWorkPoint=null;enabledPath=t.join(i.homedir(),".cache/mbler/workdir_enabled.db");constructor(e=t.join(i.homedir(),".cache/mbler/mp.db")){this.cacheDir=e}async isDisabled(){try{return await r.readFile(this.enabledPath,"utf-8"),!1}catch{return!0}}async setDisabled(e){if(e)try{await r.unlink(this.enabledPath)}catch{}else await r.writeFile(this.enabledPath,"1",{encoding:"utf-8"})}async set(e){try{if(!(await r.stat(e)).isDirectory())throw new Error("Not Dir (0xcvb)")}catch(n){const t=n.code;if(n.message&&n.message.includes("0xcvb"))return j.workdir.nfound;if("ENOENT"==t){if(!W(e))return j.workdir.nfound}}try{if(!await E(t.dirname(this.cacheDir))){if(!await W(t.dirname(this.cacheDir)))return j.workdir.nfound}await r.writeFile(this.cacheDir,e,{encoding:"utf-8"})}catch(e){z.e("WorkDir",e.stack)}return j.workdir.set+e}async get(){if(await this.isDisabled())return e.cwd();if(this.currentWorkPoint)return this.currentWorkPoint;const n=await r.readFile(this.cacheDir,"utf-8").catch(n=>(this.set(e.cwd()),e.cwd()));return this.currentWorkPoint=n}}const J={tmpdir:u.join(i.tmpdir(),".mbler"),mcxVersion:"0.0.2-beta.r7",mcxCoreVersion:"0.0.6"},K=function(){const e=u.join(J.tmpdir,"_sapi_version.json");let n=null;async function t(e){const n=await a.json(`/${e}`),t=Object.keys(n.versions),r={},i=e=>{const n=e.match(/-(?:rc|beta)(?:\.[^-.]+)*?\.((?:\d+\.){2}\d+)/);return n?n[1]:null};for(const e of t){const n=i(e);if(!n)continue;const t=/(?:-stable)(?:$|[-.])/.test(e);let o=r[n];o||(o={formal:"",beta:"",_v:-1},r[n]=o),t?((!o.formal||e>o.formal)&&(o.formal=e),o._v=1/0):((!o.beta||e>o.beta)&&(o.beta=e),o._v!==1/0&&(o._v=1))}return r}async function r(){const r=await t("@minecraft/server"),i=await t("@minecraft/server-ui"),o=new Set([...Object.keys(r),...Object.keys(i)]),a=[];for(const e of Array.from(o))a.push({version:e,server:r[e]?{formal:r[e].formal,beta:r[e].beta}:{formal:"",beta:""},"server-ui":i[e]?{formal:i[e].formal,beta:i[e].beta}:{formal:"",beta:""}});a.sort((e,n)=>M(e.version,n.version)),n=a,await l.promises.mkdir(J.tmpdir,{recursive:!0}).catch(()=>{}),await l.promises.writeFile(e,JSON.stringify(a,null,2),"utf-8")}return{refresh:r,generateVersion:async function(t,i,o){if(!n)try{const t=await l.promises.readFile(e,"utf-8");n=JSON.parse(t)}catch{await r()}if(!n)throw new Error("unable to load sapi cache data");let a=n.find(e=>e.version===i);if(!a){const e=n.slice();let t=null;for(const n of e){if(!(M(n.version,i)<=0))break;t=n}t||(t=e[0]),a=t}const s=a["@minecraft/server"===t?"server":"server-ui"];let c=o?s.beta:s.formal;return c||(c=s.formal||s.beta),c||""}}}();async function Y(e,n){await K.refresh();const i=e.params.slice(1);if(await async function(e){return(await Promise.all([N.ConfigFile,"package.json","behavior"].map(n=>E(t.join(e,n))))).every(e=>e)}(n))return 0;S(j.init.welcome);const o={name:i[0]||await q(j.init.name),description:i[1]||await q(j.init.description),lang:i[2]||await O.select(j.init.lang,["ts","js","mcx"]),initDeependencies:await O.select(j.init.initDes,["no","pnpm","npm"]),useUI:"y"===await q(j.init.useUI),useGIT:"y"===await q(j.init.useGIT),useBetaApi:"y"===await q(j.init.betaApi),mcVersion:await q(j.init.mcVersion)};if(!o.name)return S(j.init.noName),1;if(!o.lang)return S(j.init.noLanguare),1;if(!o.mcVersion||!B(o.mcVersion))return S(j.init.noMCVersion),1;const a={name:o.name,description:o.description,version:"0.0.0",script:{lang:o.lang,main:"index.js",ui:o.useUI,UseBeta:o.useBetaApi},mcVersion:o.mcVersion,minify:!1},s={name:o.name,version:"0.0.0",description:o.description,module:"module",scripts:{build:"mcx-tsc && BUILD_MODULE=release mbler build","dev:build":"mbler build",install:"pnpm i -g mbler",watch:"mbler watch"},devDependencies:{"@minecraft/server":await K.generateVersion("@minecraft/server",o.mcVersion,o.useBetaApi)}};o.useUI&&(s.devDependencies["@minecraft/server-ui"]=await K.generateVersion("@minecraft/server-ui",o.mcVersion,o.useBetaApi));const c={compilerOptions:{module:"nodenext",noEmit:!0,target:"esnext",types:["@mbler/mcx-core/client"],sourceMap:!0,declaration:!0,declarationMap:!1,noUncheckedIndexedAccess:!0,exactOptionalPropertyTypes:!0,allowJs:!0,strict:!0,moduleResolution:"nodenext",verbatimModuleSyntax:!1,isolatedModules:!0,noUncheckedSideEffectImports:!0,moduleDetection:"force",skipLibCheck:!0},include:["./behavior/scripts/**/*"]},l=t.join(n,N.ConfigFile),u=t.join(n,"package.json"),m=t.join(n,"tsconfig.json");"mcx"==o.lang&&(a.script.main="index.mjs",s.devDependencies["@mbler/mcx"]=J.mcxVersion,s.devDependencies["@mbler/mcx-core"]=J.mcxCoreVersion),"js"!==o.lang&&await U(m,c),await U(u,s),await U(l,`import { defineConfig } from "mbler";\nexport default ${JSON.stringify(a,null,2)}`);const d=await async function(){return await E(t.join(__dirname,"../template"))?t.join(__dirname,"../template"):await E(t.join(__dirname,"./template"))?t.join(__dirname,"./template"):void 0}();if(!d)return S("can't find template folder"),1;const p=t.join(d,o.lang);if(!await E(p))return S("can't resolve template folder"),1;const f=[];for(const e of await r.readdir(p))f.push(r.cp(t.join(p,e),t.join(n,e),{recursive:!0,force:!0}));return await Promise.all(f),f.length=0,"no"!==o.initDeependencies&&f.push(C([o.initDeependencies,"install"],n,"pipe")),o.useGIT&&f.push(C(["git","init","-b","main"],n,"pipe")),await Promise.all(f),f.length=0,0}async function H(e,n){if(e.params.length>1){if(!await E(n))return S("can't set workdir version, because not exists"),1;const t=e.params[1];if(!t||!B(t))return S("can't set version, it is not a vaild version"),1;const r=await V(u.join(n,"package.json"));(await V(u.join(n,N.ConfigFile))).version=r.version=t}else!function(e){let n="";Object.getOwnPropertyNames(e.opts).length<1?n=`commit: ${b}\nversion: ${w}`:e.opts.show&&(n="commit"==e.opts.show?`commit: ${b}`:"version"==e.opts.show?`version: ${w}`:'invaild "show" param');S(n)}(e);return 0}function Q(e,n){let t="";return e.params.length<2||j.__internal.set(e.params[1]),t=j.__internal.class.currenyLang,S(t),0}function X(e,n){return S("unpublish is planing"),1}function Z(e,n){return S("publish is planing"),1}function ee(e,n){return S("uninstall is planing"),1}function ne(e,n){return S("install is planing"),1}function te(e,n){return S("login is planing"),1}const re=function(){let n;function r(e,n){if(!e||!n)return 1;const t=e.params[1];if(!t)return S(j.description),0;let r=j.help[t];return r?(r.startsWith("$")&&(r=j.help[r.slice(1)]),S(r),0):0}async function i(e,r){if(!n)return 0;if(e.params.length>1){const r=t.resolve(e.params[1]);S(await n.set(r))}else S(r);return 0}async function o(e,t){if(!n)return 0;const r=e.params[1];return"off"===r?(await n.setDisabled(!0),S(j.workdir.disabled)):"on"===r?(await n.setDisabled(!1),S(j.workdir.enabled)):S(j.workdir.invalidParam),0}return async function(){const a=function(){const n={},t=[];let r=null;return e.argv.slice(2).forEach((e,i,o)=>{if(r)return n[r]=e,void(r=null);e.startsWith("-")?(r=e.slice(1),i==o.length-1&&(n[r]="")):t.push(e)}),{params:t,opts:n}}(),s={help:r,h:r,work:i,c:i,build:async(e,n)=>{const{build:t}=require("mbler/build");return await t(e,n)},watch:async(e,n)=>{const{watch:t}=require("mbler/build");return await t(e,n)},init:Y,version:H,lang:Q,"set-work-dir":o,unpublish:X,publish:Z,uninstall:ee,install:ne,login:te},c=a.params[0];n=a.opts.cwp?new G(t.resolve(a.opts.cwp)):new G,c||(r(a,await n.get()),process.exit(0));const l=s[c];if("function"!=typeof l)!function(e){console.log(`${j.default.unexpected}: ${e}`);const n=f.map(n=>function(e,n){let t=0;for(let r=0;r<n.length;r++)e[r]==n[r]&&t++;return t/n.length}(e,n)).reduce((e,n,t)=>{try{if(n>e.max)return{max:n,index:t,indices:[]};if(n===e.max)return e.indices.push(t),e}catch(e){z.w("matchDefault",e.stack)}return e},{max:-1/0,index:-1,indices:[]}),t=f[n.index];t&&console.log(`${j.default.youis} ${t}`)}(c);else{const e=l(a,await n.get());if(e instanceof Promise){const n=await e;process.exit(n)}else process.exit(e)}process.exit(0)}}();exports.Types=h,exports.cli=re,exports.commander=$,exports.defineConfig=function(e){return e},exports.i18n=x;
1
+ 'use strict';
2
+
3
+ var node_process = require('node:process');
4
+ var fs = require('node:fs');
5
+ var path = require('node:path');
6
+ var fs$1 = require('node:fs/promises');
7
+ var os = require('node:os');
8
+ var readline = require('readline');
9
+ var npmRegistryFetch = require('npm-registry-fetch');
10
+ var node_child_process = require('node:child_process');
11
+
12
+ function _interopNamespaceDefault(e) {
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var fs__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(fs);
30
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
31
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1);
32
+ var readline__namespace = /*#__PURE__*/_interopNamespaceDefault(readline);
33
+
34
+ const LanguageNames = ['zh', 'en'];
35
+ const cmdList = ['c', 'work', 'help', 'h', 'init', 'version', 'build', 'watch', 'lang', 'set-work-dir', 'publish', 'unpublish', 'install', 'uninstall', 'login'];
36
+ const templateMblerConfig = {
37
+ name: 'demo',
38
+ description: 'demo',
39
+ version: '0.0.0',
40
+ mcVersion: '1.21.100',
41
+ script: {
42
+ main: '',
43
+ },
44
+ minify: false,
45
+ outdir: {
46
+ behavior: '',
47
+ resources: '',
48
+ dist: '',
49
+ },
50
+ };
51
+
52
+ var types = /*#__PURE__*/Object.freeze({
53
+ __proto__: null,
54
+ LanguageNames: LanguageNames,
55
+ cmdList: cmdList,
56
+ templateMblerConfig: templateMblerConfig
57
+ });
58
+
59
+ var MBLERVersion = { commit: `commit 81c6f8bb0b33367bd219c7c9168f18ae83e1f2e1
60
+ Author: Ruanhor <3915264929@qq.com>
61
+ Date: Sun Apr 19 16:33:01 2026 +0800
62
+
63
+ fix: init and add plan command
64
+ `, version: "0.2.2" };
65
+
66
+ var ZhLang = {
67
+ description: `MBLER
68
+ Minecraft Bedrock Edition
69
+ Addon Bulider In Nodejs
70
+ 在基岩版我的世界上的 nodejs 构建工具
71
+ 命令 : ${cmdList.join(", ")}
72
+ 帮助命令 :
73
+ help
74
+ 显示帮助信息
75
+ 第二个参数为要查询的命令名称或空
76
+ 别名: h
77
+ git https://github.com/RuanhoR/mbler/`,
78
+ help: {
79
+ cmds: cmdList,
80
+ help: "mbler [help/h] [?:查看的命令名称]\n - 查看帮助",
81
+ h: "$help",
82
+ work: "mbler [work/c] [?:相对或绝对路径]\n - 没有输入路径:查询当前工作目录\n - 输入路径:设置工作目录",
83
+ c: "$work",
84
+ init: "mbler init\n - 初始化当前工作目录,可使用 mbler work 指定工作目录或使用参数一次确定(例: mbler init -in ./)\n - 将会询问选项以完成初始化",
85
+ build: "mbler build\n - 在工作目录执行构建",
86
+ watch: "mbler watch\n - 启动构建并开启监视模式,文件变化会自动重新构建",
87
+ lang: 'mbler lang\n- 无参数:显示当前语言\n- 跟 zh 或 en(如 mbler lang en): 设置语言',
88
+ version: "mbler version - 版本管理命令\n- 无参数:显示当前版本和提交哈希\n- --show=<commit|version>:筛选显示内容\n- <新版本号>:更新package.json和配置文件的版本",
89
+ 'set-work-dir': "mbler set-work-dir <on|off>\n - on: 启用工作目录功能\n - off: 禁用工作目录功能,直接使用 process.cwd()",
90
+ publish: 'mbler publish\n - 将你的附加包发布到 pmnx\n- 参数:\n- -tag: 版本标签名称',
91
+ uninstall: 'mbler uninstall @<scope>/<name>@version\n从你的游戏中移除一个包',
92
+ install: 'mbler install @<scope>/<name>@version\n将一个包安装到你的游戏中',
93
+ unpublish: 'mbler unpublish @<scope>/<name>@version\n从 pmnx 取消发布一个包',
94
+ login: 'mbler login <?:token>\n使用 token 登录你的 pmnx 账户\n- 如果没有 token,会向你请求'
95
+ },
96
+ init: {
97
+ useUI: '使用UI模块? (y/n): ',
98
+ useGIT: '初始化GIT仓库? (y/n): ',
99
+ name: '项目名称: ',
100
+ welcome: '欢迎使用Mbler初始化向导 语言:中文 mbler 版本: ' + MBLERVersion.version,
101
+ description: "项目描述: ",
102
+ initDes: "初始化依赖? (y/n): ",
103
+ lang: "选择项目语言: ",
104
+ betaApi: "使用Beta Api? (y/n): ",
105
+ mcVersion: "项目使用的mc版本(x.x.x): ",
106
+ noLanguare: "没有输入项目语言,这是必要的",
107
+ noName: "没有项目名称,这是必要的",
108
+ noMCVersion: "输入的 '支持的mc版本' 格式不对"
109
+ },
110
+ default: {
111
+ unexpected: "不正确的命令,",
112
+ youis: "你是否想说: ",
113
+ },
114
+ workdir: {
115
+ set: "[工作目录] 设置为: ",
116
+ nfound: "找不到输入文件夹(无法创建或不是文件夹)",
117
+ disabled: "工作目录功能已禁用,将使用当前目录",
118
+ enabled: "工作目录功能已启用",
119
+ invalidParam: "参数错误,请使用 on 或 off",
120
+ },
121
+ };
122
+
123
+ var enLang = {
124
+ description: 'MBLER\nMinecraft Bedrock Edition\nAddon Bulider In Nodejs\nnodejs build tools on bedrock version of minecraft\nCommands: ' +
125
+ cmdList.join(', ') +
126
+ '\nHelp command:\n help\n Show help information\n The second parameter is the name of the command to be queried or empty\n Alias: -h, -help\n git https://github.com/RuanhoR/mbler/',
127
+ help: {
128
+ cmds: cmdList,
129
+ help: 'mbler [help/h] [?: command name]\n - see tip',
130
+ h: '$help',
131
+ work: 'mbler [work/c] [?: path]\n - No input path: see current work dir\n - input path: set as current dir',
132
+ c: '$work',
133
+ init: 'mbler init\n - Init current work dir, you can use `mbler work` command or use command param(like be: mbler init -in ./)',
134
+ build: 'mbler build\n - perform a build using the library API',
135
+ b: '$build',
136
+ watch: 'mbler watch\n - run build and enter watch mode; changes will trigger rebuilds',
137
+ lang: 'mbler lang [?:languare]\n- No args: show current languare\n- languare = "zh” | “en": set languare',
138
+ version: 'mbler version\n - Version control command\n- No args: Shows version + commit hash\n- --show=<commit|version>: Filters output\n- <new_version>: Updates version in both package.json and config file',
139
+ 'set-work-dir': "mbler set-work-dir <on|off>\n - on: Enable work dir feature\n - off: Disable work dir feature, use process.cwd() directly",
140
+ publish: 'mbler publish\n - Publish your package to pmnx\n- Params:\n- -tag: version tag name',
141
+ uninstall: 'mbler uninstall @<scope>/<name>@version\nRemove a package from your game',
142
+ install: 'mbler install @<scope>/<name>@version\nInstall a package to your game',
143
+ unpublish: 'mbler unpublish @<scope>/<name>@version\nUnpublish a package from pmnx',
144
+ login: 'mbler login <?:token>\nUse token login your pmnx account'
145
+ },
146
+ init: {
147
+ useUI: 'Use UI? (y/n): ',
148
+ useGIT: 'Initialize GIT repository? (y/n): ',
149
+ name: 'Project name: ',
150
+ description: "Project description: ",
151
+ initDes: "Initialize dependencies? (y/n): ",
152
+ welcome: 'Welcome to use Mbler init wizard! Language: English mbler version: ' + MBLERVersion.version,
153
+ lang: "Project languare: ",
154
+ betaApi: "use beta api(y/n): ",
155
+ mcVersion: 'Minecraft version(be like: x.x.x): ',
156
+ noLanguare: 'project languare is required',
157
+ noMCVersion: "project mcVersion format is not right",
158
+ noName: "project name is required"
159
+ },
160
+ default: {
161
+ unexpected: 'Not found this command,',
162
+ youis: 'You want to input: ',
163
+ },
164
+ workdir: {
165
+ set: '[path to]: ',
166
+ nfound: "not found this dir(can't create or not directory)",
167
+ disabled: "Work dir disabled, will use current directory",
168
+ enabled: "Work dir enabled",
169
+ invalidParam: "Invalid parameter, use on or off",
170
+ },
171
+ };
172
+
173
+ const configPath = path.join(require("node:os").homedir(), ".cache/mbler/lang.db");
174
+ function isLanguareName(language) {
175
+ return LanguageNames.includes(language);
176
+ }
177
+ class Lang {
178
+ currenyLang = "zh";
179
+ init() {
180
+ try {
181
+ const TheyLang = fs.readFileSync(configPath, "utf-8").toString().trim();
182
+ if (isLanguareName(TheyLang)) {
183
+ this.currenyLang = TheyLang;
184
+ }
185
+ else {
186
+ throw new Error("[setup lang]: set lang error");
187
+ }
188
+ }
189
+ catch {
190
+ this.currenyLang = "zh";
191
+ }
192
+ }
193
+ set(newLang) {
194
+ if (LanguageNames.includes(newLang)) {
195
+ if (!fs.existsSync(configPath)) {
196
+ fs.mkdirSync(path.dirname(configPath), {
197
+ recursive: true,
198
+ });
199
+ }
200
+ fs.writeFileSync(configPath, newLang);
201
+ this.currenyLang = newLang;
202
+ return true;
203
+ }
204
+ return false;
205
+ }
206
+ get() {
207
+ try {
208
+ if (this.currenyLang == "zh")
209
+ return ZhLang;
210
+ return enLang;
211
+ }
212
+ catch {
213
+ return ZhLang;
214
+ }
215
+ }
216
+ }
217
+ const lang = new Lang();
218
+ let i18n = {};
219
+ function Export(lang) {
220
+ const obj = lang.get();
221
+ // 用原型来让导入后切换语言不需要再次导入,相同引用
222
+ Object.setPrototypeOf(i18n, {
223
+ ...obj,
224
+ __internal: {
225
+ class: lang,
226
+ set: (newLang) => {
227
+ lang.set(newLang);
228
+ Export(lang);
229
+ },
230
+ },
231
+ });
232
+ }
233
+ lang.init();
234
+ Export(lang);
235
+
236
+ var index$1 = /*#__PURE__*/Object.freeze({
237
+ __proto__: null,
238
+ default: i18n
239
+ });
240
+
241
+ // 启用 raw mode 和键盘事件(仅在 TTY 环境中)
242
+ if (process.stdin.isTTY) {
243
+ process.stdin.setRawMode(true);
244
+ readline__namespace.emitKeypressEvents(process.stdin);
245
+ }
246
+ const promises = [];
247
+ const tasks = [];
248
+ process.on("exit", (code) => {
249
+ process.stdout.write("\x1b[?25h");
250
+ });
251
+ const endTasks = [];
252
+ function onEnd(task) {
253
+ endTasks.push(task);
254
+ }
255
+ click("c", {
256
+ ctrl: true,
257
+ }).then(() => {
258
+ endTasks.forEach((task) => task());
259
+ process.exit(0);
260
+ });
261
+ /**
262
+ * 监听键盘输入并触发对应的 Promise 或任务
263
+ */
264
+ function handler(name, { ctrl, alt, }, raw) {
265
+ // 查找是否有匹配的 Promise 等待触发
266
+ const find = promises.find((e) => e.name === name && e.ctrl === ctrl && e.alt === alt);
267
+ if (find) {
268
+ find.resolve();
269
+ promises.splice(promises.indexOf(find), 1);
270
+ }
271
+ // 通知所有注册的监听任务
272
+ tasks.forEach((item) => item(name, ctrl, alt, raw));
273
+ }
274
+ /**
275
+ * 模拟等待某个按键被按下,返回一个 Promise
276
+ */
277
+ function click(name, { ctrl = false, alt = false, }) {
278
+ return new Promise((resolve) => {
279
+ promises.push({
280
+ name,
281
+ ctrl: ctrl || false,
282
+ alt: alt || false,
283
+ resolve,
284
+ });
285
+ });
286
+ }
287
+ /**
288
+ * 工具类:提供控制台交互功能,比如高亮菜单渲染、交互式选择等
289
+ */
290
+ class Input {
291
+ /**
292
+ * 渲染一个字符串数组,高亮当前选中的项
293
+ * @param arr 菜单项数组
294
+ * @param index 当前选中索引
295
+ * @returns 格式化后的字符串
296
+ */
297
+ static render(arr, index) {
298
+ return arr
299
+ .map((item, pindex) => {
300
+ if (pindex === index)
301
+ return "\x1b[1m\x1b[32m" + item + "\x1b[0m"; // 亮绿,高亮
302
+ return "\x1b[1m\x1b[33m" + item + "\x1b[0m"; // 亮黄
303
+ })
304
+ .join(" ");
305
+ }
306
+ /**
307
+ * 提供一个交互式菜单选择器
308
+ * @param tip 提示文本
309
+ * @param arr 选项数组
310
+ * @returns 用户选中的选项内容(Promise<string>)
311
+ */
312
+ static select(tip, arr) {
313
+ let index = 0;
314
+ let win = false;
315
+ console.log(`\x1b[2K\x1b[47m\x1b[1m\x1b[30m${tip} (按 b 确认,n 键选择下一个) \x1b[0m\x1b[?25l`);
316
+ console.log(Input.render(arr, index) + "\n\x1b[1A");
317
+ const handlerNext = () => {
318
+ if (win)
319
+ return;
320
+ index++;
321
+ if (index >= arr.length)
322
+ index = 0;
323
+ console.log(`\x1b[1A${Input.render(arr, index)}\n\x1b[1A`);
324
+ click("n", {
325
+ ctrl: false,
326
+ alt: false,
327
+ }).then(handlerNext);
328
+ };
329
+ return new Promise((resolve) => {
330
+ // 监听 n 按键来切换选项
331
+ click("n", {
332
+ ctrl: false,
333
+ alt: false,
334
+ }).then(handlerNext);
335
+ // 监听 b 按键来确认选择
336
+ click("b", {
337
+ ctrl: false,
338
+ alt: false,
339
+ }).then(() => {
340
+ win = true;
341
+ process.stdout.write("\x1b[?25h");
342
+ resolve(arr[index]);
343
+ });
344
+ });
345
+ }
346
+ /**
347
+ * 注册一个全局任务,每次按键都会被调用
348
+ * @param task 回调函数
349
+ */
350
+ static use(task) {
351
+ tasks.push(task);
352
+ }
353
+ }
354
+ // 监听键盘输入事件
355
+ process.stdin.on("keypress", (str, key) => {
356
+ const rawKeyName = key?.name || "";
357
+ const ctrl = Boolean(key?.ctrl);
358
+ const alt = Boolean(key?.alt);
359
+ handler(rawKeyName, {
360
+ ctrl,
361
+ alt,
362
+ }, str);
363
+ });
364
+
365
+ var index = /*#__PURE__*/Object.freeze({
366
+ __proto__: null,
367
+ Input: Input,
368
+ click: click,
369
+ onEnd: onEnd
370
+ });
371
+
372
+ const BuildConfig = {
373
+ ConfigFile: "mbler.config.js"};
374
+
375
+ async function FileExsit(file) {
376
+ try {
377
+ const f = await fs__namespace.stat(file);
378
+ if (f)
379
+ return true;
380
+ }
381
+ catch {
382
+ return false;
383
+ }
384
+ return false;
385
+ }
386
+ async function readFileAsJson(filePath) {
387
+ try {
388
+ const content = await fs__namespace.readFile(filePath, 'utf-8');
389
+ const json = JSON.parse(content);
390
+ return json;
391
+ }
392
+ catch (err) {
393
+ if (err instanceof Error) {
394
+ throw err;
395
+ }
396
+ else {
397
+ throw new Error(err);
398
+ }
399
+ }
400
+ }
401
+ /**
402
+ * Print a single-line message to stdout with a trailing newline.
403
+ * Exported here so other modules (for example `build`) do not need
404
+ * to import from `cli`, avoiding a circular dependency.
405
+ */
406
+ // IO缓冲队列,避免多线程写入冲突
407
+ let outputQueue = [];
408
+ let isFlushing = false;
409
+ async function flushOutputQueue() {
410
+ if (isFlushing || outputQueue.length === 0)
411
+ return;
412
+ isFlushing = true;
413
+ try {
414
+ while (outputQueue.length > 0) {
415
+ const chunk = outputQueue.shift();
416
+ if (chunk) {
417
+ process.stdout.write(chunk);
418
+ }
419
+ }
420
+ }
421
+ finally {
422
+ isFlushing = false;
423
+ }
424
+ }
425
+ process.on("exit", flushOutputQueue);
426
+ function showText(text, needNextLine = true) {
427
+ outputQueue.push(text + (needNextLine ? '\n' : ""));
428
+ if (!isFlushing) {
429
+ Promise.resolve().then(() => flushOutputQueue()).catch(() => {
430
+ outputQueue = [];
431
+ isFlushing = false;
432
+ });
433
+ }
434
+ }
435
+ async function writeJSON(filePath, data) {
436
+ const content = JSON.stringify(data, null, 2);
437
+ if (!(await FileExsit(path__namespace.dirname(filePath)))) {
438
+ await fs__namespace
439
+ .mkdir(path__namespace.dirname(filePath), { recursive: true })
440
+ .catch(() => void 0);
441
+ }
442
+ return await fs__namespace.writeFile(filePath, content, 'utf-8');
443
+ }
444
+ function compareVersion(a, b) {
445
+ const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
446
+ const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
447
+ for (let i = 0; i < 3; i++) {
448
+ const na = pa[i] || 0;
449
+ const nb = pb[i] || 0;
450
+ if (na !== nb)
451
+ return na - nb;
452
+ }
453
+ return 0;
454
+ }
455
+ const input = (function () {
456
+ let curr;
457
+ let currstr = '';
458
+ let tip = '';
459
+ let show = true;
460
+ // 在输入时使用输入中间件
461
+ Input.use(function (raw, ctrl, alt, name) {
462
+ if (typeof curr !== 'function')
463
+ return;
464
+ if (ctrl || alt)
465
+ return;
466
+ if (raw) {
467
+ if (raw === 'return' || raw === 'enter') {
468
+ curr(currstr);
469
+ curr = null;
470
+ currstr = '';
471
+ console.log('');
472
+ return;
473
+ }
474
+ if (raw === 'backspace') {
475
+ currstr = currstr.slice(0, -1);
476
+ refreshInput();
477
+ return;
478
+ }
479
+ }
480
+ if (name && typeof name === 'string') {
481
+ currstr += name;
482
+ refreshInput();
483
+ }
484
+ });
485
+ function refreshInput() {
486
+ const out = `\x1b[2K\r${tip}${show ? currstr : ''}`;
487
+ process.stdout.write(out);
488
+ }
489
+ /**
490
+ * 输入文本
491
+ * @param{string} tip 提示
492
+ * @param{boolean} show 是否显示输入
493
+ */
494
+ return async function (t = '', g = true) {
495
+ return new Promise((resolve) => {
496
+ show = g;
497
+ tip = t;
498
+ refreshInput();
499
+ curr = resolve;
500
+ });
501
+ };
502
+ })();
503
+ function isVaildVersion(version) {
504
+ const split = version.split("-");
505
+ if (!split[0])
506
+ return false;
507
+ if (split[0].split(".").map(Number).filter(i => !Number.isNaN(i)).length !== 3)
508
+ return false;
509
+ return true;
510
+ }
511
+ function runCommand(param, cwd, stdio) {
512
+ let resolve;
513
+ let data = "";
514
+ const promise = new Promise((r) => resolve = r);
515
+ const p = node_child_process.spawn(param[0], param.slice(1), {
516
+ cwd: cwd,
517
+ shell: false,
518
+ stdio: stdio,
519
+ timeout: 1000 * 60 * 10
520
+ });
521
+ p.on("error", (err) => {
522
+ resolve(data + "(code: error)");
523
+ });
524
+ p.on("data", (...args) => {
525
+ data += args.join("");
526
+ });
527
+ p.on("exit", (code) => {
528
+ if (!code) {
529
+ resolve(`${data}(code: ${code})`);
530
+ }
531
+ else {
532
+ resolve(data);
533
+ }
534
+ });
535
+ return promise;
536
+ }
537
+
538
+ const logFile = path.join(os.homedir(), ".cache/mbler/latest.log");
539
+ function _clean(promise) {
540
+ return () => {
541
+ Logger.run = Logger.run.filter((item) => {
542
+ return item !== promise;
543
+ });
544
+ };
545
+ }
546
+ function writeLog(logContent) {
547
+ async function write() {
548
+ try {
549
+ const dir = path.dirname(logFile);
550
+ if (!(await FileExsit(dir))) {
551
+ // ensure the directory exists, root-to-leaf
552
+ await fs$1.mkdir(dir, { recursive: true }).catch(() => void 0);
553
+ }
554
+ // if file does not exist, create it (touch)
555
+ if (!(await FileExsit(logFile))) {
556
+ await fs$1.writeFile(logFile, "");
557
+ }
558
+ }
559
+ catch (err) {
560
+ // if we can't prepare the log file, output to stderr but don't crash
561
+ console.error("[logger] unable to prepare log file:", err);
562
+ return;
563
+ }
564
+ try {
565
+ await fs$1.appendFile(logFile, "\n" + logContent);
566
+ }
567
+ catch (err) {
568
+ console.error("[logger] failed to append to log file:", err);
569
+ }
570
+ }
571
+ const asy = write();
572
+ Logger.run.push(asy.then(_clean(asy)));
573
+ }
574
+ class Logger {
575
+ // 写入日志池
576
+ static LogFile = logFile;
577
+ static run = [];
578
+ static _b(tag, msg, t) {
579
+ const date = new Date();
580
+ const logContent = [
581
+ `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`,
582
+ `[${t} ${tag}]`,
583
+ msg,
584
+ ].join(" ");
585
+ writeLog(logContent);
586
+ }
587
+ static w(tag, msg) {
588
+ Logger._b(tag, msg, "WARN");
589
+ }
590
+ static e(tag, msg) {
591
+ Logger._b(tag, msg, "ERROR");
592
+ }
593
+ static i(tag, msg) {
594
+ Logger._b(tag, msg, "INFO");
595
+ }
596
+ static d(tag, msg) {
597
+ Logger._b(tag, msg, "DEBUG");
598
+ }
599
+ }
600
+
601
+ async function tryMkdir(point) {
602
+ try {
603
+ await fs$1.mkdir(point);
604
+ return true;
605
+ }
606
+ catch {
607
+ return false;
608
+ }
609
+ }
610
+ class WorkDirManage {
611
+ cacheDir;
612
+ currentWorkPoint = null;
613
+ enabledPath = path.join(os.homedir(), ".cache/mbler/workdir_enabled.db");
614
+ constructor(cacheDir = path.join(os.homedir(), ".cache/mbler/mp.db")) {
615
+ this.cacheDir = cacheDir;
616
+ }
617
+ async isDisabled() {
618
+ try {
619
+ await fs$1.readFile(this.enabledPath, "utf-8");
620
+ return false; // 文件存在,表示启用
621
+ }
622
+ catch {
623
+ return true; // 文件不存在,默认禁用
624
+ }
625
+ }
626
+ async setDisabled(disabled) {
627
+ if (!disabled) {
628
+ // 启用:创建文件
629
+ await fs$1.writeFile(this.enabledPath, "1", { encoding: "utf-8" });
630
+ }
631
+ else {
632
+ try {
633
+ await fs$1.unlink(this.enabledPath);
634
+ }
635
+ catch {
636
+ // 文件不存在,忽略
637
+ }
638
+ }
639
+ }
640
+ async set(newPointDir) {
641
+ // check
642
+ try {
643
+ const s = await fs$1.stat(newPointDir);
644
+ if (!s.isDirectory()) {
645
+ throw new Error("Not Dir (0xcvb)");
646
+ }
647
+ }
648
+ catch (err) {
649
+ const code = err.code;
650
+ if (err.message && err.message.includes("0xcvb"))
651
+ return i18n.workdir.nfound;
652
+ if (code == "ENOENT") {
653
+ const res = tryMkdir(newPointDir);
654
+ if (!res) {
655
+ return i18n.workdir.nfound;
656
+ }
657
+ }
658
+ }
659
+ try {
660
+ if (!(await FileExsit(path.dirname(this.cacheDir)))) {
661
+ const isC = await tryMkdir(path.dirname(this.cacheDir));
662
+ if (!isC)
663
+ return i18n.workdir.nfound;
664
+ }
665
+ await fs$1.writeFile(this.cacheDir, newPointDir, {
666
+ encoding: "utf-8",
667
+ });
668
+ }
669
+ catch (err) {
670
+ Logger.e("WorkDir", err.stack);
671
+ }
672
+ return i18n.workdir.set + newPointDir;
673
+ }
674
+ async get() {
675
+ if (await this.isDisabled()) {
676
+ return node_process.cwd();
677
+ }
678
+ if (this.currentWorkPoint) {
679
+ return this.currentWorkPoint;
680
+ }
681
+ const file = await fs$1.readFile(this.cacheDir, "utf-8").catch((e) => {
682
+ this.set(node_process.cwd());
683
+ return node_process.cwd();
684
+ });
685
+ return (this.currentWorkPoint = file);
686
+ }
687
+ }
688
+
689
+ const config = {
690
+ tmpdir: path__namespace.join(os.tmpdir(), ".mbler"),
691
+ mcxVersion: "0.0.2-beta.r7",
692
+ mcxCoreVersion: "0.0.6"
693
+ };
694
+
695
+ /**
696
+ * Compare two dotted version strings ("major.minor.patch").
697
+ * Returns negative if a < b, positive if a > b, zero if equal.
698
+ */
699
+ const exp = (function () {
700
+ const cacheFile = path__namespace.join(config.tmpdir, "_sapi_version.json");
701
+ // cacheData is an array of entries keyed by the embedded mc version string
702
+ let cacheData = null;
703
+ /**
704
+ * Pull every published version for a package and reduce it to a mapping
705
+ * from the embedded Minecraft version (e.g. "1.21.60") to the most
706
+ * recent formal/beta release we were able to parse.
707
+ */
708
+ async function fetchData(pkgName) {
709
+ const data = (await npmRegistryFetch.json(`/${pkgName}`));
710
+ const pkgVersions = Object.keys(data.versions);
711
+ const reValue = {};
712
+ // helper to extract the embedded MC version ("yyyy") from a full
713
+ // npm package version string. returns null when the expected pattern
714
+ // cannot be found.
715
+ const mcVersionFrom = (str) => {
716
+ const m = str.match(/-(?:rc|beta)(?:\.[^-.]+)*?\.((?:\d+\.){2}\d+)/);
717
+ return m ? m[1] : null;
718
+ };
719
+ for (const v of pkgVersions) {
720
+ const mcVersion = mcVersionFrom(v);
721
+ if (!mcVersion)
722
+ continue;
723
+ const isStable = /(?:-stable)(?:$|[-.])/.test(v);
724
+ let entry = reValue[mcVersion];
725
+ if (!entry) {
726
+ entry = { formal: "", beta: "", _v: -1 };
727
+ reValue[mcVersion] = entry;
728
+ }
729
+ if (isStable) {
730
+ // pick the lexically greatest stable version string
731
+ if (!entry.formal || v > entry.formal) {
732
+ entry.formal = v;
733
+ }
734
+ entry._v = Infinity;
735
+ }
736
+ else {
737
+ // non-stable release; treat everything else as a beta candidate
738
+ if (!entry.beta || v > entry.beta) {
739
+ entry.beta = v;
740
+ }
741
+ if (entry._v !== Infinity)
742
+ entry._v = 1;
743
+ }
744
+ }
745
+ return reValue;
746
+ }
747
+ async function refresh() {
748
+ // grab the two packages we care about and merge the keys
749
+ const serverMap = await fetchData("@minecraft/server");
750
+ const uiMap = await fetchData("@minecraft/server-ui");
751
+ const versions = new Set([
752
+ ...Object.keys(serverMap),
753
+ ...Object.keys(uiMap),
754
+ ]);
755
+ const arr = [];
756
+ for (const ver of Array.from(versions)) {
757
+ arr.push({
758
+ version: ver,
759
+ server: serverMap[ver]
760
+ ? { formal: serverMap[ver].formal, beta: serverMap[ver].beta }
761
+ : { formal: "", beta: "" },
762
+ "server-ui": uiMap[ver]
763
+ ? { formal: uiMap[ver].formal, beta: uiMap[ver].beta }
764
+ : { formal: "", beta: "" },
765
+ });
766
+ }
767
+ arr.sort((a, b) => compareVersion(a.version, b.version));
768
+ cacheData = arr;
769
+ await fs__namespace$1.promises
770
+ .mkdir(config.tmpdir, { recursive: true })
771
+ .catch(() => void 0);
772
+ await fs__namespace$1.promises.writeFile(cacheFile, JSON.stringify(arr, null, 2), "utf-8");
773
+ }
774
+ async function generateVersion(module, mcVersion, isBeta) {
775
+ if (!cacheData) {
776
+ try {
777
+ const txt = await fs__namespace$1.promises.readFile(cacheFile, "utf-8");
778
+ cacheData = JSON.parse(txt);
779
+ }
780
+ catch {
781
+ await refresh();
782
+ }
783
+ }
784
+ if (!cacheData) {
785
+ throw new Error("unable to load sapi cache data");
786
+ }
787
+ // try exact match first
788
+ let entry = cacheData.find((e) => e.version === mcVersion);
789
+ if (!entry) {
790
+ // find closest entry less than or equal to requested version
791
+ const sorted = cacheData.slice();
792
+ let candidate = null;
793
+ for (const e of sorted) {
794
+ if (compareVersion(e.version, mcVersion) <= 0) {
795
+ candidate = e;
796
+ }
797
+ else {
798
+ break;
799
+ }
800
+ }
801
+ if (!candidate) {
802
+ candidate = sorted[0];
803
+ }
804
+ entry = candidate;
805
+ }
806
+ const moduleKey = module === "@minecraft/server" ? "server" : "server-ui";
807
+ const entryModule = entry[moduleKey];
808
+ let result = isBeta ? entryModule.beta : entryModule.formal;
809
+ if (!result) {
810
+ // fall back to whatever is available
811
+ result = entryModule.formal || entryModule.beta;
812
+ }
813
+ return result || "";
814
+ }
815
+ return {
816
+ refresh,
817
+ generateVersion,
818
+ };
819
+ })();
820
+
821
+ async function isInit(dir) {
822
+ return (await Promise.all([BuildConfig.ConfigFile, 'package.json', 'behavior'].map((item) => {
823
+ return FileExsit(path.join(dir, item));
824
+ }))).every((value) => {
825
+ return value;
826
+ });
827
+ }
828
+ async function findTemplatedir() {
829
+ if (await FileExsit(path.join(__dirname, '../template')))
830
+ return path.join(__dirname, '../template');
831
+ if (await FileExsit(path.join(__dirname, './template')))
832
+ return path.join(__dirname, './template');
833
+ }
834
+ async function initCommand(cliParam, workdir) {
835
+ node_process.stdout.write(i18n.init.welcome + "\n");
836
+ await exp.refresh();
837
+ const cmdParams = cliParam.params.slice(1);
838
+ if (await isInit(workdir)) {
839
+ return 0;
840
+ }
841
+ const initOpts = {
842
+ name: cmdParams[0] || (await input(i18n.init.name)),
843
+ description: cmdParams[1] || (await input(i18n.init.description)),
844
+ lang: (cmdParams[2] ||
845
+ (await Input.select(i18n.init.lang, ['ts', 'js', 'mcx']))),
846
+ initDeependencies: await Input.select(i18n.init.initDes, [
847
+ 'no',
848
+ 'pnpm',
849
+ 'npm',
850
+ ]),
851
+ useUI: (await input(i18n.init.useUI)) === 'y',
852
+ useGIT: (await input(i18n.init.useGIT)) === 'y',
853
+ useBetaApi: (await input(i18n.init.betaApi)) === 'y',
854
+ mcVersion: await input(i18n.init.mcVersion),
855
+ };
856
+ if (!initOpts.name) {
857
+ showText(i18n.init.noName);
858
+ return 1;
859
+ }
860
+ if (!initOpts.lang) {
861
+ showText(i18n.init.noLanguare);
862
+ return 1;
863
+ }
864
+ if (!initOpts.mcVersion || !isVaildVersion(initOpts.mcVersion)) {
865
+ showText(i18n.init.noMCVersion);
866
+ return 1;
867
+ }
868
+ const mblerConfig = {
869
+ name: initOpts.name,
870
+ description: initOpts.description,
871
+ version: '0.0.0',
872
+ script: {
873
+ lang: initOpts.lang,
874
+ main: 'index.js',
875
+ ui: initOpts.useUI,
876
+ UseBeta: initOpts.useBetaApi,
877
+ },
878
+ mcVersion: initOpts.mcVersion,
879
+ minify: false,
880
+ };
881
+ const packageJSON = {
882
+ name: initOpts.name,
883
+ version: '0.0.0',
884
+ description: initOpts.description,
885
+ module: 'module',
886
+ scripts: {
887
+ build: 'mcx-tsc && BUILD_MODULE=release mbler build',
888
+ 'dev:build': 'mbler build',
889
+ install: 'pnpm i -g mbler',
890
+ watch: 'mbler watch',
891
+ },
892
+ devDependencies: {
893
+ '@minecraft/server': await exp.generateVersion('@minecraft/server', initOpts.mcVersion, initOpts.useBetaApi),
894
+ },
895
+ };
896
+ if (initOpts.useUI) {
897
+ packageJSON.devDependencies['@minecraft/server-ui'] =
898
+ await exp.generateVersion('@minecraft/server-ui', initOpts.mcVersion, initOpts.useBetaApi);
899
+ }
900
+ const tsconfig = {
901
+ compilerOptions: {
902
+ module: 'nodenext',
903
+ noEmit: true,
904
+ target: 'esnext',
905
+ types: ["@mbler/mcx-core/client"],
906
+ sourceMap: true,
907
+ declaration: true,
908
+ declarationMap: false,
909
+ noUncheckedIndexedAccess: true,
910
+ exactOptionalPropertyTypes: true,
911
+ allowJs: true,
912
+ strict: true,
913
+ moduleResolution: 'nodenext',
914
+ verbatimModuleSyntax: false,
915
+ isolatedModules: true,
916
+ noUncheckedSideEffectImports: true,
917
+ moduleDetection: 'force',
918
+ skipLibCheck: true,
919
+ },
920
+ include: ['./behavior/scripts/**/*'],
921
+ };
922
+ const mblerConfigPath = path.join(workdir, BuildConfig.ConfigFile);
923
+ const packageJSONPath = path.join(workdir, 'package.json');
924
+ const tsconfigPath = path.join(workdir, 'tsconfig.json');
925
+ if (initOpts.lang == 'mcx') {
926
+ mblerConfig.script.main = 'index.mjs';
927
+ packageJSON.devDependencies['@mbler/mcx'] = config.mcxVersion;
928
+ packageJSON.devDependencies['@mbler/mcx-core'] = config.mcxCoreVersion;
929
+ }
930
+ if (initOpts.lang !== 'js') {
931
+ await writeJSON(tsconfigPath, tsconfig);
932
+ }
933
+ await writeJSON(packageJSONPath, packageJSON);
934
+ const mblerConfigContent = `import { defineConfig } from "mbler";\nexport default ${JSON.stringify(mblerConfig, null, 2)}`;
935
+ await fs$1.writeFile(mblerConfigPath, mblerConfigContent);
936
+ // write template
937
+ const templatedir = await findTemplatedir();
938
+ if (!templatedir) {
939
+ showText("can't find template folder");
940
+ return 1;
941
+ }
942
+ const templateTagerFolder = path.join(templatedir, initOpts.lang);
943
+ if (!(await FileExsit(templateTagerFolder))) {
944
+ showText("can't resolve template folder");
945
+ return 1;
946
+ }
947
+ const tasks = [];
948
+ for (const item of await fs$1.readdir(templateTagerFolder)) {
949
+ tasks.push(fs$1.cp(path.join(templateTagerFolder, item), path.join(workdir, item), {
950
+ recursive: true,
951
+ force: true,
952
+ }));
953
+ }
954
+ await Promise.all(tasks);
955
+ tasks.length = 0;
956
+ if (initOpts.initDeependencies !== 'no') {
957
+ tasks.push(runCommand([initOpts.initDeependencies, 'install'], workdir, 'pipe'));
958
+ }
959
+ if (initOpts.useGIT) {
960
+ tasks.push(runCommand(['git', 'init', '-b', 'main'], workdir, 'pipe'));
961
+ }
962
+ await Promise.all(tasks);
963
+ tasks.length = 0;
964
+ return 0;
965
+ }
966
+
967
+ async function handlerVersion(cliParam, workdir) {
968
+ if (cliParam.params.length > 1) {
969
+ if (!await FileExsit(workdir)) {
970
+ showText("can't set workdir version, because not exists");
971
+ return 1;
972
+ }
973
+ const version = cliParam.params[1];
974
+ if (!version || !isVaildVersion(version)) {
975
+ showText("can't set version, it is not a vaild version");
976
+ return 1;
977
+ }
978
+ const pkgJSON = await readFileAsJson(path__namespace.join(workdir, "package.json"));
979
+ const mblerConfigJSON = await readFileAsJson(path__namespace.join(workdir, BuildConfig.ConfigFile));
980
+ mblerConfigJSON.version = pkgJSON.version = version;
981
+ }
982
+ else {
983
+ showVersion(cliParam);
984
+ }
985
+ return 0;
986
+ }
987
+ function showVersion(cliParam) {
988
+ let show = "";
989
+ if (Object.getOwnPropertyNames(cliParam.opts).length < 1) {
990
+ show = `commit: ${MBLERVersion.commit}\nversion: ${MBLERVersion.version}`;
991
+ }
992
+ else if (cliParam.opts.show) {
993
+ if (cliParam.opts.show == "commit") {
994
+ show = `commit: ${MBLERVersion.commit}`;
995
+ }
996
+ else if (cliParam.opts.show == "version") {
997
+ show = `version: ${MBLERVersion.version}`;
998
+ }
999
+ else {
1000
+ show = 'invaild "show" param';
1001
+ }
1002
+ }
1003
+ showText(show);
1004
+ }
1005
+
1006
+ function langCommand(cliParam, workdir) {
1007
+ let show = '';
1008
+ if (cliParam.params.length < 2) {
1009
+ show = i18n.__internal.class.currenyLang;
1010
+ }
1011
+ else {
1012
+ i18n.__internal.set(cliParam.params[1]);
1013
+ show = i18n.__internal.class.currenyLang;
1014
+ }
1015
+ showText(show);
1016
+ return 0;
1017
+ }
1018
+
1019
+ function unpublishCommand(cliParam, work) {
1020
+ showText("unpublish is planing");
1021
+ return 1;
1022
+ }
1023
+
1024
+ function publishCommand(cliParam, work) {
1025
+ showText("publish is planing");
1026
+ return 1;
1027
+ }
1028
+
1029
+ function uninstallCommand(cliParam, work) {
1030
+ showText("uninstall is planing");
1031
+ return 1;
1032
+ }
1033
+
1034
+ function installCommand(cliParam, work) {
1035
+ showText("install is planing");
1036
+ return 1;
1037
+ }
1038
+
1039
+ function loginCommand(cliParam, work) {
1040
+ showText("login is planing");
1041
+ return 1;
1042
+ }
1043
+
1044
+ // `showText` moved to `utils` to avoid circular dependency with `build`.
1045
+ const main = (function () {
1046
+ let currentWDManage;
1047
+ function parseParam() {
1048
+ const opts = {};
1049
+ const params = [];
1050
+ let InValue = null;
1051
+ node_process.argv.slice(2).forEach((item, index, arr) => {
1052
+ if (InValue) {
1053
+ opts[InValue] = item;
1054
+ InValue = null;
1055
+ return;
1056
+ }
1057
+ if (item.startsWith('-')) {
1058
+ InValue = item.slice(1);
1059
+ if (index == arr.length - 1)
1060
+ opts[InValue] = '';
1061
+ }
1062
+ else {
1063
+ params.push(item);
1064
+ }
1065
+ });
1066
+ return {
1067
+ params,
1068
+ opts,
1069
+ };
1070
+ }
1071
+ function handlerHelp(cliParam, _) {
1072
+ if (!cliParam || !_)
1073
+ return 1;
1074
+ const seeCmd = cliParam.params[1];
1075
+ if (!seeCmd) {
1076
+ showText(i18n.description);
1077
+ return 0;
1078
+ }
1079
+ let text = i18n.help[seeCmd];
1080
+ if (!text)
1081
+ return 0;
1082
+ if (text.startsWith('$')) {
1083
+ text = i18n.help[text.slice(1)];
1084
+ }
1085
+ showText(text);
1086
+ return 0;
1087
+ }
1088
+ function getMatchChance(a, b) {
1089
+ let match = 0;
1090
+ // b = 比较值,a = 待比较值
1091
+ for (let i = 0; i < b.length; i++) {
1092
+ if (a[i] == b[i])
1093
+ match++;
1094
+ }
1095
+ return match / b.length;
1096
+ }
1097
+ async function handlerWorkDirCommand(cliParam, workDir) {
1098
+ if (!currentWDManage)
1099
+ return 0;
1100
+ if (cliParam.params.length > 1) {
1101
+ const newPointWorkDir = path.resolve(cliParam.params[1]);
1102
+ showText(await currentWDManage.set(newPointWorkDir));
1103
+ }
1104
+ else {
1105
+ showText(workDir);
1106
+ }
1107
+ return 0;
1108
+ }
1109
+ async function handlerSetWorkDirCommand(cliParam, _) {
1110
+ if (!currentWDManage)
1111
+ return 0;
1112
+ const param = cliParam.params[1];
1113
+ if (param === 'off') {
1114
+ await currentWDManage.setDisabled(true);
1115
+ showText(i18n.workdir.disabled);
1116
+ }
1117
+ else if (param === 'on') {
1118
+ await currentWDManage.setDisabled(false);
1119
+ showText(i18n.workdir.enabled);
1120
+ }
1121
+ else {
1122
+ showText(i18n.workdir.invalidParam);
1123
+ }
1124
+ return 0;
1125
+ }
1126
+ function defaultCommand(commandcc) {
1127
+ console.log(`\x1b[31m${i18n.default.unexpected}: ${commandcc}\x1b[0m`);
1128
+ const didvalue = cmdList
1129
+ .map((item) => getMatchChance(commandcc, item))
1130
+ .reduce((acc, cur, index) => {
1131
+ try {
1132
+ if (cur > acc.max) {
1133
+ return {
1134
+ max: cur,
1135
+ index: index,
1136
+ indices: [],
1137
+ }; // 更新最大值及索引
1138
+ }
1139
+ else if (cur === acc.max) {
1140
+ acc.indices.push(index); // 记录重复最大值的索引
1141
+ return acc;
1142
+ }
1143
+ }
1144
+ catch (err) {
1145
+ Logger.w('matchDefault', err.stack);
1146
+ }
1147
+ return acc;
1148
+ }, {
1149
+ max: -Infinity,
1150
+ index: -1,
1151
+ indices: [],
1152
+ });
1153
+ const value = cmdList[didvalue.index];
1154
+ if (value)
1155
+ console.log(`${i18n.default.youis} ${value}`);
1156
+ }
1157
+ return async function cli() {
1158
+ const cliParam = parseParam();
1159
+ const handlerBuild = async (cliParam, workDir) => {
1160
+ const { build } = require("mbler/build");
1161
+ return await build(cliParam, workDir);
1162
+ };
1163
+ const handlerWatch = async (cliParam, workDir) => {
1164
+ const { watch } = require("mbler/build");
1165
+ return await watch(cliParam, workDir);
1166
+ };
1167
+ const cmdMap = {
1168
+ help: handlerHelp,
1169
+ h: handlerHelp,
1170
+ work: handlerWorkDirCommand,
1171
+ c: handlerWorkDirCommand,
1172
+ build: handlerBuild,
1173
+ watch: handlerWatch,
1174
+ init: initCommand,
1175
+ version: handlerVersion,
1176
+ lang: langCommand,
1177
+ 'set-work-dir': handlerSetWorkDirCommand,
1178
+ unpublish: unpublishCommand,
1179
+ publish: publishCommand,
1180
+ uninstall: uninstallCommand,
1181
+ install: installCommand,
1182
+ login: loginCommand
1183
+ };
1184
+ const cmd = cliParam.params[0];
1185
+ if (cliParam.opts.cwp) {
1186
+ currentWDManage = new WorkDirManage(path.resolve(cliParam.opts.cwp));
1187
+ }
1188
+ else {
1189
+ currentWDManage = new WorkDirManage();
1190
+ }
1191
+ if (!cmd) {
1192
+ handlerHelp(cliParam, await currentWDManage.get());
1193
+ process.exit(0);
1194
+ }
1195
+ const handler = cmdMap[cmd];
1196
+ if (typeof handler !== 'function') {
1197
+ defaultCommand(cmd);
1198
+ }
1199
+ else {
1200
+ const r = handler(cliParam, await currentWDManage.get());
1201
+ if (r instanceof Promise) {
1202
+ const code = await r;
1203
+ process.exit(code);
1204
+ }
1205
+ else {
1206
+ process.exit(r);
1207
+ }
1208
+ }
1209
+ process.exit(0);
1210
+ };
1211
+ })();
1212
+
1213
+ /**
1214
+ * Define Mbler config with type
1215
+ * @param {MblerConfigData} config - config
1216
+ * @returns config
1217
+ */
1218
+ function defineConfig(config) {
1219
+ return config;
1220
+ }
1221
+
1222
+ exports.Types = types;
1223
+ exports.cli = main;
1224
+ exports.commander = index;
1225
+ exports.defineConfig = defineConfig;
1226
+ exports.i18n = index$1;
2
1227
  //# sourceMappingURL=index.js.map