@bepack/cli 0.1.0-beta.6 → 0.1.0-beta.7
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/README.md +89 -224
- package/README.zh-CN.md +95 -223
- package/dist/cli.js +11 -11
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{constants as e,lstatSync as t,promises as n,readFileSync as r,statSync as i}from"node:fs";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import s,{dirname as c,join as l}from"node:path";import{randomUUID as u}from"node:crypto";import d,{platform as f}from"node:os";import{replacePlugin as p}from"rolldown/plugins";import{spawn as m}from"node:child_process";import h,{access as g,mkdir as _,readFile as v}from"node:fs/promises";import{rolldown as y}from"rolldown";import{loadConfig as b}from"rolldown/config";import{createRequire as x}from"module";import S from"chokidar";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,te=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},
|
|
2
|
+
import{constants as e,lstatSync as t,promises as n,readFileSync as r,statSync as i}from"node:fs";import{fileURLToPath as a,pathToFileURL as o}from"node:url";import s,{dirname as c,join as l}from"node:path";import{randomUUID as u}from"node:crypto";import d,{platform as f}from"node:os";import{replacePlugin as p}from"rolldown/plugins";import{spawn as m}from"node:child_process";import h,{access as g,mkdir as _,readFile as v}from"node:fs/promises";import{rolldown as y}from"rolldown";import{loadConfig as b}from"rolldown/config";import{createRequire as x}from"module";import S from"chokidar";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,ee=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,te=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},O=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),k=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},A=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!D.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},j=(e,t,n)=>(n=e==null?{}:C(ee(e)),A(t||!e||!e.__esModule||!D.call(e,`default`)?w(n,`default`,{value:e,enumerable:!0}):n,e));function M(e){return e==null?[]:Array.isArray(e)?e:[e]}function ne(e,t,n,r){var i,a=e[t],o=~r.string.indexOf(t)?n==null||n===!0?``:String(n):typeof n==`boolean`?n:~r.boolean.indexOf(t)?n===`false`?!1:n===`true`||(e._.push((i=+n,i*0==0?i:n)),!!n):(i=+n,i*0==0?i:n);e[t]=a==null?o:Array.isArray(a)?a.concat(o):[a,o]}function re(e,t){e||=[],t||={};var n,r,i,a,o,s={_:[]},c=0,l=0,u=0,d=e.length;let f=t.alias!==void 0,p=t.unknown!==void 0,m=t.default!==void 0;if(t.alias=t.alias||{},t.string=M(t.string),t.boolean=M(t.boolean),f)for(n in t.alias)for(r=t.alias[n]=M(t.alias[n]),c=0;c<r.length;c++)(t.alias[r[c]]=r.concat(n)).splice(c,1);for(c=t.boolean.length;c-->0;)for(r=t.alias[t.boolean[c]]||[],l=r.length;l-->0;)t.boolean.push(r[l]);for(c=t.string.length;c-->0;)for(r=t.alias[t.string[c]]||[],l=r.length;l-->0;)t.string.push(r[l]);if(m){for(n in t.default)if(a=typeof t.default[n],r=t.alias[n]=t.alias[n]||[],t[a]!==void 0)for(t[a].push(n),c=0;c<r.length;c++)t[a].push(r[c])}let h=p?Object.keys(t.alias):[];for(c=0;c<d;c++){if(i=e[c],i===`--`){s._=s._.concat(e.slice(++c));break}for(l=0;l<i.length&&i.charCodeAt(l)===45;l++);if(l===0)s._.push(i);else if(i.substring(l,l+3)===`no-`){if(a=i.substring(l+3),p&&!~h.indexOf(a))return t.unknown(i);s[a]=!1}else{for(u=l+1;u<i.length&&i.charCodeAt(u)!==61;u++);for(a=i.substring(l,u),o=i.substring(++u)||c+1===d||(``+e[c+1]).charCodeAt(0)===45||e[++c],r=l===2?[a]:a,u=0;u<r.length;u++){if(a=r[u],p&&!~h.indexOf(a))return t.unknown(`-`.repeat(l)+a);ne(s,a,u+1<r.length||o,t)}}}if(m)for(n in t.default)s[n]===void 0&&(s[n]=t.default[n]);if(f)for(n in s)for(r=t.alias[n]||[];r.length>0;)s[r.shift()]=s[n];return s}function N(e){return e.replace(/[<[].+/,``).trim()}function ie(e){let t=/<([^>]+)>/g,n=/\[([^\]]+)\]/g,r=[],i=e=>{let t=!1,n=e[1];return n.startsWith(`...`)&&(n=n.slice(3),t=!0),{required:e[0].startsWith(`<`),value:n,variadic:t}},a;for(;a=t.exec(e);)r.push(i(a));let o;for(;o=n.exec(e);)r.push(i(o));return r}function ae(e){let t={alias:{},boolean:[]};for(let[n,r]of e.entries())r.names.length>1&&(t.alias[r.names[0]]=r.names.slice(1)),r.isBoolean&&(r.negated&&e.some((e,t)=>t!==n&&e.names.some(e=>r.names.includes(e))&&typeof e.required==`boolean`)||t.boolean.push(r.names[0]));return t}function P(e){return e.sort((e,t)=>e.length>t.length?-1:1)[0]}function F(e,t){return e.length>=t?e:`${e}${` `.repeat(t-e.length)}`}function oe(e){return e.replaceAll(/([a-z])-([a-z])/g,(e,t,n)=>t+n.toUpperCase())}function se(e,t,n){let r=e;for(let e=0;e<t.length;e++){let i=t[e];if(e===t.length-1){r[i]=n;return}if(r[i]==null){let n=+t[e+1]>-1;r[i]=n?[]:{}}r=r[i]}}function ce(e,t){for(let n of Object.keys(t)){let r=t[n];r.shouldTransform&&(e[n]=[e[n]].flat(),typeof r.transformFunction==`function`&&(e[n]=e[n].map(r.transformFunction)))}}function le(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:``}function ue(e){return e.split(`.`).map((e,t)=>t===0?oe(e):e).join(`.`)}var de=class extends Error{constructor(e){super(e),this.name=`CACError`,typeof Error.captureStackTrace!=`function`&&(this.stack=Error(e).stack)}},fe=class{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,n){this.rawName=e,this.description=t,this.config=Object.assign({},n),e=e.replaceAll(`.*`,``),this.negated=!1,this.names=N(e).split(`,`).map(e=>{let t=e.trim().replace(/^-{1,2}/,``);return t.startsWith(`no-`)&&(this.negated=!0,t=t.replace(/^no-/,``)),ue(t)}).sort((e,t)=>e.length>t.length?1:-1),this.name=this.names.at(-1),this.negated&&this.config.default==null&&(this.config.default=!0),e.includes(`<`)?this.required=!0:e.includes(`[`)?this.required=!1:this.isBoolean=!0}};let pe,me;if(typeof process<`u`){let e;e=typeof Deno<`u`&&typeof Deno.version?.deno==`string`?`deno`:typeof Bun<`u`&&typeof Bun.version==`string`?`bun`:`node`,me=`${process.platform}-${process.arch} ${e}-${process.version}`,pe=process.argv}else me=typeof navigator>`u`?`unknown`:`${navigator.platform} ${navigator.userAgent}`;var he=class{rawName;description;config;cli;options;aliasNames;name;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;constructor(e,t,n={},r){this.rawName=e,this.description=t,this.config=n,this.cli=r,this.options=[],this.aliasNames=[],this.name=N(e),this.args=ie(e),this.examples=[]}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t=`-v, --version`){return this.versionNumber=e,this.option(t,`Display version number`),this}example(e){return this.examples.push(e),this}option(e,t,n){let r=new fe(e,t,n);return this.options.push(r),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}isMatched(e){return this.name===e||this.aliasNames.includes(e)}get isDefaultCommand(){return this.name===``||this.aliasNames.includes(`!`)}get isGlobalCommand(){return this instanceof ge}hasOption(e){return e=e.split(`.`)[0],this.options.find(t=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:n,options:r,helpCallback:i}=this.cli.globalCommand,a=[{body:`${e}${n?`/${n}`:``}`}];if(a.push({title:`Usage`,body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let n=P(t.map(e=>e.rawName));a.push({title:`Commands`,body:t.map(e=>` ${F(e.rawName,n.length)} ${e.description}`).join(`
|
|
3
3
|
`)},{title:"For more info, run any command with the `--help` flag",body:t.map(t=>` $ ${e}${t.name===``?``:` ${t.name}`} --help`).join(`
|
|
4
|
-
`)})}let o=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(o=o.filter(e=>e.name!==`version`)),o.length>0){let e=
|
|
4
|
+
`)})}let o=this.isGlobalCommand?r:[...this.options,...r||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand&&(o=o.filter(e=>e.name!==`version`)),o.length>0){let e=P(o.map(e=>e.rawName));a.push({title:`Options`,body:o.map(t=>` ${F(t.rawName,e.length)} ${t.description} ${t.config.default===void 0?``:`(default: ${t.config.default})`}`).join(`
|
|
5
5
|
`)})}this.examples.length>0&&a.push({title:`Examples`,body:this.examples.map(t=>typeof t==`function`?t(e):t).join(`
|
|
6
6
|
`)}),i&&(a=i(a)||a),console.info(a.map(e=>e.title?`${e.title}:\n${e.body}`:e.body).join(`
|
|
7
7
|
|
|
8
|
-
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;t&&console.info(`${e}/${t} ${ge}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new pe(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!==`--`&&!this.hasOption(n)&&!t.hasOption(n))throw new pe(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let t of n){let r=e[t.name.split(`.`)[0]];if(t.required){let e=n.some(e=>e.negated&&e.names.includes(t.name));if(r===!0||r===!1&&!e)throw new pe(`option \`${t.rawName}\` value is missing`)}}}checkUnusedArgs(){let e=this.args.some(e=>e.variadic)?1/0:this.args.length;if(e<this.cli.args.length)throw new pe(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},ve=class extends _e{constructor(e){super(`@@global@@`,``,{},e)}},ye=class extends EventTarget{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor(e=``){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ve(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new _e(e,t||``,n,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,n){return this.globalCommand.option(e,t,n),this}help(e){return this.globalCommand.option(`-h, --help`,`Display this message`),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t=`-v, --version`){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},n,r){return this.args=e,this.options=t,n&&(this.matchedCommand=n),r&&(this.matchedCommandName=r),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e,{run:t=!0}={}){if(!e){if(!he)throw Error(`No argv provided and runtime process argv is not available.`);e=he}this.rawArgs=e,this.name||=e[1]?de(e[1]):`cli`;let n=!0;for(let t of this.commands){let r=this.mri(e.slice(2),t),i=r.args[0];if(t.isMatched(i)){n=!1;let e={...r,args:r.args.slice(1)};this.setParsedInfo(e,t,i),this.dispatchEvent(new CustomEvent(`command:${i}`,{detail:t}))}}if(n){for(let t of this.commands)if(t.isDefaultCommand){n=!1;let r=this.mri(e.slice(2),t);this.setParsedInfo(r,t),this.dispatchEvent(new CustomEvent(`command:!`,{detail:t}))}}if(n){let t=this.mri(e.slice(2));this.setParsedInfo(t)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),t=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),t=!1,this.unsetMatchedCommand());let r={args:this.args,options:this.options};return t&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.dispatchEvent(new CustomEvent(`command:*`,{detail:this.args[0]})),r}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],r=oe(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=ie(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[fe(t)]:o[t]}),{_:[]});let s=o._,c={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,u=Object.create(null);for(let e of n){if(!l&&e.config.default!==void 0)for(let t of e.names)c[t]=e.config.default;Array.isArray(e.config.type)&&u[e.name]===void 0&&(u[e.name]=Object.create(null),u[e.name].shouldTransform=!0,u[e.name].transformFunction=e.config.type[0])}for(let e of Object.keys(o))e!==`_`&&(le(c,e.split(`.`),o[e]),ue(c,u));return{args:s,options:c}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs(),n.checkUnusedArgs();let r=[];return n.args.forEach((t,n)=>{t.variadic?r.push(e.slice(n)):r.push(e[n])}),r.push(t),n.commandAction.apply(this,r)}};const be=(e=``)=>new ye(e);function xe(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function Se(e){return`${JSON.stringify(e,null,4)}\n`}async function P(e){try{return await n.access(e),!0}catch{return!1}}async function Ce(e){await n.mkdir(e,{recursive:!0})}async function we(e){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0})}async function Te(e){return xe(await n.readFile(e,`utf8`),e)}async function Ee(e,t){await Ce(s.dirname(e)),await n.writeFile(e,Se(t),`utf8`)}async function De(e,t){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(s.dirname(t),{recursive:!0}),await n.cp(e,t,{recursive:!0})}var F=class extends Error{code;details;suggestions;constructor(e,t,n={}){super(t),this.name=`BePackError`,this.code=e,this.details=n.details,this.suggestions=n.suggestions}},Oe=/* @__PURE__ */ A((/* @__PURE__ */ O(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})))(),1);const I=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var L=class{options;constructor(e={}){this.options=e}formatDuration(e){return I.green(`${(e/1e3).toFixed(2)}s`)}info(e){this.options.silent||console.log(e)}warn(e){this.options.silent||console.warn(I.yellow(e))}error(e){this.options.silent||console.error(I.red(e))}verbose(e){!this.options.silent&&this.options.verbose&&console.log(I.gray(e))}clear(){this.options.silent||console.clear()}step(e,t,n=`cyan`){this.info(`${I[n](e.padEnd(10))} ${t}`)}progress(e,t){this.step(e,t,`blue`)}success(e,t){this.step(e,t,`green`)}bepack(e,t){this.info(`${I.green(`bepack`)} ${I.bold(e)} ${I.gray(t)}`)}manifest(e){this.step(`manifest`,e,`yellow`)}typescript(e){this.step(`TS`,e,`blue`)}rolldown(e){this.step(`rolldown`,e,`magenta`)}install(e){this.step(`install`,e,`blue`)}copy(e){this.step(`copy`,e,`cyan`)}pack(e){this.step(`pack`,e,`magenta`)}hook(e,t){this.step(`hook`,`${e}: ${t}`,`gray`)}timing(e,t){this.step(`timing`,`${e.padEnd(14)} ${t} ms`,`gray`)}done(e,t){this.info(`${I.green(`√`)} ${I.green(e)} ${t}`)}};function ke(e){return Array.isArray(e)&&e.length===3&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`}function Ae(e){return typeof e==`string`&&/^\d+\.\d+\.\d+$/.test(e)}function je(e){return e===3?Ae:ke}function Me(e,t){return e===3?`${t} must be SemVer string like "x.y.z" (format 3)`:`${t} must be [number, number, number] (format 2)`}const Ne=[e=>e.format_version===void 0?`format_version is required`:null,e=>e.header?null:`header is required`,e=>e.header&&!e.header.name?`header.name is required`:null,e=>e.header&&!e.header.uuid?`header.uuid is required`:null,e=>e.header?je(e.format_version)(e.header.version)?null:Me(e.format_version,`header.version`):null,e=>e.header?je(e.format_version)(e.header.min_engine_version)?null:Me(e.format_version,`header.min_engine_version`):null,e=>e.modules!==void 0&&!Array.isArray(e.modules)?`modules must be an array`:null,(e,t)=>{if(!Array.isArray(e.modules))return null;let n=e.modules.some(e=>e?.type===`resources`),r=[];return t===`rp`&&!n&&r.push(`RP manifest must have a resources module`),r.length>0?r:null},e=>{if(!Array.isArray(e.modules))return null;let t=je(e.format_version),n=[];for(let r=0;r<e.modules.length;r++){let i=e.modules[r];i&&i.version!==void 0&&i.version!==null&&!t(i.version)&&n.push(`modules[${r}] (uuid: ${i.uuid??`unknown`}): ${Me(e.format_version,`version`)}`)}return n.length>0?n:null},e=>e.dependencies!==void 0&&!Array.isArray(e.dependencies)?`dependencies must be an array`:null,e=>{if(!Array.isArray(e.dependencies))return null;let t=je(e.format_version),n=[];for(let r=0;r<e.dependencies.length;r++){let i=e.dependencies[r];if(!i){n.push(`dependencies[${r}] is invalid`);continue}`uuid`in i&&i.uuid&&!t(i.version)&&n.push(`dependencies[${r}] (uuid: ${i.uuid}): ${Me(e.format_version,`version`)}`),`module_name`in i&&i.module_name&&typeof i.version!=`string`&&n.push(`dependencies[${r}] (module_name: ${i.module_name}): version must be a string`)}return n.length>0?n:null},e=>e.capabilities===void 0?null:Array.isArray(e.capabilities)?e.capabilities.every(e=>typeof e==`string`)?null:`capabilities must be an array of strings`:`capabilities must be an array`,e=>e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)?`metadata must be an object`:null];function Pe(e,t){let n=[];for(let r of Ne){let i=r(e,t);i!==null&&(Array.isArray(i)?n.push(...i):n.push(i))}if(n.length>0)throw new F(`MANIFEST_INVALID`,`Manifest validation failed: ${n.join(`; `)}`)}function Fe(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Ie(e){return Array.isArray(e)?e:[]}function Le(e){if(!(e&&Object.keys(e).length===0))return e}var Re=class{static async read(e){if(!await P(e))return;let t=await n.readFile(e,`utf8`);try{return Fe(JSON.parse(t))}catch{throw new F(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){Pe(t,n),await Ee(e,t)}};function ze(e){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)throw new F(`VERSION_INVALID`,`Manifest version requires x.y.z.`,{details:{version:e}});return[Number(t[1]),Number(t[2]),Number(t[3])]}function Be(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function R(e,t){let n=e.split(/[^0-9A-Za-z]+/),r=t.split(/[^0-9A-Za-z]+/),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??``,i=r[e]??``,a=/^\d+$/.test(t)?Number(t):NaN,o=/^\d+$/.test(i)?Number(i):NaN,s=Number.isNaN(a)||Number.isNaN(o)?t.localeCompare(i):a-o;if(s!==0)return s}return 0}function Ve(e){return e===`latest`||R(e,`1.21.120`)>=0}function He(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(e.trim());if(!t)return;let n=/(?:^|[.-])(\d+)\.(\d+)\.(\d+)(?:[.-]|$)/.exec(t[4]??``);return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),...n?{minecraftTarget:[Number(n[1]),Number(n[2]),Number(n[3])]}:{}}}function Ue(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function We(e,t){let n=He(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?He(t[1]):void 0;return!r||n.major!==r.major||Ue(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?R(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}function Ge(e){if(e===`stable`||e===`beta`||e===`preview`)throw new F(`DEPENDENCY_VERSION_INVALID`,`${e} must be resolved from npm registry before writing package.json.`,{details:{specifier:e}});if(Be(e))return e;throw new F(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function Ke(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(R)}function qe(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(R)}var Je=class{npm;logger;constructor(e,t){this.npm=e,this.logger=t}latestStable(e,t){let n=this.npm.distTag(t,`latest`);if(n&&/^\d+\.\d+\.\d+$/.test(n))return this.logger?.verbose(`Resolved ${e}@stable -> ${n}`),n;let r=Ke(this.npm.versions(t)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@stable -> ${r}`),r}latestBeta(e,t){let n=this.npm.distTag(t,`beta`);if(n)return this.logger?.verbose(`Resolved ${e}@beta -> ${n}`),n;let r=qe(this.npm.versions(t)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@beta -> ${r}`),r}betaForTarget(e,t,n){let r=t.replace(/\./g,`\\.`),i=RegExp(`beta[-.]${r}-stable`),a=this.npm.versions(n).filter(e=>i.test(e)).sort(R).at(-1);if(!a)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@beta for target ${t}.`,{details:{package:e,specifier:`beta`,target:t},suggestions:[`Use target: "latest"`,`Specify an exact version`,`Update BePack`,`Manually edit package.json and manifest.json`]});return this.logger?.verbose(`Resolved ${e}@beta for target ${t} -> ${a}`),a}inferStableFromBeta(e,t,n,r){let i=/^(\d+)\.(\d+)\.(\d+)-beta[.-]/.exec(n);if(!i)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot infer stable version from ${e}@${n}.`,{details:{package:e,beta:n,target:t}});let a=Number(i[1]),o=Number(i[2])-1,s=`${a}.${o}.${Number(i[3])}`;if(o<0||!r.versions?.[s])throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot confirm inferred stable version ${s} for ${e}.`,{details:{package:e,target:t,beta:n,inferredStable:s}});return s}};function Ye(e,t){return t===`latest`||Ve(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function Xe(e,t,n){let r=qe(t).filter(e=>/^\d+\.\d+\.\d+-beta\.\d+\.\d+\.\d+/.test(e)).filter(e=>!/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@beta -> ${r}`),r}function Ze(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(R)}function Qe(e,t,n){let r=Ze(t).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@preview -> ${r}`),r}function $e(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(R).at(-1);if(!o)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@preview for target ${n}.`,{details:{package:e,specifier:`preview`,target:n},suggestions:[`Use target: "latest"`,`Specify an exact version`]});return r?.verbose(`Resolved ${e}@preview for target ${n} -> ${o}`),o}const et={name:`minecraft-script-api`,resolver:`minecraft-script-api`,match:e=>e.specifier===`stable`||e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Je(e.npm,e.logger);if(e.specifier===`stable`){e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`);let r=e.target===`latest`?n.latestStable(e.packageName,t):n.inferStableFromBeta(e.packageName,e.target,n.betaForTarget(e.packageName,e.target,t),t);return{packageVersion:r,manifestVersion:r}}if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ye(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Qe(e.packageName,e.npm.versions(t),e.logger):$e(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},tt={name:`minecraft-script-api-bp`,resolver:`minecraft-script-api-bp`,match:e=>e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Je(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ye(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Qe(e.packageName,e.npm.versions(t),e.logger):$e(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},nt=/^\d+\.\d+\.\d+$/,rt=/^\d+\.\d+\.\d+-preview\.\d+$/,it={name:`minecraft-vanilla-data`,resolver:`minecraft-vanilla-data`,match:e=>e.specifier===`stable`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName);return e.specifier===`stable`?at(e,t):ot(e,t)}};function at(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`),e.target===`latest`){let n=e.npm.distTag(t,`latest`);if(n&&nt.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>nt.test(e)).sort(R).at(-1);if(!r)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${r}`),{packageVersion:r}}if(t.versions?.[e.target])return e.logger?.verbose(`Resolved ${e.packageName}@stable for target ${e.target} -> ${e.target}`),{packageVersion:e.target};throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@stable for target ${e.target}. The target version does not exist in the registry.`,{details:{package:e.packageName,specifier:`stable`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact version`]})}function ot(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`),e.target===`latest`){let n=e.npm.versions(t).filter(e=>rt.test(e)).sort(R).at(-1);if(!n)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@preview -> ${n}`),{packageVersion:n}}let n=e.target.replace(/\./g,`\\.`),r=RegExp(`^${n}-preview\\.\\d+$`),i=e.npm.versions(t).filter(e=>r.test(e)).sort(R).at(-1);if(!i)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@preview for target ${e.target}. No matching preview version found.`,{details:{package:e.packageName,specifier:`preview`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact preview version`]});return e.logger?.verbose(`Resolved ${e.packageName}@preview for target ${e.target} -> ${i}`),{packageVersion:i}}const st={"@minecraft/common":{resolver:et,manifest:!0},"@minecraft/server":{resolver:et,manifest:!0},"@minecraft/server-ui":{resolver:et,manifest:!0},"@minecraft/server-net":{resolver:tt,manifest:!0},"@minecraft/server-admin":{resolver:tt,manifest:!0},"@minecraft/server-gametest":{resolver:tt,manifest:!0},"@minecraft/debug-utilities":{resolver:tt,manifest:!0},"@minecraft/diagnostics":{resolver:tt,manifest:!0},"@minecraft/server-graphics":{resolver:tt,manifest:!0},"@minecraft/server-editor":{resolver:tt,manifest:!0},"@minecraft/vanilla-data":{resolver:it,manifest:!1}};var ct=class e{static validateHeader(e,t){if(!e.header?.name||!e.header?.uuid)throw new F(`MANIFEST_INVALID`,`${t} manifest is missing header.name or header.uuid`);return{name:e.header.name,uuid:e.header.uuid,...e.header.description?{description:e.header.description}:{}}}static findScriptModuleUuid(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.uuid}static findScriptModuleEntry(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.entry}static findResourcesModuleUuid(t){for(let n of t.modules??[])if(n&&e.isResourcesModule(n))return n.uuid}static matchDependencies(e){let t={};for(let n of e.dependencies??[])if(`module_name`in n&&typeof n.module_name==`string`){let e=n.module_name;st[e]&&(t[e]=typeof n.version==`string`?n.version:String(n.version))}return t}static isScriptModule(e){return e?.type===`script`&&e?.language===`javascript`}static isResourcesModule(e){return e?.type===`resources`}};function lt(e,t){if(typeof e!=`string`||!e)throw new F(`MANIFEST_INVALID`,`${t} script module entry must be a non-empty string.`);let n=e.replace(/\\/g,`/`);if(s.posix.isAbsolute(n)||s.win32.isAbsolute(n))throw new F(`MANIFEST_INVALID`,`${t} script module entry must be a relative path, got absolute: "${e}".`);if(!n.endsWith(`.js`))throw new F(`MANIFEST_INVALID`,`${t} script module entry must end with .js, got: "${e}".`);let r=n.split(`/`);if(r.includes(`..`))throw new F(`MANIFEST_INVALID`,`${t} script module entry must not contain "..": "${e}".`);if(r.includes(``))throw new F(`MANIFEST_INVALID`,`${t} script module entry must not contain empty segments: "${e}".`);return n}function ut(e,t){let n=s.resolve(e,t),r=s.dirname(n),i=s.relative(e,r);if(i.startsWith(`..`)||s.isAbsolute(i))throw new F(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function dt(e,t){if(!t&&await P(e))throw new F(`CONFIG_INVALID`,`Config file already exists: ${e}. Use --force to overwrite.`,{suggestions:[`Pass --force to overwrite the existing file.`]})}async function ft(e,t,r,i=!1){return await dt(e,r),!i&&(await Ce(s.dirname(e)),await n.writeFile(e,t,`utf8`),!0)}const pt=[`.ts`,`.mts`,`.js`,`.mjs`];async function mt(e,t){let n=(t===`main`?[`main`]:[t,`main`]).flatMap(e=>pt.map(t=>`src/${e}${t}`));for(let t of n)if(await P(s.join(e,t))){let e=s.extname(t);return{entry:t,typecheckable:e===`.ts`||e===`.mts`,searched:n}}}function ht(e){return(e===`main`?[`main`]:[e,`main`]).map(e=>`src/${e}.{${pt.join(`,`).replace(/\./g,``)}}`).join(` or `)}function gt(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
|
|
9
|
-
$1$2: `)}\n`}function _t(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function vt(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function yt(e){if(Array.isArray(e)&&e.length===3)return e;if(typeof e==`string`){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}}async function bt(e,t){let n=t.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new F(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(e,`bepack.config.${n}`),i=!!t.force,a=!!t.dryRun,o=new L({silent:t.silent,verbose:t.verbose}),c=!!t.fromBp,l=!!t.fromRp,u,d,f,p=!1,m,h,g,_,v,y,b=[];if(c){let n=s.resolve(e,t.fromBp),r=await Re.read(n);if(!r)throw new F(`CONFIG_NOT_FOUND`,`BP manifest not found: ${t.fromBp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ct.validateHeader(r,`BP`),a=ct.findScriptModuleUuid(r),o=ct.findScriptModuleEntry(r),c=_t(r.header?.version);c&&b.push(c),u={root:ut(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:ct.matchDependencies(r),...o?{scriptEntry:o}:{}},m=i.name,h=i.description,g=i.name,_=i.description}if(l){let n=s.resolve(e,t.fromRp),r=await Re.read(n);if(!r)throw new F(`CONFIG_NOT_FOUND`,`RP manifest not found: ${t.fromRp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ct.validateHeader(r,`RP`),a=ct.findResourcesModuleUuid(r);if(!a)throw new F(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let o=_t(r.header?.version);o&&b.push(o),d={root:ut(e,n),uuid:i.uuid,moduleUuid:a,...o?{version:o}:{}},c||(m=i.name,h=i.description),v=i.name,y=i.description}let x;if(b.length===1)x=b[0];else if(b.length===2){let e=b[0],t=b[1];if(e===t)x=e;else{let n=yt(e),r=yt(t);x=n&&r?vt(n,r)>=0?e:t:e,o.warn(`BP version (${e}) and RP version (${t}) differ. Using ${x}.`)}}p&&(o.warn(`Detected format_version ${f} doesn't match the actual version format used in manifest. Falling back to format_version 2.`),f=2);let S={root:`.`,target:`latest`,pack:{outDir:`dist`}};f!==void 0&&(S.manifestFormat=f),x&&(S.version=x),m&&(S.name=m),h&&(S.description=h);let C={};if(u){let t={root:u.root,uuid:u.uuid};if(u.moduleUuid){if(t.moduleUuid=u.moduleUuid,u.scriptEntry){let n=lt(u.scriptEntry,`BP`),r=s.posix.dirname(n),i=s.posix.basename(n,`.js`);if(r===`.`)throw new F(`MANIFEST_INVALID`,`BP manifest script entry "${u.scriptEntry}" is at the BP root. BePack cannot safely manage root-level script output because the output directory would need to be emptied on each build, which would delete the entire BP root. Please add a subdirectory prefix to the script module entry in your manifest.json (e.g. "scripts/main.js"), then rerun init.`);let a=await mt(e,i);if(a){let n=await P(s.join(e,`tsconfig.json`)),i=a.typecheckable&&n;t.compile={entry:a.entry,scriptOutputDir:r,...i?{}:{typecheck:!1}},i||o.warn(`Detected script entry "${u.scriptEntry}" with source "${a.entry}", but ${a.typecheckable?`tsconfig.json is missing`:`the source is JavaScript`}. Generated config sets compile.typecheck: false.`+(a.typecheckable?` Add tsconfig.json and remove that flag to enable typechecking.`:``))}else o.warn(`BP manifest declares script entry "${u.scriptEntry}" but no matching source file exists (looked for ${ht(i)}). Leaving packs.bp.compile unset: the existing "${r}" folder is copied/packed as-is. Set packs.bp.compile manually once you add sources.`)}else o.warn("BP manifest has a script module but no `entry` field, so the script output directory cannot be derived. Leaving packs.bp.compile unset; add it manually to compile TypeScript into the pack.")}g&&(t.name=g),_&&(t.description=_),Object.keys(u.deps).length>0&&(t.dependencies={...u.deps}),C.bp=t}if(d){let e={root:d.root,uuid:d.uuid,moduleUuid:d.moduleUuid};v&&(e.name=v),y&&(e.description=y),C.rp=e}S.packs=C,process.platform===`win32`&&(S.copy={defaultTarget:`win`});let w=await ft(r,gt(S),i,a);return a&&o.info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:a,filesCreated:+!!w,files:[r]}}function xt(){return gt({root:`.`,name:`example-addon`,version:`1.0.0`,target:`latest`,packs:{bp:{root:`bp`,uuid:u(),moduleUuid:u(),compile:{entry:`src/main.ts`},dependencies:{"@minecraft/server":`stable`}}},pack:{outDir:`dist`}})}async function St(e){let t=s.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await bt(t,e);let n=e.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new F(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(t,`bepack.config.${n}`),i=!!e.dryRun,a=await ft(r,xt(),!!e.force,i);return i&&new L({silent:e.silent,verbose:e.verbose}).info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:i,filesCreated:+!!a,files:[r]}}const Ct=[`bepack.config.ts`,`bepack.config.mjs`,`bepack.config.js`],z={root:`.`,configured:{root:!1,packOutDir:!1},name:`minecraft-addon`,version:`1.0.0`,description:``,replace:{values:{},builtins:{VERSION:!1,NAME:!1,UUID:!1,DESCRIPTION:!1}},target:`latest`,plugins:[],install:{registry:`https://registry.npmjs.org/`,saveTo:`dependencies`,packageManager:`auto`,runPackageManager:!0,updatePackageJson:!0,updateManifest:!0,dependencyCatalog:{},dependencyResolvers:[]},build:{copy:!1,timing:!1},dev:{copy:!1},copy:{defaultTarget:``,targets:{}},pack:{name:`{name}-{version}`,outDir:`dist`},hooks:{}},wt={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},Tt={keepLooseFiles:!1,keepLoose:[],exclude:[],minifyJson:!0,packOptimizationVersion:`0.1.0`,allowUnsupportedTarget:!1},Et={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,typecheckArgs:[],preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:wt,scriptOutputDir:`scripts`},Dt=[`world`,`global`,`any`];function Ot(e){let t=[];return e.packs.bp&&t.push({type:`bp`,root:e.packs.bp.root,uuid:e.packs.bp.uuid,...e.packs.bp.moduleUuid===void 0?{}:{moduleUuid:e.packs.bp.moduleUuid},name:e.packs.bp.name,include:e.packs.bp.include}),e.packs.rp&&t.push({type:`rp`,root:e.packs.rp.root,uuid:e.packs.rp.uuid,moduleUuid:e.packs.rp.moduleUuid,name:e.packs.rp.name,include:e.packs.rp.include}),t}const kt=[`scripts`,`manifest.json`,`animation_controllers`,`animations`,`biomes`,`blocks`,`cameras`,`dialogue`,`entities`,`functions`,`items`,`loot_tables`,`pack_icon.png`,`recipes`,`shapes`,`spawn_rules`,`structures`,`texts`,`trading`,`feature_rules`,`features`,`worldgen`],At=[];function jt(e,t){return s.isAbsolute(t)?t:s.join(e,t)}function B(e){return e.replace(/\\/g,`/`)}function V(e,t){return jt(e,t.root)}function H(e,t,n){return n===`bp`?t.packs.bp?jt(e,t.packs.bp.root):void 0:t.packs.rp?jt(e,t.packs.rp.root):void 0}function Mt(e,t){let n=H(V(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function Nt(e,t){let n=H(V(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function Pt(e){return!!e.packs.bp?.compile}function U(e,t){if(t.packs.bp?.compile)return jt(V(e,t),t.packs.bp.compile.entry)}function Ft(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return s.join(Mt(e,t),n)}function It(e,t){let n=Ft(e,t);if(!n)return;if(!t.packs.bp?.compile)return s.join(n,`main.js`);let r=s.basename(t.packs.bp.compile.entry,s.extname(t.packs.bp.compile.entry));return s.join(n,`${r}.js`)}function Lt(e,t){let n=s.relative(e,t);return n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n)}function Rt(e,t,n){if(!t||t===`.`)throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a non-empty relative path strictly inside the BP root. Got: "${t}". This directory will be emptied during build.`);let r=t.replace(/\\/g,`/`);if(s.posix.isAbsolute(r)||s.win32.isAbsolute(r))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a relative path, not absolute. Got: "${t}". This directory will be emptied during build.`);let i=s.posix.normalize(r);if(i.split(`/`).includes(`..`))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must not contain ".." (path escape). Got: "${t}" resolves outside the BP root. This directory will be emptied during build.`);let a=s.resolve(e,i),o=s.relative(e,a);if(!o||o.startsWith(`..`)||s.isAbsolute(o))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir must be a directory strictly inside the BP root. Value: "${t}", resolved: "${a}". This directory will be emptied during build and must not be the BP root or a path outside it.`);if(n&&Lt(a,n))throw new F(`CONFIG_INVALID`,`compile.scriptOutputDir "${t}" dangerously overlaps with the source entry directory. The output directory will be emptied during build and would delete source files.`);return B(o)}function zt(e,t,n,r=[]){let a=s.resolve(e),o=s.resolve(t),c=[o,...r.map(e=>s.resolve(e))];for(let t of c)if(Lt(a,t))throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" would overwrite a protected path ("${t}"). Refusing to empty this directory.`);try{if(!i(a).isDirectory())throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not a directory. Refusing to empty a non-directory path.`)}catch(e){if(e?.code!==`ENOENT`)throw e}let l=s.relative(o,a);if(!l||l.startsWith(`..`)||s.isAbsolute(l))throw new F(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not inside the BP root "${t}". Refusing to empty this directory.`)}function Bt(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...kt.filter(e=>e!==`scripts`)],n=e.packs.bp?.include??[],r=[...t,...n],i=/* @__PURE__ */ new Set;return r.filter(e=>!i.has(e)&&(i.add(e),!0))}function Vt(e,t){if(t.packs.bp)return s.join(Mt(e,t),`manifest.json`)}function Ht(e,t){if(t.packs.rp)return s.join(Nt(e,t),`manifest.json`)}function Ut(e,t){return jt(V(e,t),t.pack.outDir)}const Wt=f()!==`win32`;function Gt(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=B(s.resolve(e)),r=Wt?n:n.toLowerCase();return!t.has(r)&&(t.add(r),!0)})}const Kt={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function qt(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function Jt(e){let t=qt(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,Kt[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[p(r,{delimiters:[``,``]})]}function Yt(e){return{values:e?.values??{},builtins:{VERSION:e?.builtins?.VERSION??!1,NAME:e?.builtins?.NAME??!1,UUID:e?.builtins?.UUID??!1,DESCRIPTION:e?.builtins?.DESCRIPTION??!1}}}function Xt(e){let t={...e??{}};for(let[e,n]of Object.entries(t))try{Function(`return (${n});`)}catch{throw new F(`CONFIG_INVALID`,`packs.bp.compile.define["${e}"] is not a valid JavaScript expression: ${n}. Define values must be expression strings, e.g. JSON.stringify("server") or "true".`,{details:{defineKey:e,defineValue:n}})}return t}function Zt(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}const Qt=`tsc --noEmit`;function $t(e){let t=[],n=``,r,i=!1;for(let a=0;a<e.length;a+=1){let o=e[a];if(r){o===r?r=void 0:o===`\\`&&e[a+1]===r?(a+=1,n+=r):n+=o;continue}if(o===`"`||o===`'`){r=o,i=!0;continue}if(o===`\\`&&(e[a+1]===`"`||e[a+1]===`'`)){a+=1,n+=e[a],i=!0;continue}if(/\s/.test(o)){i&&=(t.push(n),n=``,!1);continue}n+=o,i=!0}if(r)throw new F(`CONFIG_INVALID`,`Unterminated ${r===`"`?`double`:`single`} quote in typecheck command: ${e}`);return i&&t.push(n),t}function en(e,t=[],n={}){let r=typeof e==`string`?e.trim():``;if(r===``){let e=[...$t(Qt)],r=e.shift(),i=[...tn(e,n),...t];return n.useNpx?{command:`npx`,args:[r,...i],label:`npx tsc --noEmit`,isDefault:!0}:{command:r,args:i,label:Qt,isDefault:!0}}let i=$t(r),a=i[0];if(!a)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${JSON.stringify(e)}`);return{command:a,args:[...i.slice(1),...t],label:r,isDefault:!1}}function tn(e,t){let n=[...e];return t.tsconfigPath&&n.push(`--project`,t.tsconfigPath),t.incremental&&t.tsBuildInfoFile&&n.push(`--incremental`,`--tsBuildInfoFile`,t.tsBuildInfoFile),n}function nn(e){return[e.command,...e.args].map(e=>/\s/.test(e)?JSON.stringify(e):e).join(` `)}function rn(e,t){if(e===void 0||typeof e==`boolean`)return{typecheck:e??t.typecheck,...t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand},typecheckArgs:t.typecheckArgs??[]};if(typeof e!=`object`||!e||Array.isArray(e))throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck must be a boolean or an object { enabled?, command?, args? }, got: ${cn(e)}.`);sn(e);let{enabled:n,command:r,args:i}=e;if(n!==void 0&&typeof n!=`boolean`)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.enabled must be a boolean, got: ${cn(n)}.`);if(r!==void 0&&typeof r!=`string`)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a string, got: ${cn(r)}.`);if(typeof r==`string`&&r.trim()===``)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${cn(r)}.`);let a=an(i,`packs.bp.compile.typecheck.args`);return{typecheck:n??t.typecheck,...r===void 0?t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand}:{typecheckCommand:r},typecheckArgs:a??t.typecheckArgs??[]}}function an(e,t){if(e!==void 0){if(!Array.isArray(e))throw new F(`CONFIG_INVALID`,`${t} must be an array of strings, got: ${cn(e)}.`);return e.map(e=>{if(typeof e!=`string`)throw new F(`CONFIG_INVALID`,`${t} entries must be strings, got: ${cn(e)}.`);return e})}}function on(e,t){if(e!==void 0){if(typeof e!=`string`||e.trim()===``)throw new F(`CONFIG_INVALID`,`${t} must be a non-empty command line string, got: ${cn(e)}.`);return e.trim()}}function sn(e){let t=e;if(t.typechecker!==void 0)throw new F(`CONFIG_INVALID`,`packs.bp.compile.typecheck.typechecker was replaced by packs.bp.compile.typecheck.command: write the full command line instead, e.g. { command: "bun check" }, got: ${cn(t.typechecker)}.`)}function cn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}const ln=[et,tt,it,{name:`exact-version`,match:e=>Be(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Ge(e.specifier),manifestVersion:e.specifier}}}];var un=class e{resolvers;pluginNames=/* @__PURE__ */ new Map;constructor(e,t=[]){this.resolvers=e;for(let e of t)for(let t of e.install?.dependencyResolvers??[])this.pluginNames.set(t,e.name)}static fromConfig(t,n=[]){return new e([...t,...ln],n)}resolverMatchesCatalog(e,t){let n=e.entry.resolver;if(!n)return!0;let r=typeof n==`string`?n:n.name;return t.resolver===void 0||t.resolver===r}find(e){let t;for(let n of this.resolvers)if(this.resolverMatchesCatalog(e,n))try{if(n.match(e)){t=n;break}}catch(e){let t=this.pluginNames.get(n);throw t?new F(`PLUGIN_FAILED`,`Plugin ${t} resolver ${n.name} match failed: ${e instanceof Error?e.message:String(e)}`):e}if(!t)throw new F(`DEPENDENCY_VERSION_INVALID`,`${e.packageName} dependency version is invalid: ${e.specifier}`,{details:{package:e.packageName,specifier:e.specifier,resolver:e.entry.resolver}});return e.logger?.verbose(`Resolving ${e.packageName}@${e.specifier} with ${t.name}`),t}async resolve(e){let t=this.find(e);try{return await t.resolve(e)}catch(e){let n=this.pluginNames.get(t);throw n?new F(`PLUGIN_FAILED`,`Plugin ${n} resolver ${t.name} failed: ${e instanceof Error?e.message:String(e)}`):e}}};const dn=`sapi-pro`,fn=[`@minecraft/server`,`@minecraft/server-ui`];function pn(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function mn(e){return pn(e)?`beta`:`stable`}function hn(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function gn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function _n(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...st,...e.config.install.dependencyCatalog},o=un.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==yn),e.config.plugins);for(let[s,c]of Object.entries(t)){if(!s.startsWith(`@minecraft/`))continue;let t=i[s],l=a[s];if(!t||!l)return r.add(s),!1;let u;if(n.has(s)?u=n.get(s):(u=await o.resolve({packageName:s,specifier:t,target:e.target,entry:l,config:e.config,npm:e.npm,...e.logger?{logger:e.logger}:{}}),n.set(s,u)),!u||fn.includes(s)&&pn(c)!==pn(u.packageVersion)||!We(u.packageVersion,c))return!1}return!0}function vn(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!hn(e))return!1;let r=gn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>R(e,t)).reverse()}const yn={name:`sapi-pro`,resolver:`sapi-pro`,match:e=>e.specifier===`stable`||e.specifier===`beta`||/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(e.specifier),async resolve(e){let t=await e.npm.metadata(dn),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set;for(let[i,a]of vn(t.versions??{},e.specifier))if(await _n(e,gn(a),n,r))return/^0\.3\./.test(i)&&e.logger?.warn(`sapi-pro@${i} uses legacy metadata; compatibility is best-effort only.`),{packageVersion:i,manifestVersion:null};throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot find a compatible ${dn}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:dn,specifier:e.specifier,target:e.target},suggestions:[`Explicitly declare the @minecraft packages required by sapi-pro.`,`Use a compatible target or specify an exact sapi-pro version.`]})}};function bn(){return{name:`sapi-pro`,apiVersion:1,description:`Resolve sapi-pro versions compatible with BePack Script API dependencies.`,configResolved:({config:e})=>{let t=e.packs.bp?.dependencies??{},n=t[dn];if(!n)return;let r=fn.filter(e=>!t[e]);if(r.length>0)throw Error(`sapi-pro requires explicit dependencies: ${r.join(`, `)}.`);if(n===`stable`||n===`beta`)for(let e of fn){let r=t[e];if(mn(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[dn]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[yn]}}}const xn={"sapi-pro":bn};function W(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function Sn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`function`?`function`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}function Cn(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...W(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...W(t.packs?.rp)});let r={...e.copy?.targets??{},...W(t.copy?.targets)},i=W(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...W(t.install)},build:{...e.build,...W(t.build)},dev:{...e.dev,...W(t.dev)},copy:{...e.copy,...W(t.copy),targets:r},pack:{...e.pack,...W(t.pack)},hooks:{...e.hooks,...W(t.hooks)}}}function wn(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=xn[e];if(!t)throw new F(`CONFIG_INVALID`,`Unknown built-in plugin: ${e}.`);return t()}),n=/* @__PURE__ */ new Set;for(let e of t){if(!e?.name||e.name.trim()===``)throw new F(`CONFIG_INVALID`,`Every plugin must have a non-empty name.`);if(n.has(e.name))throw new F(`CONFIG_INVALID`,`Plugin name is duplicated: ${e.name}.`);if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new F(`CONFIG_INVALID`,`Plugin ${e.name} requires unsupported BePack plugin API version ${e.apiVersion}.`);if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new F(`CONFIG_INVALID`,`Plugin ${e.name} priority must be a finite number.`);n.add(e.name)}return t.sort((e,t)=>(t.priority??0)-(e.priority??0))}function Tn(e,t){let n=/* @__PURE__ */ new Set;for(let r of[...e.map(e=>e.hooks),t])for(let e of Object.keys(r??{}))n.add(e);return Object.fromEntries([...n].map(n=>{let r=[...e.map(e=>({plugin:e,hook:e.hooks?.[n]})).filter(e=>e.hook!==void 0),...t?.[n]?[{hook:t[n]}]:[]];return[n,async(...e)=>{let t;for(let i of r)try{t=await i.hook(...e)}catch(e){let t=`plugin`in i?i.plugin:void 0;throw t?new F(`PLUGIN_FAILED`,`Plugin ${t.name} ${String(n)} hook failed: ${e instanceof Error?e.message:String(e)}`):e}return t}]}))}function En(e,t){let n={},r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let[e,a]of Object.entries(t.install?.dependencyCatalog??{})){let o=r.get(e);if(o){i.push(`dependency catalog ${e}: plugin ${o} takes precedence over plugin ${t.name}`);continue}n[e]=a,r.set(e,t.name)}for(let[e,a]of Object.entries(t)){let t=r.get(e);t&&i.push(`dependency catalog ${e}: project config overrides plugin ${t}`),n[e]=a}return{catalog:n,diagnostics:i}}function Dn(e,t,n){let r=Et,i=e?.scriptOutputDir??r.scriptOutputDir,a=s.resolve(n,e?.entry??r.entry),o=Rt(t,i,s.dirname(a)),c=on(e?.typecheckCommand,`packs.bp.compile.typecheckCommand`)??r.typecheckCommand,l=an(e?.typecheckArgs,`packs.bp.compile.typecheckArgs`),u=rn(e?.typecheck,{typecheck:r.typecheck,...c===void 0?{}:{typecheckCommand:c},...l===void 0?{}:{typecheckArgs:l}});return{entry:e?.entry??r.entry,define:Xt(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:u.typecheck,typecheckArgs:u.typecheckArgs,...u.typecheckCommand===void 0?{}:{typecheckCommand:u.typecheckCommand},preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:p(e?.cache),scriptOutputDir:o,...e?.rolldown===void 0?{}:{rolldown:d(e.rolldown)},...e?.rolldownConfig===void 0?{}:{rolldownConfig:f(e.rolldownConfig)}};function d(e){if(typeof e==`function`||e&&typeof e==`object`&&!Array.isArray(e))return e;throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown must be a rolldown options object or a function (options, context) => options, got: ${Sn(e)}.`)}function f(e){if(typeof e!=`string`||e.trim()===``)throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldownConfig must be a non-empty path string, got: ${Sn(e)}.`);return e}function p(e){let t=wt;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function On(e){if(e===void 0||e===!1)return;let t=e===!0?{}:e;if(typeof t!=`object`||!t||Array.isArray(t))throw new F(`CONFIG_INVALID`,`pack.optimize must be a boolean or an options object, got: ${Sn(e)}.`);let n=t.packOptimizationVersion;if(n!==void 0&&(typeof n!=`string`||n.trim()===``))throw new F(`CONFIG_INVALID`,`pack.optimize.packOptimizationVersion must be a non-empty string, got: ${Sn(n)}.`);return{keepLooseFiles:t.keepLooseFiles??Tt.keepLooseFiles,keepLoose:t.keepLoose!==!1&&(t.keepLoose??[]).map(kn),exclude:(t.exclude??[]).map(kn),minifyJson:t.minifyJson??Tt.minifyJson,packOptimizationVersion:n??Tt.packOptimizationVersion,allowUnsupportedTarget:t.allowUnsupportedTarget??Tt.allowUnsupportedTarget}}function kn(e){let t=String(e).replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(!t||t.includes(`/`)||t.includes(`..`)||s.posix.isAbsolute(t))throw new F(`CONFIG_INVALID`,`pack.optimize.exclude entries must be top-level folder names (no path separators, no ".."), got: ${Sn(e)}.`);return t}function An(e){let t=e?.merge??`preserve`;if(t!==`preserve`&&t!==`clean`)throw new F(`CONFIG_INVALID`,`manifest.merge must be "preserve" or "clean", got: ${String(e?.merge)}.`);let n=e?.minEngineVersion;if(n!==void 0&&!/^\d+\.\d+\.\d+$/.test(n))throw new F(`CONFIG_INVALID`,`manifest.minEngineVersion must be a SemVer string like "1.21.0", got: ${n}.`);return{merge:t,...n===void 0?{}:{minEngineVersion:n},extraDependencies:e?.extraDependencies??[],extraModules:e?.extraModules??[],extraHeader:e?.extraHeader??{}}}function jn(e,t={},n=process.cwd()){let r=Cn(e,t),i=wn(r.plugins),a=r.target??z.target;if(a===`stable`||a===`beta`)throw new F(`TARGET_INVALID`,`target must be a Minecraft game version or latest, not a Script API channel.`,{details:{target:a}});let o=!!r.packs?.bp,c=!!r.packs?.rp;if(!o&&!c)throw new F(`CONFIG_INVALID`,`At least one pack (packs.bp or packs.rp) is required.`);if(!r.name||r.name.trim()===``)throw new F(`CONFIG_INVALID`,`name is required.`);let l=r.name,u=r.version??z.version,d=r.description,f=r.packs,p=f.bp?.compile,m=f.bp,h=f.rp;if(m){if(!m.uuid)throw new F(`CONFIG_INVALID`,`packs.bp.uuid is required.`);if(m.compile&&!m.moduleUuid)throw new F(`CONFIG_INVALID`,`packs.bp.moduleUuid is required when packs.bp.compile is configured.`);if(m.root===void 0)throw new F(`CONFIG_INVALID`,`packs.bp.root is required. Set the behavior pack directory in bepack.config.ts.`);if(p?.define){let e=Object.keys(r.replace?.values??{}),t=Object.keys(p.define),n=e.filter(e=>t.includes(e));if(n.length>0)throw new F(`CONFIG_INVALID`,`Config conflict: ${n.map(e=>`"${e}"`).join(`, `)} is configured in both replace.values and packs.bp.compile.define. Use only one mechanism per key.`,{details:{overlap:n}})}}let g=s.resolve(n,r.root??`.`),_=m?s.resolve(g,m.root):void 0;if(h){if(!h.uuid||!h.moduleUuid)throw new F(`CONFIG_INVALID`,`packs.rp.uuid and packs.rp.moduleUuid are required.`);if(h.root===void 0)throw new F(`CONFIG_INVALID`,`packs.rp.root is required when packs.rp is configured.`);if(h.packScope!==void 0&&!Dt.includes(h.packScope))throw new F(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${Dt.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=En(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]),C=On(r.pack?.optimize),w=On(r.copy?.optimize);return{root:r.root??z.root,configured:{root:r.root!==void 0,packOutDir:r.pack?.outDir!==void 0},name:l,version:u,...d===void 0?{}:{description:d},replace:Yt(r.replace),target:a,plugins:i,...x.length>0?{pluginDiagnostics:x}:{},...r.manifestFormat===void 0?{}:{manifestFormat:r.manifestFormat},packs:{...m?{bp:{root:m.root,uuid:m.uuid,...m.moduleUuid===void 0?{}:{moduleUuid:m.moduleUuid},name:m.name??l,...v===void 0?{}:{description:v},...p&&_?{compile:Dn(p,_,g)}:{},manifest:An(m.manifest),dependencies:m.dependencies??{},...m.achievement===void 0?{}:{achievement:m.achievement},include:m.include??[]}}:{},...h?{rp:{root:h.root,uuid:h.uuid,moduleUuid:h.moduleUuid,name:h.name??l,...y===void 0?{}:{description:y},manifest:An(h.manifest),...h.pbr===void 0?{}:{pbr:h.pbr},...h.packScope===void 0?{}:{packScope:h.packScope},include:h.include??[]}}:{}},install:{registry:r.install?.registry??z.install.registry,saveTo:r.install?.saveTo??z.install.saveTo,packageManager:r.install?.packageManager??z.install.packageManager,runPackageManager:r.install?.runPackageManager??z.install.runPackageManager,updatePackageJson:r.install?.updatePackageJson??z.install.updatePackageJson,updateManifest:r.install?.updateManifest??z.install.updateManifest,dependencyCatalog:b,dependencyResolvers:[...S,...r.install?.dependencyResolvers??[]]},build:{copy:r.build?.copy??z.build.copy,timing:r.build?.timing??z.build.timing},dev:{copy:r.dev?.copy??z.dev.copy,...r.dev?.watch?{watch:r.dev.watch}:{}},copy:{defaultTarget:r.copy?.defaultTarget??z.copy.defaultTarget,...r.copy?.name?{name:r.copy.name}:{},...r.copy?.include?{include:r.copy.include}:{},targets:r.copy?.targets??{},...w?{optimize:w}:{}},pack:{name:r.pack?.name??z.pack.name,outDir:r.pack?.outDir??z.pack.outDir,...C?{optimize:C}:{}},hooks:Tn(i,r.hooks)}}async function Mn(e,t){if(t){let r=jt(e,t);return await n.access(r).catch(()=>{throw new F(`CONFIG_NOT_FOUND`,`Config not found: ${t}`,{details:{configPath:t}})}),r}for(let t of Ct){let r=s.join(e,t);try{return await n.access(r),r}catch{}}throw new F(`CONFIG_NOT_FOUND`,`No bepack.config.ts, bepack.config.mjs, or bepack.config.js found.`,{details:{cwd:e}})}async function Nn(e){try{if(e.endsWith(`.ts`))try{return await import(`${o(e).href}?t=${Date.now()}`)}catch{let t=Pn(await n.readFile(e,`utf8`));return await import(`data:text/javascript;base64,${Buffer.from(t,`utf8`).toString(`base64`)}`)}return await import(`${o(e).href}?t=${Date.now()}`)}catch(t){throw new F(`CONFIG_INVALID`,`Failed to load config: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Use bepack.config.mjs/js for complex config logic.`,`Keep bepack.config.ts free of TypeScript-only runtime syntax.`]})}}function Pn(e){return e.replace(/^\s*import\s+type\s+[^;]+;\s*$/gm,``).replace(/\s+satisfies\s+[A-Za-z_$][\w$<>,\s.[\]|&{}]*/g,``).replace(/\((\s*[A-Za-z_$][\w$]*)\s*:\s*[^)=]+?\)\s*=>/g,`($1) =>`)}async function Fn(e,t){for(let n of e.plugins??[])if(n.configResolved)try{await n.configResolved({cwd:t,config:e})}catch(e){throw new F(`PLUGIN_FAILED`,`Plugin ${n.name} configResolved hook failed: ${e instanceof Error?e.message:String(e)}`)}}async function In(e){let t=s.resolve(e.cwd),n=await Mn(t,e.configPath),r=await Nn(n);if(r.default===void 0)throw new F(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=jn(r.default,e.overrides,t);return await Fn(i,t),{config:i,path:n,cwd:t}}function Ln(e){return{...st,...e.install.dependencyCatalog}}function Rn(e,t){let n=e[t];if(!n)throw new F(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency. Add it to install.dependencyCatalog or remove it from packs.bp.dependencies.`,{details:{package:t}});return n}function zn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var Bn=class{registry;logger;cache=/* @__PURE__ */ new Map;constructor(e,t){this.registry=e,this.logger=t}async metadata(e){let t=this.packageUrl(e),n=this.cache.get(t);if(n)return this.logger?.verbose(`Using cached metadata for ${e}`),n;zn(this.logger,`fetching ${e} metadata from ${this.registry}`);let r=await fetch(t);if(!r.ok)throw new F(`SAPI_VERSION_NOT_FOUND`,`Cannot fetch ${e} versions from registry.`,{details:{package:e,registry:this.registry,status:r.status}});let i=await r.json();return this.cache.set(t,i),this.logger?.verbose(`Fetched ${e} metadata (${Object.keys(i.versions??{}).length} versions)`),i}versions(e){return Object.keys(e.versions??{})}async versionsOf(e){return this.versions(await this.metadata(e))}distTag(e,t){let n=e[`dist-tags`]?.[t];return n&&e.versions?.[n]?n:void 0}packageUrl(e){return`${this.registry.replace(/\/$/,``)}/${encodeURIComponent(e).replace(/^%40/,`@`)}`}};function Vn(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var Hn=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new Bn(e.install.registry,t),this.catalog=Ln(e),this.pkgResolver=new Je(this.npm,t),this.log=Vn(t)}async resolveAll(){let e={},t=this.config.packs.bp?.dependencies;if(!t||Object.keys(t).length===0)return this.log(`no BP dependencies to resolve`),e;this.log(`resolving dependencies for target ${this.config.target}`);for(let[n,r]of Object.entries(t)){let t=Rn(this.catalog,n),i=await this.resolveOne(n,r,t),a=t.manifest??!1;e[n]={specifier:r,packageVersion:i.packageVersion,manifestVersion:a?i.manifestVersion??i.packageVersion:null,manifest:a,external:a,resolver:typeof t.resolver==`string`?t.resolver:t.resolver.name},this.log(`${n}: ${r} -> package ${e[n].packageVersion}, manifest ${e[n].manifestVersion}`)}return this.logger?.verbose(`Dependency resolution complete`),e}async resolveOne(e,t,n){let r={packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config};await this.runDependencyHooks(`beforeResolveDependency`,r);let i=await un.fromConfig(this.config.install.dependencyResolvers,this.config.plugins??[]).resolve({packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config,npm:this.npm,...this.logger?{logger:this.logger}:{}});return await this.runDependencyHooks(`afterResolveDependency`,{...r,result:i}),i}async runDependencyHooks(e,t){for(let n of this.config.plugins??[]){let r=n.install?.hooks?.[e];if(r)try{await r(t)}catch(t){throw new F(`PLUGIN_FAILED`,`Plugin ${n.name} ${e} hook failed: ${t instanceof Error?t.message:String(t)}`)}}}};async function Un(e,t,n,r=!1){let i=s.join(e,`package.json`);if(!await P(i))throw new F(`PACKAGE_JSON_NOT_FOUND`,`package.json not found.`,{details:{cwd:e}});let a=await Te(i),o=t.install.saveTo;a.dependencies=a.dependencies??{},a.devDependencies=a.devDependencies??{};for(let e of Object.keys(n))delete a.dependencies[e],delete a.devDependencies[e];a[o]=a[o]??{};for(let[e,t]of Object.entries(n))a[o][e]=t.packageVersion;return Object.keys(a.dependencies).length||delete a.dependencies,Object.keys(a.devDependencies).length||delete a.devDependencies,r||await Ee(i,a),{updated:!0,path:`package.json`}}const Wn=[1,21,0],Gn=[1,0,0];var Kn=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=ze(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Fe(e);this.depManager.validateBpDependencies();let r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanBp(t,r):this.buildPreserveBp(n,t,r);return this.applyAchievementMetadata(i,t),i}buildRp(e){let t=this.requireRp(),n=Fe(e),r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanRp(t,r):this.buildPreserveRp(n,t,r);return this.applyPbrCapability(i,t),i}buildPreserveBp(e,t,n){return{...e,format_version:n,header:this.buildBpHeader(e,t,n),...t.moduleUuid?{modules:this.replaceManagedBpModules(e.modules,t,n)}:e.modules?{modules:e.modules}:{},dependencies:this.depManager.replaceBpDependencies(e.dependencies,this.config.packs.rp?.uuid,n)}}buildPreserveRp(e,t,n){return{...e,format_version:n,header:this.buildRpHeader(e,t,n),modules:this.replaceManagedRpModules(e.modules,t,n),dependencies:this.depManager.replaceRpDependencies(e.dependencies,this.config.packs.bp?.uuid,n)}}buildCleanBp(e,t){return{format_version:t,header:this.buildBpHeaderClean(e,t),...e.moduleUuid?{modules:this.buildCleanBpModules(e,t)}:{},dependencies:this.depManager.buildBpDependenciesClean(t,this.config.packs.rp?.uuid,e.manifest.extraDependencies)}}buildCleanRp(e,t){return{format_version:t,header:this.buildRpHeaderClean(e,t),modules:this.buildCleanRpModules(e,t),dependencies:this.depManager.buildRpDependenciesClean(t,this.config.packs.bp?.uuid,e.manifest.extraDependencies)}}buildBpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildRpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,...e.packScope===void 0?{}:{pack_scope:e.packScope},version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildCleanBpModules(e,t){return[...e.moduleUuid?[this.createScriptModule(e,t)]:[],...e.manifest.extraModules]}buildCleanRpModules(e,t){return[this.createResourcesModule(e,t),...e.manifest.extraModules]}buildBpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}buildRpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,...t.packScope===void 0?{}:{pack_scope:t.packScope},version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}getScriptEntry(){let e=this.config.packs.bp?.compile;return e?`${e.scriptOutputDir}/${s.basename(e.entry,s.extname(e.entry))}.js`:`scripts/main.js`}isManagedBpModule(e,t){if(e.type!==`script`||e.language!==`javascript`)return!1;let n=this.getScriptEntry();return e.uuid===t.moduleUuid||e.entry===n}isManagedRpModule(e,t){return e.type===`resources`&&e.uuid===t.moduleUuid}createScriptModule(e,t){return{type:`script`,language:`javascript`,uuid:e.moduleUuid,version:this.getModuleVersion(t),entry:this.getScriptEntry()}}createResourcesModule(e,t){return{type:`resources`,uuid:e.moduleUuid,version:this.getModuleVersion(t)}}replaceManagedBpModules(e,t,n){return[...Ie(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Ie(e).filter(e=>!this.isManagedRpModule(e,t)),this.createResourcesModule(t,n)]}applyAchievementMetadata(e,t){if(t.achievement===!0)e.metadata={...e.metadata??{},product_type:`addon`};else if(t.achievement===!1&&e.metadata){let t={...e.metadata};delete t.product_type;let n=Le(t);n?e.metadata=n:delete e.metadata}}applyPbrCapability(e,t){if(t.pbr===!0){let t=Ie(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Ie(e.capabilities).filter(e=>e!==`pbr`);t.length>0?e.capabilities=t:delete e.capabilities}}getVersionFor(e){return e===3?this.versionStr:this.version}getModuleVersion(e){return e===3?`1.0.0`:Gn}getWriteFormatVersion(e){return this.config.manifestFormat===void 0?e.format_version??2:this.config.manifestFormat}normalizeMinEngineVersion(e,t,n){if(n!==void 0)return this.configMinEngineVersion(n,t);if(e==null)return this.defaultMinEngineVersion(t);if(Array.isArray(e))return t===3?e.join(`.`):e;if(typeof e==`string`){if(t===2){let t=this.stringToVersionTuple(e);if(t)return t}return e}return this.defaultMinEngineVersion(t)}configMinEngineVersion(e,t){return t===3?e:this.stringToVersionTuple(e)??this.defaultMinEngineVersion(t)}defaultMinEngineVersion(e){return e===3?`1.21.0`:Wn}stringToVersionTuple(e){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}requireBp(){if(!this.config.packs.bp)throw new F(`CONFIG_INVALID`,`packs.bp is required to build the BP manifest.`);return this.config.packs.bp}requireRp(){if(!this.config.packs.rp)throw new F(`CONFIG_INVALID`,`packs.rp is required to build the RP manifest.`);return this.config.packs.rp}},qn=class e{config;catalog;installVersions;manifestVersions;version;versionStr;dependencyDiagnostics=[];constructor(e,t,n={}){this.config=e,this.catalog=t,this.installVersions=n.install??{},this.manifestVersions=n.manifest??{},this.version=ze(e.version),this.versionStr=e.version}static isAllowedSpecifier(e){return e===`stable`||e===`beta`||e===`preview`||/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}static resolveVersion(t){return e.resolveVersionDetail(t).version}static resolveVersionDetail(e){let{specifier:t,target:n,resolvedVersion:r,manifestVersion:i}=e;if(t===`stable`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,"Run `bepack install` to resolve stable manifest dependencies.",{details:{specifier:t,target:n}})}if(t===`beta`){if(Ve(n))return{version:`beta`,source:`config`};if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve manifest dependencies for target ${n}.`,{details:{target:n}})}if(t===`preview`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new F(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve preview manifest dependencies for target ${n}.`,{details:{specifier:t,target:n}})}return{version:t,source:`config`}}static isAchievementCompatible(e){return e!==`beta`&&e!==`preview`}validateBpDependencies(){if(this.config.packs.bp){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[t]){let e=Object.keys(this.catalog),n=e.length>0?[`Managed packages: ${e.join(`, `)}.`,`Add a missing package to install.dependencyCatalog, or remove it from packs.bp.dependencies.`]:[`No managed packages are available. Extend install.dependencyCatalog to add one.`];throw new F(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency.`,{details:{package:t},suggestions:n})}if(!e.isAllowedSpecifier(n))throw new F(`DEPENDENCY_VERSION_INVALID`,`${t} dependency version is invalid: ${n}`,{details:{package:t,specifier:n}})}if(this.config.packs.bp.achievement){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies))if(!e.isAchievementCompatible(n))throw new F(`ACHIEVEMENT_REQUIRES_STABLE_API`,`${t}: achievement requires stable Script API dependencies (${n} is not allowed).`)}}}isManagedBpDependency(e){return!!(`module_name`in e&&typeof e.module_name==`string`&&this.catalog[e.module_name]?.manifest||`uuid`in e&&typeof e.uuid==`string`&&this.config.packs.rp?.uuid===e.uuid)}isManagedRpDependency(e,t){return t!==void 0&&`uuid`in e&&typeof e.uuid==`string`&&e.uuid===t}buildManagedDependencies(){if(this.dependencyDiagnostics.length=0,!this.config.packs.bp)return[];let t=[];for(let[n,r]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[n]?.manifest)continue;let i=e.resolveVersionDetail({specifier:r,target:this.config.target,resolvedVersion:this.installVersions[n],manifestVersion:this.manifestVersions[n]});t.push({module_name:n,version:i.version}),this.dependencyDiagnostics.push({name:n,specifier:r,version:i.version,source:i.source})}return t}getDependencyDiagnostics(){return this.dependencyDiagnostics}getFormatAwareVersion(e){return(e??this.config.manifestFormat??2)===3?this.versionStr:this.version}replaceBpDependencies(e,t,n){let r=Ie(e).filter(e=>!this.isManagedBpDependency(e)),i=this.buildManagedDependencies();return t&&i.push({uuid:t,version:this.getFormatAwareVersion(n)}),[...r,...i]}replaceRpDependencies(e,t,n){let r=Ie(e).filter(e=>!this.isManagedRpDependency(e,t));return t?[...r,{uuid:t,version:this.getFormatAwareVersion(n)}]:r}buildBpDependenciesClean(e,t,n){let r=this.buildManagedDependencies();return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}buildRpDependenciesClean(e,t,n){let r=[];return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}};const Jn=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Yn(e){let t=Ln(e.config),n=e.config.packs.bp?Vt(e.cwd,e.config):void 0,r=n?await Re.read(n):void 0,i=Zn(r,t),a=new qn(e.config,t,{...e.resolvedDeps?{install:e.resolvedDeps}:{},manifest:i}),o=new Kn(e.config,a),c={};if(e.config.packs.bp){let t=r!==void 0;e.config.manifestFormat===2&&r?.format_version===3&&(e.logger?.warn??console.warn)(`Warning: config manifestFormat is 2, but existing manifest uses format_version 3. format_version 2 does not support string versions; any string versions in the existing manifest will be preserved as-is.`);let l=o.buildBp(r),u=a.getDependencyDiagnostics().map(e=>({module_name:e.name,specifier:e.specifier,version:e.version,source:e.source,...i[e.name]===void 0?{}:{previous:i[e.name]}}));e.dryRun||await Re.write(n,l,`bp`),Xn(u,e.logger),c.bpManifest={path:B(s.relative(e.cwd,n)),updated:!0,existed:t,dependencies:u}}if(e.config.packs.rp){let t=Ht(e.cwd,e.config),n=await Re.read(t),r=n!==void 0,i=o.buildRp(n);e.dryRun||await Re.write(t,i,`rp`),c.rpManifest={path:B(s.relative(e.cwd,t)),updated:!0,existed:r}}return c}function Xn(e,t){if(t)for(let n of e){let e=Jn.cyan(n.module_name);n.previous!==void 0&&n.previous!==n.version?t.info(`manifest ${e}: ${n.previous} ${Jn.dim(`->`)} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`):n.source===`manifest`?t.info(`manifest ${e} ${n.version} ${Jn.dim(`kept from manifest`)} (specifier ${JSON.stringify(n.specifier)}) — run \`bepack install\` to refresh`):t.verbose(`manifest ${e} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`)}}function Zn(e,t){let n={};for(let r of e?.dependencies??[])`module_name`in r&&typeof r.module_name==`string`&&typeof r.version==`string`&&t[r.module_name]?.manifest&&r.version!==`stable`&&(n[r.module_name]=r.version);return n}function Qn(e){if(e==null||e===``)return`hook ran`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function $n(e,t){let n={dist:Ut(e,t)};if(t.packs.bp&&(n.bpRoot=Mt(e,t),n.bpManifest=Vt(e,t),Pt(t))){let r=U(e,t);r&&(n.srcEntry=r);let i=It(e,t);i&&(n.scriptOutFile=i);let a=Ft(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=Nt(e,t),n.rpManifest=Ht(e,t)),n}async function G(e,t,n,r,i,a={}){let o=r.hooks[e];if(o)try{let s=await o({command:t,cwd:n,...a.mode===void 0?{}:{mode:a.mode},target:r.target,dryRun:!!a.dryRun,config:r,paths:$n(n,r),logger:i});i.hook(String(e),Qn(s))}catch(t){throw new F(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function er(e){let{command:t,logger:n,mode:r,...i}=e,a={...r===void 0?{}:{mode:r},dryRun:!!i.dryRun};await G(`beforeManifest`,t,i.cwd,i.config,n,a);let o=await Yn({...i,logger:n});return await G(`afterManifest`,t,i.cwd,i.config,n,a),o}function tr(e){let t=[],n={};for(let[r,i]of Object.entries(e)){if(r.toLowerCase()===`npm_config_allow_scripts`){t.push(r);continue}n[r]=i}return{env:n,removed:t}}var nr=class{cwd;registry;logger;constructor(e,t,n){this.cwd=e,this.registry=t,this.logger=n}async detect(e){if(e!==`auto`)return e;let t=s.join(this.cwd,`package.json`);if(await P(t)){let e=(await Te(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await P(s.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await P(s.join(this.cwd,`yarn.lock`))?`yarn`:await P(s.join(this.cwd,`bun.lock`))||await P(s.join(this.cwd,`bun.lockb`))?`bun`:`npm`}async install(e){let{command:t,args:n}=this.commandForPlatform(e,this.installArgs(e)),{env:r,removed:i}=tr(process.env);return i.length>0&&this.logger?.warn(`Ignoring inherited ${i.join(`, `)}: npm rejects --allow-scripts for project-scoped installs. Declare allowed packages in package.json "allowScripts" or in .npmrc instead.`),await new Promise((i,a)=>{let o;try{o=m(t,n,{cwd:this.cwd,stdio:`inherit`,env:r})}catch(t){a(new F(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t instanceof Error?t.message:String(t)}}));return}o.on(`error`,t=>a(new F(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t.message}}))),o.on(`exit`,t=>{t&&t!==0?a(new F(`PACKAGE_MANAGER_FAILED`,`${e} install failed.`,{details:{manager:e,registry:this.registry,exitCode:t}})):i(t??0)})})}commandForPlatform(e,t){return process.platform===`win32`?{command:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,e,...t]}:{command:e,args:t}}installArgs(e){let t=[`install`];return this.registry&&(e===`npm`||e===`pnpm`||e===`bun`||e===`yarn`)&&t.push(`--registry`,this.registry),t}};async function rr(e){let t=new L({...e,silent:e.silent||e.json}),n={target:e.target};(e.registry||e.pm||e.saveTo||e.skipPm||e.skipManifest||e.skipPackageJson)&&(n.install={...e.registry?{registry:e.registry}:{},...e.pm?{packageManager:e.pm}:{},...e.saveTo?{saveTo:e.saveTo}:{},...e.skipPm?{runPackageManager:!1}:{},...e.skipManifest?{updateManifest:!1}:{},...e.skipPackageJson?{updatePackageJson:!1}:{}});let{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await G(`beforeInstall`,`install`,r,i,t,{dryRun:!!e.dryRun});let a=await new Hn(i,t).resolveAll(),o=Object.fromEntries(Object.entries(a).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion])),s={};i.install.updatePackageJson&&(s.packageJson=await Un(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await er({cwd:r,config:i,command:`install`,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new nr(r,i.install.registry,t),l=await c.detect(i.install.packageManager),u={ran:!1,manager:l,exitCode:null};return!e.dryRun&&i.install.runPackageManager&&(t.progress(`Install`,`running ${l} install with registry ${i.install.registry}`),u={ran:!0,manager:l,exitCode:await c.install(l)}),await G(`afterInstall`,`install`,r,i,t,{dryRun:!!e.dryRun}),t.success(`Install`,`done`),{ok:!0,command:`install`,target:i.target,packageManager:l,resolved:a,files:s,packageInstall:u}}async function ir(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}}),i=await er({cwd:n,config:r,command:`manifest`,dryRun:e.dryRun,logger:t});return t.success(`Manifest`,e.dryRun?`dry-run complete`:`updated manifest.json`),{ok:!0,command:`manifest`,target:r.target,files:i}}const ar=10485760;async function or(e,t={}){let n=mr(t.command),r=t.tsconfigPath??`tsconfig.json`,i=s.resolve(e,r),a=await P(i),o=en(t.command,t.args??[],n?{tsconfigPath:i,incremental:!!t.incremental,useNpx:!!t.useNpx,...t.tsBuildInfoFile?{tsBuildInfoFile:t.tsBuildInfoFile}:{}}:{});if(!a){if(n)throw new F(`TYPECHECK_FAILED`,`TypeScript config not found: ${r}. Create it or run build with --skip-typecheck.`,{details:{path:r,command:o.label}});t.warn?.(`TypeScript config not found: ${r} — running \`${o.label}\` anyway.`)}t.incremental&&t.tsBuildInfoFile&&n&&await _(s.dirname(t.tsBuildInfoFile),{recursive:!0});let c=nn(o),l=await dr(o.command,e);if(!l)throw new F(`TYPECHECK_FAILED`,`Cannot find ${o.command}.`,{details:{command:c,label:o.label},suggestions:pr(o)});let u=process.platform===`win32`&&/\.(cmd|bat)$/i.test(l),d=u?sr(l,o.args):l,f=u?[]:o.args,p;try{p=m(d,f,{cwd:e,windowsHide:!0,shell:u,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw new F(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e instanceof Error?e.message:String(e)},suggestions:pr(o)})}return await new Promise((e,n)=>{let r=``,i=``,a=0,s=e=>{let t=Buffer.isBuffer(e)?e:Buffer.from(String(e)),n=ar-a;return n<=0?``:t.length<=n?(a+=t.length,t.toString(`utf8`)):(a=ar,t.subarray(0,n).toString(`utf8`))};p.stdout?.on(`data`,e=>{r+=s(e),t.quiet||process.stdout.write(e)}),p.stderr?.on(`data`,e=>{i+=s(e),t.quiet||process.stderr.write(e)}),p.on(`error`,e=>{n(new F(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e.message},suggestions:pr(o)}))}),p.on(`close`,t=>{if(t===0){e();return}let a=[r.trim(),i.trim()].filter(Boolean).join(`
|
|
10
|
-
`),s=ur(a);n(new F(`TYPECHECK_FAILED`,s?`Cannot find ${o.command}.`:`${c} failed.`,{details:{command:c,label:o.label,exitCode:typeof t==`number`?t:null,...a?{diagnostics:a}:{}},...s?{suggestions:pr(o)}:{}}))})}),{...o,commandLine:c}}function sr(e,t){let n=process.platform===`win32`?cr:lr;return[e,...t].map(n).join(` `)}function cr(e){if(e===``)return`""`;if(!/[\s"&|<>^()!,;=]/.test(e))return e.replace(/%/g,`^%`);let t=`"`,n=0;for(let r of e){if(r===`\\`){n+=1;continue}if(r===`%`){t+=`\\`.repeat(n*2)+`"^%"`,n=0;continue}if(r===`"`){t+=`\\`.repeat(n*2+1)+`"`,n=0;continue}t+=`\\`.repeat(n)+r,n=0}return t+=`\\`.repeat(n*2)+`"`,t}function lr(e){return e===``?`''`:/[\s"'\\$`!*?[\]{}();&|<>~#]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function ur(e){return e.includes(`ENOENT`)||e.includes(`is not recognized`)||e.includes(`不是内部或外部命令`)||e.includes(`command not found`)}async function dr(e,t){let n=e.includes(`/`)||e.includes(`\\`);if(s.isAbsolute(e)||n){let n=s.resolve(t,e);return await fr(n)?n:void 0}let r=process.env.PATH??``,i=process.platform===`win32`?(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).filter(Boolean):[``];for(let n of r.split(s.delimiter)){let r=n?s.resolve(t,n):t,a=s.join(r,e);if(await fr(a))return a;for(let t of i){if(t&&s.extname(e))continue;let n=s.join(r,e+t);if(await fr(n))return n}}}async function fr(t){try{return await g(t,e.X_OK),!0}catch{return!1}}function pr(e){return[`Install the checker so \`${e.command}\` is available, or point packs.bp.compile.typecheck.command at a command you do have (for example "bun check", "tsc-rs --noEmit", "npx tsc --noEmit").`,`Run with --skip-typecheck to build without checking (the bundle is still produced).`]}function mr(e){return typeof e!=`string`||e.trim()===``}const hr=/* @__PURE__ */ new Set([`plugins`]),gr=/* @__PURE__ */ new Set([`external`]),_r=/* @__PURE__ */ new Set([`output`,`resolve`,`transform`,`experimental`,`checks`,`optimization`,`watch`,`moduleTypes`]),vr=[{key:`file`,suggestion:`The output file is derived from packs.bp.compile.entry and scriptOutputDir.`},{key:`dir`,suggestion:`The output directory is derived from packs.bp.compile.scriptOutputDir.`},{key:`format`,suggestion:`Minecraft Script API modules must be ESM, so BePack always writes format: "esm".`},{key:`preserveModules`,suggestion:`Use packs.bp.compile.preserveModules instead.`},{key:`preserveModulesRoot`,suggestion:`The modules root is always the entry file directory.`},{key:`entryFileNames`,suggestion:"Manifest script entries assume one `.js` file per source module."}];function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yr(e){return e==null||e===!1?[]:Array.isArray(e)?e:[e]}function br(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function xr(e,t,n){return typeof e!=`string`||typeof t!=`string`?!1:br(s.resolve(n,e),s.resolve(n,t))}function Sr(e){if(e instanceof Error){let t=e.cause;return t instanceof Error&&t.message?t.message:e.message}return String(e)}function Cr(e,t){if(typeof e==`function`||typeof t==`function`)return t;let n=[],r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let a of[...yr(e),...yr(t)])if(typeof a==`string`){if(r.has(a))continue;r.add(a),n.push(a)}else if(a instanceof RegExp){let e=`${a.source}/${a.flags}`;if(i.has(e))continue;i.add(e),n.push(a)}return n}function wr(e,t){if(!K(t))return t;let n=K(e)?e:{},r={...n,...t},i=K(n.define)?n.define:{};return K(t.define)&&(r.define={...i,...t.define}),r}function Tr(e,t){if(!t)return{...e};let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=hr.has(e)?[...yr(t),...yr(r)]:gr.has(e)?Cr(t,r):e===`transform`?wr(t,r):_r.has(e)&&K(t)&&K(r)?{...t,...r}:r}return n}function Er(e){if(!e.packs.bp?.compile)return[];let t=[...e.packs.bp.compile.external],n=new Set(t.filter(e=>typeof e==`string`));for(let[r,i]of Object.entries(Ln(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function Dr(e){let t=e.packs.bp?.compile;if(!t)throw new F(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);return t}function Or(e,t){let n=Dr(t),r=U(e,t);if(!r)throw new F(`BUILD_FAILED`,`packs.bp.compile.entry could not be resolved.`);return{input:r,external:Er(t),plugins:Jt(t),...Zt(n.define)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:n.preserveModules?`none`:`simple`}}}function kr(e,t){let n=Dr(t),r=U(e,t),i=Ft(e,t),a=It(e,t);if(!r||!i||!a)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);return n.preserveModules?{dir:i,format:`esm`,preserveModules:!0,preserveModulesRoot:s.dirname(r),entryFileNames:`[name].js`,minify:n.minify}:{file:a,format:`esm`,minify:n.minify}}function Ar(e,t){if(typeof e==`string`)return[s.resolve(t,e)];if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e.map(e=>s.resolve(t,e)).sort():void 0;if(K(e)){let n=Object.values(e);return n.every(e=>typeof e==`string`)?n.map(e=>s.resolve(t,e)).sort():void 0}}function jr(e,t,n){if(e.input===void 0)return;let r=Ar(e.input,n),i=Ar(t.input,n);if(!(r!==void 0&&i!==void 0&&r.length===i.length&&r.every((e,t)=>br(e,i[t]))))throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "input" — the bundle entry is managed by BePack.`,{details:{input:e.input,expected:t.input},suggestions:[`Set the entry file via packs.bp.compile.entry instead.`]})}function Mr(e,t,n){for(let{key:r,suggestion:i}of vr){let a=e[r];if(a===void 0)continue;let o=t[r];if(!(r===`file`||r===`dir`||r===`preserveModulesRoot`?xr(a,o,n):Object.is(a,o)||r===`preserveModules`&&o===void 0&&a===!1))throw new F(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "output.${r}" — it is managed by BePack.`,{details:{key:r,value:a,expected:o},suggestions:[i]})}}function Nr(e,t){if(K(e)&&e.__esModule===!0&&`default`in e)return Nr(e.default,t);if(typeof e==`function`)return e;if(Array.isArray(e)){if(e.length===0)throw new F(`CONFIG_INVALID`,`rolldown config file exports an empty array: ${t}`,{details:{file:t},suggestions:[`Export a single rolldown options object.`]});if(e.length>1)throw new F(`CONFIG_INVALID`,`rolldown config file exports ${e.length} configs, but BePack builds a single behavior pack per run: ${t}`,{details:{file:t,count:e.length},suggestions:[`Export a single rolldown options object.`]});if(!K(e[0]))throw new F(`CONFIG_INVALID`,`rolldown config file must export an options object or function: ${t}`);return e[0]}if(K(e))return e;throw new F(`CONFIG_INVALID`,`rolldown config file must default-export a rolldown options object, a function, or a single-element array: ${t}`)}async function Pr(e){if(!await P(e))throw new F(`CONFIG_INVALID`,`rolldown config file not found: ${e}`,{details:{path:e},suggestions:[`Check the path in packs.bp.compile.rolldownConfig or --rolldown-config.`]});let t;try{t=await b(e)}catch(t){throw new F(`CONFIG_INVALID`,`Failed to load rolldown config file "${e}": ${Sr(t)}`)}return Nr(t,e)}async function Fr(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new F(`BUILD_FAILED`,`compile.rolldown customization function failed: ${Sr(e)}`)}if(r==null)return t;if(!K(r))throw new F(`CONFIG_INVALID`,`compile.rolldown customization function must return a rolldown options object (or nothing).`);return Tr(t,r)}async function Ir(e){let{cwd:t,config:n}=e,r=Dr(n),i=V(t,n),a=U(t,n),o=Ft(t,n),c=It(t,n);if(!a||!o||!c)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);let l=Or(t,n),u=kr(t,n),d={command:e.command??`build`,...e.mode===void 0?{}:{mode:e.mode},target:n.target,entry:a,outDir:o,outFile:c,preserveModules:r.preserveModules},f=r.rolldown,p=e.configPath??r.rolldownConfig,m=p?await Pr(s.resolve(i,p)):void 0,h=Tr(l,typeof f==`function`?void 0:f);h=Tr(h,typeof m==`function`?void 0:m),typeof f==`function`&&(h=await Fr(f,h,d)),typeof m==`function`&&(h=await Fr(m,h,d));let{output:g,input:_,...v}=h;if(Array.isArray(g))throw new F(`CONFIG_INVALID`,"packs.bp.compile.rolldown cannot declare multiple outputs (an `output` array) — BePack writes exactly one output.",{suggestions:["Declare a single `output` object."]});if(g!==void 0&&!K(g))throw new F(`CONFIG_INVALID`,"packs.bp.compile.rolldown `output` must be an object.",{details:{output:g}});jr({input:_},l,i);let y=Tr(u,g);return Mr(y,u,i),{inputOptions:{...v,input:l.input},outputOptions:y}}function Lr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(2)} MB`}function Rr(e,n){let r=s.resolve(e),i=s.resolve(n),a=s.relative(r,i);if(!a||a.startsWith(`..`)||s.isAbsolute(a))return;try{if(t(r).isSymbolicLink())throw new F(`BUILD_FAILED`,`Safety check failed: BP root is a symbolic link or junction: "${r}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e instanceof F)throw e;if(e?.code===`ENOENT`)return;throw e}let o=r;for(let e of a.split(s.sep)){o=s.join(o,e);try{if(t(o).isSymbolicLink())throw new F(`BUILD_FAILED`,`Safety check failed: script output path contains a symbolic link: "${o}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e.code===`ENOENT`)break;throw e}}}function zr(e,t,n){let r=s.resolve(e),i=s.resolve(t);if(Lt(r,i)||Lt(i,r))throw new F(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function Br(e,t,n,r){let i=V(e,t),a=Mt(e,t),o=s.join(a,`manifest.json`),c=[s.join(i,`.git`),s.join(a,`.git`)];for(let e of c)zr(r,e,`.git metadata`);if(t.packs.rp){let e=H(i,t,`rp`);s.resolve(e)!==s.resolve(a)&&zr(r,e,`RP root`)}zr(r,o,`BP manifest`);let l=s.dirname(n),u=s.relative(a,l);zt(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!s.isAbsolute(u)?[l]:[]),Rr(a,r)}async function Vr(e,t,n,r={}){if(!Pt(t))throw new F(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let i=U(e,t),a=Ft(e,t),o=It(e,t);if(!i||!a||!o)throw new F(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);try{let{inputOptions:o,outputOptions:s}=await Ir({cwd:e,config:t,...r.command===void 0?{}:{command:r.command},...r.mode===void 0?{}:{mode:r.mode},...r.rolldownConfig===void 0?{}:{configPath:r.rolldownConfig}});Br(e,t,i,a),await we(a);let c=await y(o);try{await c.write(s)}finally{await c.close()}await Hr(a,n)}catch(e){throw e instanceof F?e:new F(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function Hr(e,t){let n=[];async function r(t){let i=await h.readdir(t,{withFileTypes:!0});for(let a of i){let i=s.join(t,a.name);if(a.isDirectory())await r(i);else if(a.isFile()&&a.name.endsWith(`.js`)){let t=await h.stat(i);n.push({path:s.relative(e,i),size:t.size})}}}if(await r(e),n.length===0)return;n.sort((e,t)=>t.size-e.size);let i=n.reduce((e,t)=>e+t.size,0);t?.rolldown(n.length===1?`${n[0].path} (${Lr(n[0].size)})`:`${n.length} files, total ${Lr(i)}`)}async function Ur(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function Wr(e){let t=Date.now(),n=e.config.build.timing,r=V(e.cwd,e.config),i=Pt(e.config),a=e.command??`build`,o={...e.mode===void 0?{}:{mode:e.mode},dryRun:!!e.dryRun};await Ur(`manifest`,()=>er({cwd:e.cwd,config:e.config,command:a,logger:e.logger,dryRun:!!e.dryRun,...e.mode===void 0?{}:{mode:e.mode},...e.resolvedDeps?{resolvedDeps:e.resolvedDeps}:{}}),e.logger,n);let c=[];e.config.packs.bp&&c.push(`bp`),e.config.packs.rp&&c.push(`rp`),e.logger.manifest(`manifest.json updated (${c.join(`, `)})`),await G(`beforeBuild`,a,e.cwd,e.config,e.logger,o);let l=!1,u;if(i&&!e.dryRun&&e.typecheck!==!1){let t=e.config.packs.bp.compile,i=e.cache?s.resolve(r,t.cache.file):void 0,a=e.typecheckCommand??(e.useNpx?void 0:t.typecheckCommand),o=e.typecheckCommand===void 0&&(!!e.useNpx||a===void 0&&t.useNpx),c=await Ur(`typecheck`,()=>or(r,{quiet:!!e.quiet,...a===void 0?{}:{command:a},useNpx:o,args:e.typecheckCommand!==void 0||e.useNpx?[]:t.typecheckArgs,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{},warn:t=>e.logger.warn(t)}),e.logger,n);l=!0,u=c.commandLine,e.logger.typescript(`typecheck complete (${c.commandLine})`)}i&&!e.dryRun&&(await Ur(`rolldown`,()=>Vr(e.cwd,e.config,e.logger,{...e.command===void 0?{}:{command:e.command},...e.mode===void 0?{}:{mode:e.mode},...e.rolldownConfig===void 0?{}:{rolldownConfig:e.rolldownConfig}}),e.logger,n),e.logger.rolldown(e.config.packs.bp.compile.preserveModules?`preserve modules build complete`:`bundle complete`)),await G(`afterBuild`,a,e.cwd,e.config,e.logger,o);let d=Date.now()-t;return{script:i?B(It(e.cwd,e.config)):void 0,compiled:i,typecheck:l,...u?{typecheckCommand:u}:{},durationMs:d}}async function Gr(e,t=``){let r={},i=await n.readdir(e,{withFileTypes:!0});for(let a of i){let i=s.join(e,a.name),o=t?`${t}/${a.name}`:a.name;a.isDirectory()?Object.assign(r,await Gr(i,o)):r[o]=new Uint8Array(await n.readFile(i))}return r}async function Kr(e,t){let r={};for(let i of t){let t=s.join(e,i);try{(await n.stat(t)).isDirectory()?Object.assign(r,await Gr(t,i)):r[i]=new Uint8Array(await n.readFile(t))}catch{}}return r}async function qr(e,t){return t?await t(e):e}function Jr(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}/${r}`]=i;return n}function Yr(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function Xr(e,t){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0});for(let[r,i]of Object.entries(t)){let t=s.join(e,r);await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,i)}}var Zr=te((()=>{}));Zr();const Qr=new TextEncoder;new TextDecoder;function $r(e){let t=16+e.length*256,n=0,r=[];for(let t of e){let e=Qr.encode(t.name);if(e.length===0)throw new F(`PACK_FAILED`,`brarchive entry names must not be empty.`);if(e.length>247)throw new F(`PACK_FAILED`,`brarchive entry name is too long (max 247 bytes): ${t.name}`,{details:{name:t.name,bytes:e.length}});r.push(e),n+=t.data.length}let i=new Uint8Array(t+n),a=new DataView(i.buffer);a.setBigUint64(0,9018218223661903910n,!1),a.setUint32(8,e.length,!0),a.setUint32(12,1,!0);let o=0;return e.forEach((e,n)=>{let s=16+n*256,c=r[n];a.setUint8(s,c.length),i.set(c,s+1),a.setUint32(s+248,o,!0),a.setUint32(s+252,e.data.length,!0),i.set(e.data,t+o),o+=e.data.length}),i}const ei=[`functions`,`loot_tables`,`structures`,`texts`],ti=[`font`,`materials`,`sounds`,`texts`,`textures`],ni=[1,26,40],ri=ni.join(`.`),ii=new TextEncoder,ai=new TextDecoder,oi=new TextDecoder(`utf-16le`),si=new TextDecoder(`utf-16be`);function ci(e){if(e.length>=2){if(e[0]===255&&e[1]===254)return oi.decode(e.subarray(2));if(e[0]===254&&e[1]===255)return si.decode(e.subarray(2))}return ai.decode(e)}function li(e){return e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255)}function ui(e){return e.startsWith(``)?e.slice(1):e}function di(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function fi(e){if(typeof e==`string`){let t=e.split(`.`).map(e=>Number.parseInt(e,10));return t.length>=3&&t.slice(0,3).every(e=>Number.isInteger(e))?[t[0],t[1],t[2]]:void 0}if(Array.isArray(e)&&e.length>=3){let t=e.slice(0,3);if(t.every(e=>typeof e==`number`&&Number.isInteger(e)))return t}}function pi(e,t){for(let n=0;n<3;n++){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return 0}function mi(e){if(e)try{return di(JSON.parse(ui(ci(e))))}catch{return}}function hi(e){return fi(di(e?.header)?.min_engine_version)}function gi(e){let t=e?.modules;return Array.isArray(t)?t.some(e=>di(e)?.type===`resources`):!1}function _i(e,t,n){if(t.allowUnsupportedTarget)return;let r=hi(e);if(r&&pi(r,ni)>=0)return;let i=r?r.join(`.`):`(not declared)`;n?.warn(`pack optimization: header.min_engine_version is ${i}, below ${ri}. The archives still load on 1.26.40+, but older clients cannot read __brarchive/ and will show missing content. Set allowUnsupportedTarget: true to silence this warning.`)}function vi(e,t,n){if(!e.toLowerCase().endsWith(`.json`))return t;try{let e=JSON.parse(ui(ci(t)));return ii.encode(JSON.stringify(e))}catch(r){let i=r instanceof Error?r.message:String(r),a=li(t)?` (UTF-16)`:``;return n?.warn(`pack optimization: could not minify ${e}${a}, storing it unchanged. ${i}. Fix the JSON to have it minified.`),t}}function yi(e,t){if(!e)throw new F(`PACK_FAILED`,`Pack optimization needs a manifest.json to write header.pack_optimization_version into.`);let n;try{let t=di(JSON.parse(ui(ci(e))));if(!t)throw Error(`manifest is not an object`);n=t}catch{throw new F(`PACK_FAILED`,`Cannot write header.pack_optimization_version: the pack's manifest.json is not valid JSON.`)}let r={...di(n.header)??{}};return r.pack_optimization_version=t,n.header=r,ii.encode(JSON.stringify(n))}function bi(e,t,n,r){let i=e[`manifest.json`]??r,a=mi(i);_i(a,t,n);let o=new Set(t.exclude),s=t.keepLoose===!1?/* @__PURE__ */ new Set:/* @__PURE__ */ new Set([...gi(a)?ti:ei,...t.keepLoose]),c=/* @__PURE__ */ new Map,l={},u={},d=0,f=0;for(let r of Object.keys(e).sort()){let i=e[r],a=r.split(`/`),p=a[0];if(a.length<2||p===`__brarchive`||o.has(p)){l[r]=i;continue}let m=a.slice(0,-1).join(`/`),h=a[a.length-1],g=c.get(m)??[],_=t.keepLooseFiles||s.has(p);s.has(p)&&!t.keepLooseFiles?(g.push({name:h,data:/* @__PURE__ */ new Uint8Array}),u[r]=i,f++):(g.push({name:h,data:t.minifyJson?vi(h,i,n):i}),d++,_&&(u[r]=i)),c.set(m,g)}let p={...l,...u};for(let e of[...c.keys()].sort())p[`__brarchive/${e}.brarchive`]=$r(c.get(e));p[`manifest.json`]=yi(i,t.packOptimizationVersion);let m=Object.keys(u).length,h=f>0?`, ${f} name-stub${f===1?``:`s`}`:``;return n?.pack(`optimized into ${c.size} archive${c.size===1?``:`s`} (${d} file${d===1?``:`s`} archived${h}, ${m} kept loose)`),Yr(p)}function xi(e,t,n){return r=>bi(r,e,t,n)}const Si={win:()=>({type:`gameRoot`,path:s.join(`C:/Users`,d.userInfo().username,`AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang`)}),winold:()=>{let e=process.env.LOCALAPPDATA;if(!e)throw new F(`COPY_TARGET_NOT_FOUND`,`%LOCALAPPDATA% is required for winold copy target.`);return{type:`gameRoot`,path:s.join(e,`Packages`,`Microsoft.MinecraftUWP_8wekyb3d8bbwe`,`LocalState`,`games`,`com.mojang`)}}};function Ci(e,t){return{type:`custom`,bp:s.join(t.path,`development_behavior_packs`),...e.packs.rp?{rp:s.join(t.path,`development_resource_packs`)}:{}}}function wi(e,t){let n=t??e.copy.defaultTarget;if(!n)throw new F(`COPY_TARGET_NOT_FOUND`,`No copy target configured. Set copy.defaultTarget or copy.targets in bepack.config.ts, or pass --target.`,{suggestions:[`Add copy.defaultTarget to your config file.`,`Or set build.copy / dev.copy to a target name instead of true.`,`Built-in targets: win, winold.`]});let r=e.copy.targets[n]??Si[n]?.();if(!r)throw new F(`COPY_TARGET_NOT_FOUND`,`Copy target not found: ${n}`,{details:{target:n}});let i=e.copy.targets[n]?.name,a=e.copy.name,o=e=>typeof e==`string`?{bp:e,rp:e}:e??{},s=o(i),c=o(a),l={},u=s.bp??c.bp,d=s.rp??c.rp;return u&&(l.bp=u),d&&(l.rp=d),r.type===`gameRoot`?{name:n,target:Ci(e,r),names:l}:{name:n,target:r,names:l}}const Ti=/* @__PURE__ */ new Set([`node_modules`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lock`,`bun.lockb`,`tsconfig.json`,...Ct]);function Ei(e,t,n){let r=H(V(e,t),t,n);if(!r)return[];let i=U(e,t),a=[Ut(e,t),i?s.dirname(i):void 0],o=[];for(let e of a){if(!e)continue;let t=s.relative(r,e);if(!t||t.startsWith(`..`)||s.isAbsolute(t))continue;let n=t.split(s.sep)[0];n&&o.push(n)}return o}async function Di(e,t,r=[]){let i;try{i=await n.readdir(e,{withFileTypes:!0})}catch{return[]}let a=new Set(t);return i.map(e=>e.name).filter(e=>!a.has(e)).filter(e=>!e.startsWith(`.`)&&!Ti.has(e)).filter(e=>!r.includes(e)).sort((e,t)=>e.localeCompare(t))}function Oi(e){return e===`bp`?`packs.bp.include`:`packs.rp.include`}async function ki(e){let{logger:t,packType:n,root:r,items:i,action:a}=e;if(!t)return;let o=await Di(r,i,e.ignore??[]);if(o.length===0)return;let s=e.limit??8,c=o.slice(0,s).join(`, `),l=o.length>s?`, +${o.length-s} more`:``,u=n===`bp`?`behavior pack`:`resource pack`;t.warn(`${u} ${a} only includes ${i.length} configured item(s); ${o.length} entr${o.length===1?`y`:`ies`} in "${Ai(r,e.cwd)}" ${o.length===1?`is`:`are`} skipped: ${c}${l}. Add them to ${Oi(n)} to include them.`)}function Ai(e,t){if(!t)return e;let n=s.relative(t,e).replace(/\\/g,`/`);return n&&!n.startsWith(`..`)&&!s.isAbsolute(n)?n:e}Zr();const ji=Oe.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Mi(e,t,r){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(t,{recursive:!0});for(let i of r){let r=s.join(e,i),a=s.join(t,i);try{await n.cp(r,a,{recursive:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}function Ni(e,t){let n=s.resolve(e),r=s.resolve(t);if(Lt(n,r)||Lt(r,n))throw new F(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function Pi(e,t){let n=s.resolve(e),r=s.resolve(n,t);if(r===n||!Lt(n,r))throw new F(`COPY_FAILED`,`Copy folder name "${t}" must resolve to a directory inside "${e}".`,{details:{targetDir:n,folderName:t,destination:r}});return r}async function Fi(e,t){if(!await P(e))throw new F(`COPY_FAILED`,`Copy target directory does not exist: ${e}`,{details:{dir:e,label:t},suggestions:[`Create the target directory: mkdir -p "${e}"`,`Or check the copy target path in bepack.config.ts.`]})}function Ii(e,t){if(t===`bp`)return Bt(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...At,...i]:[]}async function Li(e){try{return new Uint8Array(await n.readFile(s.join(e,`manifest.json`)))}catch{return}}async function Ri(e,t,n,r,i,a,o,s,c){let l=Ii(i,e),u=Pi(n,r);Ni(t,u);let d=e===`bp`||l.length>0;d&&await ki({...s?{logger:s}:{},packType:e,root:t,items:l,action:`copy`,cwd:o,ignore:Ei(o,i,e)});let f=c===void 0?i.copy.optimize:c?i.copy.optimize??Tt:void 0;if(!a){if(f){let e=d?await Kr(t,l):await Gr(t),n=xi(f,s,await Li(t));try{await Xr(u,await qr(e,n))}catch(e){throw e instanceof F?new F(e.code===`PACK_FAILED`?`COPY_FAILED`:e.code,e.message,{...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions}}):e}}else d?await Mi(t,u,l):await De(t,u)}let p=l.length>0?l.length:void 0;return s?.copy(`${a?`would copy`:`copied`} ${e}${p?` (${p} items)`:``} -> ${ji.gray(u)}`),u}async function zi(e,t,n,r=!1,i,a={}){let{name:o,target:s,names:c}=wi(t,n),l=[],u=V(e,t),d=Ot(t);for(let n of d){let o;if(o=n.type===`bp`?s.bp:s.rp,!o)continue;await Fi(o,n.type);let d=c[n.type]??n.name,f=H(u,t,n.type),p=await Ri(n.type,f,o,d,t,r,e,i,a.optimize);l.push(p)}return{target:o,copied:l}}async function Bi(e){let{command:t,cwd:n,config:r,logger:i,targetName:a,mode:o,optimize:s}=e,c=!!e.dryRun,l={...o===void 0?{}:{mode:o},dryRun:c};await G(`beforeCopy`,t,n,r,i,l);let u=await zi(n,r,a,c,i,s===void 0?{}:{optimize:s});return await G(`afterCopy`,t,n,r,i,l),u}function Vi(e,t){return Ta(e,t||{},0,0)}function Hi(e,t){if(t){for(var n=new q(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Oa)return Oa.encode(e);for(var i=e.length,a=new q(e.length+(e.length>>1)),o=0,s=function(e){a[o++]=e},r=0;r<i;++r){if(o+5>a.length){var c=new q(o+8+(i-r<<1));c.set(a),a=c}var l=e.charCodeAt(r);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,s(240|l>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|l&63)):(s(224|l>>12),s(128|l>>6&63),s(128|l&63))}return la(a,0,o)}function Ui(e,t){t||={};var n={},r=[];Da(e,``,n,t);var i=0,a=0;for(var o in n){var s=n[o],c=s[0],l=s[1],u=l.level==0?0:8,d=Hi(o),f=d.length,p=l.comment,m=p&&Hi(p),h=m&&m.length,g=Aa(l.extra);f>65535&&da(11);var _=u?Vi(c,l):c,v=_.length,y=wa();y.p(c),r.push(Ea(l,{size:c.length,crc:y.d(),c:_,f:d,m,u:f!=o.length||m&&p.length!=h,o:i,compression:u})),i+=30+f+g+v,a+=76+2*(f+g)+(h||0)+v}for(var b=new q(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];ja(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+Aa(d.extra);b.set(d.c,d.o+w),ja(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return Ma(b,i,r.length,S,x),b}var Wi,Gi,q,J,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,Y,na,ra,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,X,Da,Oa,ka,Aa,ja,Ma,Na=te((()=>{Wi=x(`/`);try{Gi=Wi("worker_threads"),Gi.Worker,Gi.isMarkedAsUntransferable}catch{}for(q=Uint8Array,J=Uint16Array,Ki=Int32Array,qi=new q([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ji=new q([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Yi=new q([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xi=function(e,t){for(var n=new J(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ki(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Gi=Xi(qi,2),Zi=Gi.b,Qi=Gi.r,Zi[28]=258,Qi[258]=28,$i=Xi(Ji,0),$i.b,ea=$i.r,ta=new J(32768),Y=0;Y<32768;++Y)na=(Y&43690)>>1|(Y&21845)<<1,na=(na&52428)>>2|(na&13107)<<2,na=(na&61680)>>4|(na&3855)<<4,ta[Y]=((na&65280)>>8|(na&255)<<8)>>1;for(ra=(function(e,t,n){for(var r=e.length,i=0,a=new J(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new J(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new J(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[ta[d]>>c]=l}else for(s=new J(r),i=0;i<r;++i)e[i]&&(s[i]=ta[o[e[i]-1]++]>>15-e[i]);return s}),ia=new q(288),Y=0;Y<144;++Y)ia[Y]=8;for(Y=144;Y<256;++Y)ia[Y]=9;for(Y=256;Y<280;++Y)ia[Y]=7;for(Y=280;Y<288;++Y)ia[Y]=8;for(aa=new q(32),Y=0;Y<32;++Y)aa[Y]=5;oa=/*#__PURE__*/ ra(ia,9,0),sa=/*#__PURE__*/ ra(aa,5,0),ca=function(e){return(e+7)/8|0},la=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new q(e.subarray(t,n))},ua=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],da=function(e,t,n){var r=Error(t||ua[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,da),!n)throw r;return r},fa=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},pa=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},ma=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:xa,l:0};if(i==1){var o=new q(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new J(f+1),m=ha(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new q(p),l:m}},ha=function(e,t,n){return e.s==-1?Math.max(ha(e.l,t,n+1),ha(e.r,t,n+1)):t[e.s]=n},ga=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new J(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},_a=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},va=function(e,t,n){var r=n.length,i=ca(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},ya=function(e,t,n,r,i,a,o,s,c,l,u){fa(t,u++,n),++i[256];for(var d=ma(i,15),f=d.t,p=d.l,m=ma(a,15),h=m.t,g=m.l,_=ga(f),v=_.c,y=_.n,b=ga(h),x=b.c,S=b.n,C=new J(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=ma(C,7),E=T.t,ee=T.l,D=19;D>4&&!E[Yi[D-1]];--D);var te=l+5<<3,O=_a(i,ia)+_a(a,aa)+o,k=_a(i,f)+_a(a,h)+o+14+3*D+_a(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&te<=O&&te<=k)return va(t,u,e.subarray(c,c+l));var ne,A,j,re;if(fa(t,u,1+(k<O)),u+=2,k<O){ne=ra(f,p,0),A=f,j=ra(h,g,0),re=h;var ie=ra(E,ee,0);fa(t,u,y-257),fa(t,u+5,S-1),fa(t,u+10,D-4),u+=14;for(var w=0;w<D;++w)fa(t,u+3*w,E[Yi[w]]);u+=3*D;for(var M=[v,x],ae=0;ae<2;++ae)for(var oe=M[ae],w=0;w<oe.length;++w){var se=oe[w]&31;fa(t,u,ie[se]),u+=E[se],se>15&&(fa(t,u,oe[w]>>5&127),u+=oe[w]>>12)}}else ne=oa,A=ia,j=sa,re=aa;for(var w=0;w<s;++w){var N=r[w];if(N>255){var se=N>>18&31;pa(t,u,ne[se+257]),u+=A[se+257],se>7&&(fa(t,u,N>>23&31),u+=qi[se]);var ce=N&31;pa(t,u,j[ce]),u+=re[ce],ce>3&&(pa(t,u,N>>5&8191),u+=Ji[ce])}else pa(t,u,ne[N]),u+=A[N]}return pa(t,u,ne[256]),u+A[256]},ba=/*#__PURE__*/ new Ki([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),xa=/*#__PURE__*/ new q(0),Sa=function(e,t,n,r,i,a){var o=a.z||e.length,s=new q(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=ba[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new J(32768),g=a.h||new J(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Ki(25e3),x=new J(288),S=new J(32),C=0,w=0,T=a.i||0,E=0,ee=a.w||0,D=0;T+2<o;++T){var te=y(T),O=T&32767,k=g[te];if(h[O]=k,g[te]=O,ee<=T){var ne=o-T;if((C>7e3||E>24576)&&(ne>423||!l)){u=ya(e,c,0,b,x,S,w,E,D,T-D,u),E=C=w=0,D=T;for(var A=0;A<286;++A)x[A]=0;for(var A=0;A<30;++A)S[A]=0}var j=2,re=0,ie=p,M=O-k&32767;if(ne>2&&te==y(T-M))for(var ae=Math.min(f,ne)-1,oe=Math.min(32767,T),se=Math.min(258,ne);M<=oe&&--ie&&O!=k;){if(e[T+j]==e[T+j-M]){for(var N=0;N<se&&e[T+N]==e[T+N-M];++N);if(N>j){if(j=N,re=M,N>ae)break;for(var ce=Math.min(M,N-2),le=0,A=0;A<ce;++A){var ue=T-M+A&32767,de=ue-h[ue]&32767;de>le&&(le=de,k=ue)}}}O=k,k=h[O],M+=O-k&32767}if(re){b[E++]=268435456|Qi[j]<<18|ea[re];var fe=Qi[j]&31,pe=ea[re]&31;w+=qi[fe]+Ji[pe],++x[257+fe],++S[pe],ee=T+j,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,ee);T<o;++T)b[E++]=e[T],++x[e[T]];u=ya(e,c,l,b,x,S,w,E,D,T-D,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=ee)}else{for(var T=a.w||0;T<o+l;T+=65535){var me=T+65535;me>=o&&(c[u/8|0]=l,me=o),u=va(c,u+1,e.subarray(T,me))}a.i=o}return la(s,0,r+ca(u)+i)},Ca=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),wa=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=Ca[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},Ta=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new q(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Sa(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},Ea=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},X=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},Da=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=Ea(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new q(0),s],Da(a,o,n,r))}},Oa=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,ka=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{ka.decode(xa,{stream:!0})}catch{}Aa=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&da(9),t+=r+4}return t},ja=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=Aa(l);X(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&da(10),X(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(X(e,t,n.crc),X(e,t+4,a<0?-a-2:a),X(e,t+8,n.size)),X(e,t+12,c),X(e,t+14,d),t+=16,o!=null&&(X(e,t,u),X(e,t+6,n.attrs),X(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;X(e,t,+m),X(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},Ma=function(e,t,n,r,i){X(e,t,101010256),X(e,t+8,n),X(e,t+10,n),X(e,t+12,r),X(e,t+16,i)}}));async function Pa(e,t){await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,Ui(Yr(e)))}async function Fa(e,t,n){await Pa(await qr(await Gr(e),n),t)}async function Ia(e,t,n,r){await Pa(await qr(await Kr(e,t),r),n)}async function La(e,t){let n={};for(let t of e){let e=await qr(await Kr(t.source,t.items),t.transform);Object.assign(n,Jr(e,s.basename(s.resolve(t.source))))}await Pa(n,t)}async function Ra(e,t,n){let r={};for(let t of e){let e=await qr(await Kr(t.source,t.items),t.transform);Object.assign(r,Jr(e,s.basename(s.resolve(t.source))))}for(let e of t){let t=await qr(await Gr(e.dir),e.transform);Object.assign(r,Jr(t,s.basename(s.resolve(e.dir))))}await Pa(r,n)}var za=te((()=>{Na(),Zr()})),Ba=/* @__PURE__ */ k({packMcpack:()=>Va});async function Va(e,t,n,r=!1,i){let a=s.join(t,`${n}.mcpack`);return r||await Fa(e,a,i),a}var Ha=te((()=>{za()}));za();function Ua(e,t,n){let r=s.resolve(e),i=s.resolve(t),a=s.relative(i,r);if(a&&!a.startsWith(`..`)&&!s.isAbsolute(a))throw new F(`PACK_FAILED`,`pack output must not be inside ${n} directory.`,{details:{output:r,dir:i},suggestions:[`Set pack.outDir to a path outside ${n}: ${i}`]})}function Wa(e,t,n){let r=s.resolve(e),i=s.resolve(t);for(let e of n){let t=s.resolve(i,e),n=s.relative(t,r);if(n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n))throw new F(`PACK_FAILED`,`pack output must not be included in the BP archive.`,{details:{output:r,includedPath:t},suggestions:[`Set pack.outDir outside the selected BP include path: ${t}`]})}}function Ga(e,t){let n=s.relative(s.resolve(t),s.resolve(e));if(n.startsWith(`..`)||s.isAbsolute(n))throw new F(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:s.resolve(e),dist:s.resolve(t)}})}function Ka(e,t){if(t===`bp`)return{items:Bt(e),selective:!0};let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?{items:[...At,...i],selective:!0}:{items:[],selective:!1}}async function qa(e,t,n={}){let r=V(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=Ut(e,t);if(Ot(t).length===0)throw new F(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let o=n.optimize===void 0?t.pack.optimize:n.optimize?t.pack.optimize??Tt:void 0,c=o?xi(o,n.logger):void 0,l=t.packs.bp?{root:H(r,t,`bp`),config:t}:void 0,u=t.packs.rp?{root:H(r,t,`rp`),config:t}:void 0,d=l?Ka(t,`bp`):void 0;if(l&&d?.selective&&await ki({...n.logger?{logger:n.logger}:{},packType:`bp`,root:l.root,items:d.items,action:`pack`,cwd:e,ignore:Ei(e,t,`bp`)}),u){let r=Ka(t,`rp`);r.selective&&await ki({...n.logger?{logger:n.logger}:{},packType:`rp`,root:u.root,items:r.items,action:`pack`,cwd:e,ignore:Ei(e,t,`rp`)})}if(l&&u){if(!d)throw new F(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcaddon`);if(Ga(e,a),d?.selective&&Wa(e,l.root,d.items),Ua(e,u.root,`RP`),!n.dryRun){let n=Ka(t,`rp`);n.selective?await La([{source:l.root,items:d.items,...c?{transform:c}:{}},{source:u.root,items:n.items,...c?{transform:c}:{}}],e):await Ra([{source:l.root,items:d.items,...c?{transform:c}:{}}],[{dir:u.root,...c?{transform:c}:{}}],e)}return e}if(l){if(!d)throw new F(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcpack`);return Ga(e,a),d?.selective&&Wa(e,l.root,d.items),n.dryRun||await Ia(l.root,d.items,e,c),e}if(u){let e=s.join(a,`${i}.mcpack`);if(Ga(e,a),Ua(e,u.root,`RP`),!n.dryRun){let r=Ka(t,`rp`);if(r.selective)await Ia(u.root,r.items,e,c);else{let{packMcpack:e}=await Promise.resolve().then(()=>(Ha(),Ba));return await e(u.root,a,i,n.dryRun,c)}}return e}throw new F(`PACK_FAILED`,`No packs configured.`)}async function Ja(e,t,n,r={}){let i=Date.now();await G(`beforePack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let a=await qa(e,t,{...r,logger:n});await G(`afterPack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let o=Date.now()-i;return n.done(`pack`,r.dryRun?`dry-run: would pack ${a} (no file written)`:`packed ${a} in ${n.formatDuration(o)}`),{output:a,durationMs:o,dryRun:!!r.dryRun}}async function Ya(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config}),i=e.build===!1||!!e.skipBuild,a=null;if(!i){let i=e.skipTypecheck?!1:e.typecheck?!0:r.packs.bp?.compile?.typecheck,o=e.cache===void 0?r.packs.bp?.compile?.cache.build??!1:!!e.cache,s=e.typecheckCommand;a=await Wr({cwd:n,config:r,logger:t,command:`build`,...i===void 0?{}:{typecheck:i},...s===void 0?{}:{typecheckCommand:s},...e.cache===void 0?{}:{cache:o},dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{}})}let{output:o,durationMs:s}=await Ja(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}});return{ok:!0,command:`pack`,durationMs:s,output:o,built:!i,build:a}}function Xa(e){for(let t of[[`copy`,`skipCopy`],[`pack`,`skipPack`],[`typecheck`,`skipTypecheck`],[`install`,`skipInstall`]]){let[n,r]=t;if(e[n]&&e[r])throw new F(`CLI_ARGUMENT_CONFLICT`,`--${n} and --${r} cannot be used together.`)}}async function Za(e){Xa(e);let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target,...e.timing===void 0?{}:{build:{timing:e.timing}}}});t.bepack(`build`,`target ${r.target}`);let i;if(e.install){let t=await rr({...e,cwd:n,config:void 0,silent:e.silent||e.json});i=Object.fromEntries(Object.entries(t.resolved).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion]))}let a=r.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=e.cache===void 0?a?.cache.build??!1:e.cache,l=await Wr({cwd:n,config:r,logger:t,mode:e.mode,command:`build`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},...e.useNpx?{useNpx:!0}:{},cache:!!c,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),u=null,d=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;d&&(u=await Bi({command:`build`,cwd:n,config:r,logger:t,...e.mode===void 0?{}:{mode:e.mode},targetName:e.copyTarget??(typeof d==`string`?d:void 0),dryRun:!!e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}}));let f=null;return!e.skipPack&&e.pack&&(f=await Ja(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}})),t.done(`build`,`complete in ${t.formatDuration(l.durationMs)}`),{ok:!0,command:`build`,durationMs:l.durationMs,build:l,copy:u,pack:f}}async function Qa(e){let t=Date.now(),n=new L({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});await G(`beforeCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let a=e.all?[`win`,`winold`,...Object.keys(i.copy.targets)]:[e.target??i.copy.defaultTarget],o={...e.optimize===void 0?{}:{optimize:!!e.optimize}},s=[];for(let t of a)s.push(await zi(r,i,t,e.dryRun,n,o));await G(`afterCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let c=Date.now()-t;return n.done(`copy`,`${e.dryRun?`dry-run complete`:`complete`} in ${n.formatDuration(c)}`),{ok:!0,command:`copy`,durationMs:c,results:s}}const $a=/[/\\]rolldown\.config\.[A-Za-z0-9_-]+\.js$/;function eo(e,t){return B(s.relative(e,t))}function to(e,t,n,r){let i=V(e,t),a=Pt(t),o=[];if(a){let n=U(e,t);n&&o.push(eo(e,s.dirname(n)))}if(r.copy){for(let n of Ot(t))if(H(i,t,n.type)){let r=no(e,t,n.type,i);o.push(...r)}}let c=t.dev.watch?.include??[];o.push(...c);let l=Gt(o.map(t=>s.resolve(e,t))).map(t=>eo(e,t));if(l.length===0)throw new F(`DEV_NO_WATCH_TARGETS`,`Nothing to watch: no compile entry, no copy-enabled pack directories and no dev.watch.include paths.`,{suggestions:[`Configure packs.bp.compile.entry to watch TypeScript sources.`,"Enable copying (packs.rp/bp, dev.copy or `bepack dev --copy`) to watch pack folders.",`Add paths explicitly with dev.watch.include.`]});let u=[`node_modules`,`.git`,eo(e,Ut(e,t))];for(let n of Ot(t)){let r=H(i,t,n.type);if(r&&(u.push(eo(e,s.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=H(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push(eo(e,s.join(n,r)))}}let d=S.watch(l,{cwd:e,ignored:[...u,$a],ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await Bi({command:`dev`,cwd:e,config:t,logger:n,targetName:r.copyTarget,dryRun:r.dryRun,...r.mode===void 0?{}:{mode:r.mode},...r.optimize===void 0?{}:{optimize:r.optimize}})},g=async()=>{await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},_=async()=>{a?await Wr({cwd:e,config:t,logger:n,command:`dev`,typecheck:r.typecheck,cache:r.cache,dryRun:r.dryRun,quiet:!!r.quiet,...r.mode===void 0?{}:{mode:r.mode},...r.typecheckCommand===void 0?{}:{typecheckCommand:r.typecheckCommand},...r.rolldownConfig===void 0?{}:{rolldownConfig:r.rolldownConfig}}):await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},v=async()=>{for(;p||m;){let e=p;p=!1,m=!1;let t=Date.now();try{n.clear(),e?(n.bepack(`dev`,`rebuilding (pending changes)`),await _(),n.done(`dev`,`rebuild done in ${n.formatDuration(Date.now()-t)}`)):await g()}catch(e){n.error(e instanceof Error?e.message:String(e))}}};d.on(`all`,async(r,i)=>{let o=B(i),c=a?U(e,t):void 0,l=c?s.dirname(c):void 0,u=s.resolve(e,o),d=l?u===l||u.startsWith(l+s.sep):!1;if(f){d?p=!0:m=!0;return}f=!0;let h=Date.now();try{n.clear(),n.bepack(`dev`,`changed ${s.normalize(i)}`),d&&a?await _():await g(),n.done(`dev`,`updated after ${s.normalize(i)} in ${n.formatDuration(Date.now()-h)}`)}catch(e){n.error(e instanceof Error?e.message:String(e))}finally{try{await v()}finally{f=!1}}});let y=t.packs.bp?B(s.relative(e,H(i,t,`bp`))):null,b=t.packs.rp?B(s.relative(e,H(i,t,`rp`))):null,x=a&&U(e,t)?eo(e,s.dirname(U(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)y&&(e===y||e.startsWith(y+`/`))?(T++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):b&&(e===b||e.startsWith(b+`/`))?(E++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))||w.push(e);return x&&!C&&w.unshift(x),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function no(e,t,n,r){let i=H(r,t,n);if(!i)return[];if(n===`bp`)return Bt(t).filter(e=>e!==`manifest.json`).map(t=>B(s.relative(e,s.join(i,t))));let a=t.packs.rp;return a?a.include&&a.include.length>0?a.include.filter(e=>e!==`manifest.json`).map(t=>B(s.relative(e,s.join(i,t)))):[B(s.relative(e,i))]:[]}async function ro(e){let t=Date.now(),n=new L({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{...e.timing===void 0?{}:{build:{timing:e.timing}}}});n.clear(),n.bepack(`dev`,`target ${i.target}`),n.progress(`dev`,`initial build started`);let a=i.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=!e.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),l=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),u=a?.cache.dev??!0,d=!!e.dryRun,f=!!(e.json||e.silent),p=e.optimize===void 0?{}:{optimize:!!e.optimize};return await Wr({cwd:r,config:i,logger:n,mode:e.mode,command:`dev`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),c&&await Bi({command:`dev`,cwd:r,config:i,logger:n,targetName:l,dryRun:d,...e.mode===void 0?{}:{mode:e.mode},...p}),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),to(r,i,n,{copy:c,mode:e.mode,...l?{copyTarget:l}:{},...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},...p,typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}function io(e){let t=/* @__PURE__ */ new WeakSet;function n(e){if(typeof e==`function`)return`[function]`;if(e instanceof RegExp)return e.toString();if(typeof e!=`object`||!e)return e;if(t.has(e))return`[circular]`;t.add(e);let r=Array.isArray(e)?e.map(n):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)]));return t.delete(e),r}return n(e)}async function ao(e){let t=new L({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:io(r)};if(e.summary){t.bepack(`config`,i),t.info(`root: ${r.root}`),t.info(`name: ${r.name}`),t.info(`version: ${r.version}`),r.description&&t.info(`description: ${r.description}`),t.info(`target: ${r.target}`);let e=[];if(r.packs.bp&&e.push(`bp`),r.packs.rp&&e.push(`rp`),t.info(`packs: ${e.join(`, `)}`),r.packs.bp?.compile){let e=r.packs.bp.compile;t.info(`compile.entry: ${e.entry}`),t.info(`compile.scriptOutputDir: ${e.scriptOutputDir}`),t.info(`compile.preserveModules: ${e.preserveModules}`),t.info(`compile.typecheck: ${e.typecheck}`),e.typecheckCommand&&t.info(`compile.typecheckCommand: ${e.typecheckCommand}`),e.typecheckArgs.length>0&&t.info(`compile.typecheckArgs: [${e.typecheckArgs.join(`, `)}]`),e.external.length>0&&t.info(`compile.external: [${e.external.map(e=>typeof e==`string`?e:e.toString()).join(`, `)}]`)}let n=Object.keys(r.hooks);n.length>0?t.info(`hooks: ${n.join(`, `)}`):t.info(`hooks: (none)`);let a=r.plugins??[];if(a.length>0){t.info(`plugins: ${a.map(e=>`${e.name} (priority ${e.priority??0})`).join(`, `)}`);for(let e of r.pluginDiagnostics??[])t.warn(`plugin conflict: ${e}`)}else t.info(`plugins: (none)`);t.info(`install.registry: ${r.install.registry}`);let o=Object.keys(Ln(r));return o.length>0?t.info(`install.dependencyCatalog: ${o.join(`, `)}`):t.info(`install.dependencyCatalog: (none)`),t.info(`pack.outDir: ${r.pack.outDir}`),r.copy.defaultTarget&&t.info(`copy.defaultTarget: ${r.copy.defaultTarget}`),r.build.copy&&t.info(`build.copy: ${r.build.copy}`),r.dev.copy&&t.info(`dev.copy: ${r.dev.copy}`),{ok:!0,command:`config`}}let a=io(r),o=JSON.stringify(a,null,2);return t.bepack(`config`,i),t.info(`cwd: ${n}`),t.info(`configFile: ${i}`),t.info(``),t.info(o),{ok:!0,command:`config`}}function Z(e,t,n){throw new F(`PROFILE_INVALID`,`${e}: ${t}`,{...n===void 0?{}:{details:n},suggestions:[`Check that the file was produced by a V8 profiler and is valid JSON.`]})}function oo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function so(e,t,n){return(typeof e!=`number`||!Number.isFinite(e))&&Z(n,`${t} must be a finite number`),e}function co(e,t,n){let r=so(e,t,n);return Number.isInteger(r)||Z(n,`${t} must be an integer`),r}function lo(e,t,n,r){let i=e[t];if(i!==void 0)return so(i,`${n}.${t}`,r)}function uo(e,t,n,r){let i=e[t];if(i!==void 0)return co(i,`${n}.${t}`,r)}function fo(e,t,n){oo(e)||Z(n,`${t} must be an object`);let r=e.functionName??``;typeof r!=`string`&&Z(n,`${t}.functionName must be a string`);let i=e.url??``;typeof i!=`string`&&Z(n,`${t}.url must be a string`);let a=e.scriptId,o;a===void 0?o=`0`:typeof a==`number`&&Number.isFinite(a)?o=String(a):typeof a==`string`?o=a:Z(n,`${t}.scriptId must be a string`);let s=e.lineNumber??-1;(typeof s!=`number`||!Number.isFinite(s))&&Z(n,`${t}.lineNumber must be a finite number`);let c=e.columnNumber??-1;return(typeof c!=`number`||!Number.isFinite(c))&&Z(n,`${t}.columnNumber must be a finite number`),{functionName:r,scriptId:o,url:i,lineNumber:s,columnNumber:c}}function po(e,t,n){let r=`nodes[${t}]`;oo(e)||Z(n,`${r} must be an object`);let i=co(e.id,`${r}.id`,n),a=fo(e.callFrame,`${r}.callFrame`,n),o=uo(e,`hitCount`,r,n),s=uo(e,`locationId`,r,n),c;return e.children!==void 0&&(Array.isArray(e.children)||Z(n,`${r}.children must be an array`),c=e.children.map((e,t)=>co(e,`${r}.children[${t}]`,n))),{id:i,callFrame:a,...o===void 0?{}:{hitCount:o},...c===void 0?{}:{children:c},...s===void 0?{}:{locationId:s}}}function mo(e,t=`<profile>`){oo(e)||Z(t,`profile root must be a JSON object`),Array.isArray(e.nodes)||Z(t,`missing nodes array`),Array.isArray(e.samples)||Z(t,`missing samples array`),Array.isArray(e.timeDeltas)||Z(t,`missing timeDeltas array`);let n=e.nodes.map((e,n)=>po(e,n,t)),r=/* @__PURE__ */ new Set;for(let e of n)r.has(e.id)&&Z(t,`duplicate node id ${e.id}`),r.add(e.id);for(let e of n)for(let n of e.children??[])r.has(n)||Z(t,`node ${e.id} references unknown child node ${n}`);e.timeDeltas.length!==e.samples.length&&Z(t,`samples and timeDeltas must have the same length (${e.samples.length} != ${e.timeDeltas.length})`);let i=e.samples.map((e,n)=>{let i=co(e,`samples[${n}]`,t);return r.has(i)||Z(t,`samples[${n}] references unknown node ${i}`),i}),a=e.timeDeltas.map((e,n)=>{let r=so(e,`timeDeltas[${n}]`,t);return r<0&&Z(t,`timeDeltas[${n}] must not be negative`),r}),o=lo(e,`startTime`,`profile`,t),s=lo(e,`endTime`,`profile`,t);return{nodes:n,samples:i,timeDeltas:a,...o===void 0?{}:{startTime:o},...s===void 0?{}:{endTime:s}}}function ho(e,t,n){let r=[],i=/* @__PURE__ */ new Set,a=e.id;for(;a!==void 0&&!i.has(a);){i.add(a);let e=n.get(a);if(!e)break;r.push(e),a=t.get(a)}return r}function go(e){let t=e[0],n=e[e.length-1];if(!t||!n)throw Error(`cannot create a burst from an empty sample run`);let r=e.reduce((e,t)=>e+t.deltaMs,0);return{startMs:t.timeMs,endMs:n.timeMs,spanMs:n.timeMs-t.timeMs,busyMs:r,samples:e.length,run:e}}function _o(e,t){let n=[],r=[];for(let i of e){if(i.active){r.push(i);continue}r.length>0&&r.length>=t&&n.push(go(r)),r=[]}return r.length>0&&r.length>=t&&n.push(go(r)),n}function vo(e,t,n){let r=mo(e,t),i=n.gapMs??5,a=n.minSamples??20,o=new Map(r.nodes.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of r.nodes)for(let t of e.children??[])s.set(t,e.id);let c=i*1e3,l=0,u=[];for(let e=0;e<r.samples.length;e++){let t=r.timeDeltas[e]??0;l+=t;let n=o.get(r.samples[e]??-1);n&&u.push({index:e,timeMs:l/1e3,deltaMs:t/1e3,active:t<=c,node:n,stack:ho(n,s,o)})}let d=u.filter(e=>e.active),f=u.filter(e=>!e.active);return{file:t,raw:r,samples:u,activeSamples:d,gapSamples:f,busyMs:d.reduce((e,t)=>e+t.deltaMs,0),idleMs:f.reduce((e,t)=>e+t.deltaMs,0),durationMs:l/1e3,gapMs:i,minSamples:a,bursts:_o(u,a)}}async function yo(e,t={}){let n;try{n=await v(e,`utf8`)}catch(t){throw new F(`PROFILE_READ_FAILED`,`Cannot read profile ${e}: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Check the path and that the file is readable.`]})}let r;try{r=JSON.parse(n)}catch(t){Z(e,`not valid JSON: ${t instanceof Error?t.message:String(t)}`)}return vo(r,e,t)}function bo(e){let t=e.callFrame;return`${t.functionName||`(anonymous)`}\u0000${t.url||`(unknown)`}\u0000${t.lineNumber}`}function xo(e,{by:t,gapMs:n}){let r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e){if(o.deltaMs>n)continue;if(i++,a+=o.deltaMs,t===`self`){let e=o.stack[0];if(!e)continue;let t=bo(e),n=r.get(t)??{node:e,count:0,ms:0};n.count++,n.ms+=o.deltaMs,r.set(t,n);continue}let e=/* @__PURE__ */ new Set;for(let t of o.stack){let n=bo(t);if(e.has(n))continue;e.add(n);let i=r.get(n)??{node:t,count:0,ms:0};i.count++,i.ms+=o.deltaMs,r.set(n,i)}}return{rows:[...r.values()].map(e=>({node:e.node,count:e.count,share:a===0?0:e.ms/a,ms:e.ms})).sort((e,t)=>t.ms-e.ms||t.count-e.count||e.node.callFrame.functionName.localeCompare(t.node.callFrame.functionName)),active:i,busyMs:a}}function So(e,t,n){let r=/* @__PURE__ */ new Map,i=0;for(let n of e){if(n.deltaMs>t)continue;i+=n.deltaMs;let e=n.stack.map(e=>bo(e)).join(`
|
|
11
|
-
`),a=r.get(e)??{sample:n,count:0,ms:0};a.count++,a.ms+=n.deltaMs,r.set(e,a)}return[...r.values()].sort((e,t)=>t.ms-e.ms||t.count-e.count).slice(0,n).map(e=>({sample:e.sample,count:e.count,share:i===0?0:e.ms/i,ms:e.ms}))}function
|
|
8
|
+
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;t&&console.info(`${e}/${t} ${me}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new de(`missing required args for command \`${this.rawName}\``)}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let n of Object.keys(e))if(n!==`--`&&!this.hasOption(n)&&!t.hasOption(n))throw new de(`Unknown option \`${n.length>1?`--${n}`:`-${n}`}\``)}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,n=[...t.options,...this.options];for(let t of n){let r=e[t.name.split(`.`)[0]];if(t.required){let e=n.some(e=>e.negated&&e.names.includes(t.name));if(r===!0||r===!1&&!e)throw new de(`option \`${t.rawName}\` value is missing`)}}}checkUnusedArgs(){let e=this.args.some(e=>e.variadic)?1/0:this.args.length;if(e<this.cli.args.length)throw new de(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},ge=class extends he{constructor(e){super(`@@global@@`,``,{},e)}},_e=class extends EventTarget{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;constructor(e=``){super(),this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ge(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new he(e,t||``,n,this);return r.globalCommand=this.globalCommand,this.commands.push(r),r}option(e,t,n){return this.globalCommand.option(e,t,n),this}help(e){return this.globalCommand.option(`-h, --help`,`Display this message`),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t=`-v, --version`){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){this.matchedCommand?this.matchedCommand.outputHelp():this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},n,r){return this.args=e,this.options=t,n&&(this.matchedCommand=n),r&&(this.matchedCommandName=r),this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}parse(e,{run:t=!0}={}){if(!e){if(!pe)throw Error(`No argv provided and runtime process argv is not available.`);e=pe}this.rawArgs=e,this.name||=e[1]?le(e[1]):`cli`;let n=!0;for(let t of this.commands){let r=this.mri(e.slice(2),t),i=r.args[0];if(t.isMatched(i)){n=!1;let e={...r,args:r.args.slice(1)};this.setParsedInfo(e,t,i),this.dispatchEvent(new CustomEvent(`command:${i}`,{detail:t}))}}if(n){for(let t of this.commands)if(t.isDefaultCommand){n=!1;let r=this.mri(e.slice(2),t);this.setParsedInfo(r,t),this.dispatchEvent(new CustomEvent(`command:!`,{detail:t}))}}if(n){let t=this.mri(e.slice(2));this.setParsedInfo(t)}this.options.help&&this.showHelpOnExit&&(this.outputHelp(),t=!1,this.unsetMatchedCommand()),this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null&&(this.outputVersion(),t=!1,this.unsetMatchedCommand());let r={args:this.args,options:this.options};return t&&this.runMatchedCommand(),!this.matchedCommand&&this.args[0]&&this.dispatchEvent(new CustomEvent(`command:*`,{detail:this.args[0]})),r}mri(e,t){let n=[...this.globalCommand.options,...t?t.options:[]],r=ae(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=re(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[ue(t)]:o[t]}),{_:[]});let s=o._,c={"--":i},l=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,u=Object.create(null);for(let e of n){if(!l&&e.config.default!==void 0)for(let t of e.names)c[t]=e.config.default;Array.isArray(e.config.type)&&u[e.name]===void 0&&(u[e.name]=Object.create(null),u[e.name].shouldTransform=!0,u[e.name].transformFunction=e.config.type[0])}for(let e of Object.keys(o))e!==`_`&&(se(c,e.split(`.`),o[e]),ce(c,u));return{args:s,options:c}}runMatchedCommand(){let{args:e,options:t,matchedCommand:n}=this;if(!n||!n.commandAction)return;n.checkUnknownOptions(),n.checkOptionValue(),n.checkRequiredArgs(),n.checkUnusedArgs();let r=[];return n.args.forEach((t,n)=>{t.variadic?r.push(e.slice(n)):r.push(e[n])}),r.push(t),n.commandAction.apply(this,r)}};const ve=(e=``)=>new _e(e);function ye(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function be(e){return`${JSON.stringify(e,null,4)}\n`}async function I(e){try{return await n.access(e),!0}catch{return!1}}async function xe(e){await n.mkdir(e,{recursive:!0})}async function Se(e){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0})}async function Ce(e){return ye(await n.readFile(e,`utf8`),e)}async function we(e,t){await xe(s.dirname(e)),await n.writeFile(e,be(t),`utf8`)}async function Te(e,t){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(s.dirname(t),{recursive:!0}),await n.cp(e,t,{recursive:!0})}var L=class extends Error{code;details;suggestions;constructor(e,t,n={}){super(t),this.name=`BePackError`,this.code=e,this.details=n.details,this.suggestions=n.suggestions}},Ee=/* @__PURE__ */ j((/* @__PURE__ */ O(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})))(),1);const R=Ee.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var z=class{options;constructor(e={}){this.options=e}formatDuration(e){return R.green(`${(e/1e3).toFixed(2)}s`)}info(e){this.options.silent||console.log(e)}warn(e){this.options.silent||console.warn(R.yellow(e))}error(e){this.options.silent||console.error(R.red(e))}verbose(e){!this.options.silent&&this.options.verbose&&console.log(R.gray(e))}clear(){this.options.silent||console.clear()}step(e,t,n=`cyan`){this.info(`${R[n](e.padEnd(10))} ${t}`)}progress(e,t){this.step(e,t,`blue`)}success(e,t){this.step(e,t,`green`)}bepack(e,t){this.info(`${R.green(`bepack`)} ${R.bold(e)} ${R.gray(t)}`)}manifest(e){this.step(`manifest`,e,`yellow`)}typescript(e){this.step(`TS`,e,`blue`)}rolldown(e){this.step(`rolldown`,e,`magenta`)}install(e){this.step(`install`,e,`blue`)}copy(e){this.step(`copy`,e,`cyan`)}pack(e){this.step(`pack`,e,`magenta`)}hook(e,t){this.step(`hook`,`${e}: ${t}`,`gray`)}timing(e,t){this.step(`timing`,`${e.padEnd(14)} ${t} ms`,`gray`)}done(e,t){this.info(`${R.green(`√`)} ${R.green(e)} ${t}`)}};function De(e){return Array.isArray(e)&&e.length===3&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`}function Oe(e){return typeof e==`string`&&/^\d+\.\d+\.\d+$/.test(e)}function ke(e){return e===3?Oe:De}function Ae(e,t){return e===3?`${t} must be SemVer string like "x.y.z" (format 3)`:`${t} must be [number, number, number] (format 2)`}const je=[e=>e.format_version===void 0?`format_version is required`:null,e=>e.header?null:`header is required`,e=>e.header&&!e.header.name?`header.name is required`:null,e=>e.header&&!e.header.uuid?`header.uuid is required`:null,e=>e.header?ke(e.format_version)(e.header.version)?null:Ae(e.format_version,`header.version`):null,e=>e.header?ke(e.format_version)(e.header.min_engine_version)?null:Ae(e.format_version,`header.min_engine_version`):null,e=>e.modules!==void 0&&!Array.isArray(e.modules)?`modules must be an array`:null,(e,t)=>{if(!Array.isArray(e.modules))return null;let n=e.modules.some(e=>e?.type===`resources`),r=[];return t===`rp`&&!n&&r.push(`RP manifest must have a resources module`),r.length>0?r:null},e=>{if(!Array.isArray(e.modules))return null;let t=ke(e.format_version),n=[];for(let r=0;r<e.modules.length;r++){let i=e.modules[r];i&&i.version!==void 0&&i.version!==null&&!t(i.version)&&n.push(`modules[${r}] (uuid: ${i.uuid??`unknown`}): ${Ae(e.format_version,`version`)}`)}return n.length>0?n:null},e=>e.dependencies!==void 0&&!Array.isArray(e.dependencies)?`dependencies must be an array`:null,e=>{if(!Array.isArray(e.dependencies))return null;let t=ke(e.format_version),n=[];for(let r=0;r<e.dependencies.length;r++){let i=e.dependencies[r];if(!i){n.push(`dependencies[${r}] is invalid`);continue}`uuid`in i&&i.uuid&&!t(i.version)&&n.push(`dependencies[${r}] (uuid: ${i.uuid}): ${Ae(e.format_version,`version`)}`),`module_name`in i&&i.module_name&&typeof i.version!=`string`&&n.push(`dependencies[${r}] (module_name: ${i.module_name}): version must be a string`)}return n.length>0?n:null},e=>e.capabilities===void 0?null:Array.isArray(e.capabilities)?e.capabilities.every(e=>typeof e==`string`)?null:`capabilities must be an array of strings`:`capabilities must be an array`,e=>e.metadata!==void 0&&(typeof e.metadata!=`object`||e.metadata===null)?`metadata must be an object`:null];function Me(e,t){let n=[];for(let r of je){let i=r(e,t);i!==null&&(Array.isArray(i)?n.push(...i):n.push(i))}if(n.length>0)throw new L(`MANIFEST_INVALID`,`Manifest validation failed: ${n.join(`; `)}`)}function Ne(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Pe(e){return Array.isArray(e)?e:[]}function Fe(e){if(!(e&&Object.keys(e).length===0))return e}var Ie=class{static async read(e){if(!await I(e))return;let t=await n.readFile(e,`utf8`);try{return Ne(JSON.parse(t))}catch{throw new L(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){Me(t,n),await we(e,t)}};function Le(e){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)throw new L(`VERSION_INVALID`,`Manifest version requires x.y.z.`,{details:{version:e}});return[Number(t[1]),Number(t[2]),Number(t[3])]}function Re(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function B(e,t){let n=e.split(/[^0-9A-Za-z]+/),r=t.split(/[^0-9A-Za-z]+/),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??``,i=r[e]??``,a=/^\d+$/.test(t)?Number(t):NaN,o=/^\d+$/.test(i)?Number(i):NaN,s=Number.isNaN(a)||Number.isNaN(o)?t.localeCompare(i):a-o;if(s!==0)return s}return 0}function ze(e){return e===`latest`||B(e,`1.21.120`)>=0}function Be(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(e.trim());if(!t)return;let n=/(?:^|[.-])(\d+)\.(\d+)\.(\d+)(?:[.-]|$)/.exec(t[4]??``);return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),...n?{minecraftTarget:[Number(n[1]),Number(n[2]),Number(n[3])]}:{}}}function Ve(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function He(e,t){let n=Be(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?Be(t[1]):void 0;return!r||n.major!==r.major||Ve(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?B(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}function Ue(e){if(e===`stable`||e===`beta`||e===`preview`)throw new L(`DEPENDENCY_VERSION_INVALID`,`${e} must be resolved from npm registry before writing package.json.`,{details:{specifier:e}});if(Re(e))return e;throw new L(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function We(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(B)}function Ge(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(B)}var Ke=class{npm;logger;constructor(e,t){this.npm=e,this.logger=t}latestStable(e,t){let n=this.npm.distTag(t,`latest`);if(n&&/^\d+\.\d+\.\d+$/.test(n))return this.logger?.verbose(`Resolved ${e}@stable -> ${n}`),n;let r=We(this.npm.versions(t)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@stable -> ${r}`),r}latestBeta(e,t){let n=this.npm.distTag(t,`beta`);if(n)return this.logger?.verbose(`Resolved ${e}@beta -> ${n}`),n;let r=Ge(this.npm.versions(t)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return this.logger?.verbose(`Resolved ${e}@beta -> ${r}`),r}betaForTarget(e,t,n){let r=t.replace(/\./g,`\\.`),i=RegExp(`beta[-.]${r}-stable`),a=this.npm.versions(n).filter(e=>i.test(e)).sort(B).at(-1);if(!a)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@beta for target ${t}.`,{details:{package:e,specifier:`beta`,target:t},suggestions:[`Use target: "latest"`,`Specify an exact version`,`Update BePack`,`Manually edit package.json and manifest.json`]});return this.logger?.verbose(`Resolved ${e}@beta for target ${t} -> ${a}`),a}inferStableFromBeta(e,t,n,r){let i=/^(\d+)\.(\d+)\.(\d+)-beta[.-]/.exec(n);if(!i)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot infer stable version from ${e}@${n}.`,{details:{package:e,beta:n,target:t}});let a=Number(i[1]),o=Number(i[2])-1,s=`${a}.${o}.${Number(i[3])}`;if(o<0||!r.versions?.[s])throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot confirm inferred stable version ${s} for ${e}.`,{details:{package:e,target:t,beta:n,inferredStable:s}});return s}};function qe(e,t){return t===`latest`||ze(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function Je(e,t,n){let r=Ge(t).filter(e=>/^\d+\.\d+\.\d+-beta\.\d+\.\d+\.\d+/.test(e)).filter(e=>!/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@beta -> ${r}`),r}function Ye(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(B)}function Xe(e,t,n){let r=Ye(t).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@preview -> ${r}`),r}function Ze(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(B).at(-1);if(!o)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e}@preview for target ${n}.`,{details:{package:e,specifier:`preview`,target:n},suggestions:[`Use target: "latest"`,`Specify an exact version`]});return r?.verbose(`Resolved ${e}@preview for target ${n} -> ${o}`),o}const Qe={name:`minecraft-script-api`,resolver:`minecraft-script-api`,match:e=>e.specifier===`stable`||e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Ke(e.npm,e.logger);if(e.specifier===`stable`){e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`);let r=e.target===`latest`?n.latestStable(e.packageName,t):n.inferStableFromBeta(e.packageName,e.target,n.betaForTarget(e.packageName,e.target,t),t);return{packageVersion:r,manifestVersion:r}}if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:qe(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):Ze(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},$e={name:`minecraft-script-api-bp`,resolver:`minecraft-script-api-bp`,match:e=>e.specifier===`beta`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName),n=new Ke(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:qe(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Xe(e.packageName,e.npm.versions(t),e.logger):Ze(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},et=/^\d+\.\d+\.\d+$/,tt=/^\d+\.\d+\.\d+-preview\.\d+$/,nt={name:`minecraft-vanilla-data`,resolver:`minecraft-vanilla-data`,match:e=>e.specifier===`stable`||e.specifier===`preview`,async resolve(e){let t=await e.npm.metadata(e.packageName);return e.specifier===`stable`?rt(e,t):it(e,t)}};function rt(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@stable for target ${e.target}`),e.target===`latest`){let n=e.npm.distTag(t,`latest`);if(n&&et.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>et.test(e)).sort(B).at(-1);if(!r)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest stable version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${r}`),{packageVersion:r}}if(t.versions?.[e.target])return e.logger?.verbose(`Resolved ${e.packageName}@stable for target ${e.target} -> ${e.target}`),{packageVersion:e.target};throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@stable for target ${e.target}. The target version does not exist in the registry.`,{details:{package:e.packageName,specifier:`stable`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact version`]})}function it(e,t){if(e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`),e.target===`latest`){let n=e.npm.versions(t).filter(e=>tt.test(e)).sort(B).at(-1);if(!n)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e.packageName}.`,{details:{package:e.packageName}});return e.logger?.verbose(`Resolved ${e.packageName}@preview -> ${n}`),{packageVersion:n}}let n=e.target.replace(/\./g,`\\.`),r=RegExp(`^${n}-preview\\.\\d+$`),i=e.npm.versions(t).filter(e=>r.test(e)).sort(B).at(-1);if(!i)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve ${e.packageName}@preview for target ${e.target}. No matching preview version found.`,{details:{package:e.packageName,specifier:`preview`,target:e.target},suggestions:[`Use target: "latest"`,`Specify an exact preview version`]});return e.logger?.verbose(`Resolved ${e.packageName}@preview for target ${e.target} -> ${i}`),{packageVersion:i}}const at={"@minecraft/common":{resolver:Qe,manifest:!0},"@minecraft/server":{resolver:Qe,manifest:!0},"@minecraft/server-ui":{resolver:Qe,manifest:!0},"@minecraft/server-net":{resolver:$e,manifest:!0},"@minecraft/server-admin":{resolver:$e,manifest:!0},"@minecraft/server-gametest":{resolver:$e,manifest:!0},"@minecraft/debug-utilities":{resolver:$e,manifest:!0},"@minecraft/diagnostics":{resolver:$e,manifest:!0},"@minecraft/server-graphics":{resolver:$e,manifest:!0},"@minecraft/server-editor":{resolver:$e,manifest:!0},"@minecraft/vanilla-data":{resolver:nt,manifest:!1}};var ot=class e{static validateHeader(e,t){if(!e.header?.name||!e.header?.uuid)throw new L(`MANIFEST_INVALID`,`${t} manifest is missing header.name or header.uuid`);return{name:e.header.name,uuid:e.header.uuid,...e.header.description?{description:e.header.description}:{}}}static findScriptModuleUuid(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.uuid}static findScriptModuleEntry(t){for(let n of t.modules??[])if(n&&e.isScriptModule(n))return n.entry}static findResourcesModuleUuid(t){for(let n of t.modules??[])if(n&&e.isResourcesModule(n))return n.uuid}static matchDependencies(e){let t={};for(let n of e.dependencies??[])if(`module_name`in n&&typeof n.module_name==`string`){let e=n.module_name;at[e]&&(t[e]=typeof n.version==`string`?n.version:String(n.version))}return t}static isScriptModule(e){return e?.type===`script`&&e?.language===`javascript`}static isResourcesModule(e){return e?.type===`resources`}};function st(e,t){if(typeof e!=`string`||!e)throw new L(`MANIFEST_INVALID`,`${t} script module entry must be a non-empty string.`);let n=e.replace(/\\/g,`/`);if(s.posix.isAbsolute(n)||s.win32.isAbsolute(n))throw new L(`MANIFEST_INVALID`,`${t} script module entry must be a relative path, got absolute: "${e}".`);if(!n.endsWith(`.js`))throw new L(`MANIFEST_INVALID`,`${t} script module entry must end with .js, got: "${e}".`);let r=n.split(`/`);if(r.includes(`..`))throw new L(`MANIFEST_INVALID`,`${t} script module entry must not contain "..": "${e}".`);if(r.includes(``))throw new L(`MANIFEST_INVALID`,`${t} script module entry must not contain empty segments: "${e}".`);return n}function ct(e,t){let n=s.resolve(e,t),r=s.dirname(n),i=s.relative(e,r);if(i.startsWith(`..`)||s.isAbsolute(i))throw new L(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function lt(e,t){if(!t&&await I(e))throw new L(`CONFIG_INVALID`,`Config file already exists: ${e}. Use --force to overwrite.`,{suggestions:[`Pass --force to overwrite the existing file.`]})}async function ut(e,t,r,i=!1){return await lt(e,r),!i&&(await xe(s.dirname(e)),await n.writeFile(e,t,`utf8`),!0)}const dt=[`.ts`,`.mts`,`.js`,`.mjs`];async function ft(e,t){let n=(t===`main`?[`main`]:[t,`main`]).flatMap(e=>dt.map(t=>`src/${e}${t}`));for(let t of n)if(await I(s.join(e,t))){let e=s.extname(t);return{entry:t,typecheckable:e===`.ts`||e===`.mts`,searched:n}}}function pt(e){return(e===`main`?[`main`]:[e,`main`]).map(e=>`src/${e}.{${dt.join(`,`).replace(/\./g,``)}}`).join(` or `)}function mt(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
|
|
9
|
+
$1$2: `)}\n`}function ht(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function gt(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function _t(e){if(Array.isArray(e)&&e.length===3)return e;if(typeof e==`string`){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}}async function vt(e,t){let n=t.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new L(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(e,`bepack.config.${n}`),i=!!t.force,a=!!t.dryRun,o=new z({silent:t.silent,verbose:t.verbose}),c=!!t.fromBp,l=!!t.fromRp,u,d,f,p=!1,m,h,g,_,v,y,b=[];if(c){let n=s.resolve(e,t.fromBp),r=await Ie.read(n);if(!r)throw new L(`CONFIG_NOT_FOUND`,`BP manifest not found: ${t.fromBp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ot.validateHeader(r,`BP`),a=ot.findScriptModuleUuid(r),o=ot.findScriptModuleEntry(r),c=ht(r.header?.version);c&&b.push(c),u={root:ct(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:ot.matchDependencies(r),...o?{scriptEntry:o}:{}},m=i.name,h=i.description,g=i.name,_=i.description}if(l){let n=s.resolve(e,t.fromRp),r=await Ie.read(n);if(!r)throw new L(`CONFIG_NOT_FOUND`,`RP manifest not found: ${t.fromRp}`);f??=r.format_version,r.format_version!==void 0&&r.header?.version!==void 0&&(r.format_version===3&&Array.isArray(r.header.version)||r.format_version===2&&typeof r.header.version==`string`)&&(p=!0);let i=ot.validateHeader(r,`RP`),a=ot.findResourcesModuleUuid(r);if(!a)throw new L(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let o=ht(r.header?.version);o&&b.push(o),d={root:ct(e,n),uuid:i.uuid,moduleUuid:a,...o?{version:o}:{}},c||(m=i.name,h=i.description),v=i.name,y=i.description}let x;if(b.length===1)x=b[0];else if(b.length===2){let e=b[0],t=b[1];if(e===t)x=e;else{let n=_t(e),r=_t(t);x=n&&r?gt(n,r)>=0?e:t:e,o.warn(`BP version (${e}) and RP version (${t}) differ. Using ${x}.`)}}p&&(o.warn(`Detected format_version ${f} doesn't match the actual version format used in manifest. Falling back to format_version 2.`),f=2);let S={root:`.`,target:`latest`,pack:{outDir:`dist`}};f!==void 0&&(S.manifestFormat=f),x&&(S.version=x),m&&(S.name=m),h&&(S.description=h);let C={};if(u){let t={root:u.root,uuid:u.uuid};if(u.moduleUuid){if(t.moduleUuid=u.moduleUuid,u.scriptEntry){let n=st(u.scriptEntry,`BP`),r=s.posix.dirname(n),i=s.posix.basename(n,`.js`);if(r===`.`)throw new L(`MANIFEST_INVALID`,`BP manifest script entry "${u.scriptEntry}" is at the BP root. BePack cannot safely manage root-level script output because the output directory would need to be emptied on each build, which would delete the entire BP root. Please add a subdirectory prefix to the script module entry in your manifest.json (e.g. "scripts/main.js"), then rerun init.`);let a=await ft(e,i);if(a){let n=await I(s.join(e,`tsconfig.json`)),i=a.typecheckable&&n;t.compile={entry:a.entry,scriptOutputDir:r,...i?{}:{typecheck:!1}},i||o.warn(`Detected script entry "${u.scriptEntry}" with source "${a.entry}", but ${a.typecheckable?`tsconfig.json is missing`:`the source is JavaScript`}. Generated config sets compile.typecheck: false.`+(a.typecheckable?` Add tsconfig.json and remove that flag to enable typechecking.`:``))}else o.warn(`BP manifest declares script entry "${u.scriptEntry}" but no matching source file exists (looked for ${pt(i)}). Leaving packs.bp.compile unset: the existing "${r}" folder is copied/packed as-is. Set packs.bp.compile manually once you add sources.`)}else o.warn("BP manifest has a script module but no `entry` field, so the script output directory cannot be derived. Leaving packs.bp.compile unset; add it manually to compile TypeScript into the pack.")}g&&(t.name=g),_&&(t.description=_),Object.keys(u.deps).length>0&&(t.dependencies={...u.deps}),C.bp=t}if(d){let e={root:d.root,uuid:d.uuid,moduleUuid:d.moduleUuid};v&&(e.name=v),y&&(e.description=y),C.rp=e}S.packs=C,process.platform===`win32`&&(S.copy={defaultTarget:`win`});let w=await ut(r,mt(S),i,a);return a&&o.info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:a,filesCreated:+!!w,files:[r]}}function yt(){return mt({root:`.`,name:`example-addon`,version:`1.0.0`,target:`latest`,packs:{bp:{root:`bp`,uuid:u(),moduleUuid:u(),compile:{entry:`src/main.ts`},dependencies:{"@minecraft/server":`stable`}}},pack:{outDir:`dist`}})}async function bt(e){let t=s.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await vt(t,e);let n=e.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new L(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(t,`bepack.config.${n}`),i=!!e.dryRun,a=await ut(r,yt(),!!e.force,i);return i&&new z({silent:e.silent,verbose:e.verbose}).info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:i,filesCreated:+!!a,files:[r]}}const xt=[`bepack.config.ts`,`bepack.config.mjs`,`bepack.config.js`],V={root:`.`,configured:{root:!1,packOutDir:!1},name:`minecraft-addon`,version:`1.0.0`,description:``,replace:{values:{},builtins:{VERSION:!1,NAME:!1,UUID:!1,DESCRIPTION:!1}},target:`latest`,plugins:[],install:{registry:`https://registry.npmjs.org/`,saveTo:`dependencies`,packageManager:`auto`,runPackageManager:!0,updatePackageJson:!0,updateManifest:!0,dependencyCatalog:{},dependencyResolvers:[]},build:{copy:!1,timing:!1},dev:{copy:!1},copy:{defaultTarget:``,targets:{}},pack:{name:`{name}-{version}`,outDir:`dist`},hooks:{}},St={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},Ct={keepLooseFiles:!1,keepLoose:[],exclude:[],minifyJson:!0,packOptimizationVersion:`0.1.0`,allowUnsupportedTarget:!1},wt={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,typecheckArgs:[],preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:St,scriptOutputDir:`scripts`},Tt=[`world`,`global`,`any`];function Et(e){let t=[];return e.packs.bp&&t.push({type:`bp`,root:e.packs.bp.root,uuid:e.packs.bp.uuid,...e.packs.bp.moduleUuid===void 0?{}:{moduleUuid:e.packs.bp.moduleUuid},name:e.packs.bp.name,include:e.packs.bp.include}),e.packs.rp&&t.push({type:`rp`,root:e.packs.rp.root,uuid:e.packs.rp.uuid,moduleUuid:e.packs.rp.moduleUuid,name:e.packs.rp.name,include:e.packs.rp.include}),t}const Dt=[`scripts`,`manifest.json`,`animation_controllers`,`animations`,`biomes`,`blocks`,`cameras`,`dialogue`,`entities`,`functions`,`items`,`loot_tables`,`pack_icon.png`,`recipes`,`shapes`,`spawn_rules`,`structures`,`texts`,`trading`,`feature_rules`,`features`,`worldgen`],Ot=[];function kt(e,t){return s.isAbsolute(t)?t:s.join(e,t)}function H(e){return e.replace(/\\/g,`/`)}function U(e,t){return kt(e,t.root)}function W(e,t,n){return n===`bp`?t.packs.bp?kt(e,t.packs.bp.root):void 0:t.packs.rp?kt(e,t.packs.rp.root):void 0}function At(e,t){let n=W(U(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function jt(e,t){let n=W(U(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function Mt(e){return!!e.packs.bp?.compile}function Nt(e,t){if(t.packs.bp?.compile)return kt(U(e,t),t.packs.bp.compile.entry)}function Pt(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return s.join(At(e,t),n)}function Ft(e,t){let n=Pt(e,t);if(!n)return;if(!t.packs.bp?.compile)return s.join(n,`main.js`);let r=s.basename(t.packs.bp.compile.entry,s.extname(t.packs.bp.compile.entry));return s.join(n,`${r}.js`)}function It(e,t){let n=s.relative(e,t);return n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n)}function Lt(e,t,n){if(!t||t===`.`)throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a non-empty relative path strictly inside the BP root. Got: "${t}". This directory will be emptied during build.`);let r=t.replace(/\\/g,`/`);if(s.posix.isAbsolute(r)||s.win32.isAbsolute(r))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a relative path, not absolute. Got: "${t}". This directory will be emptied during build.`);let i=s.posix.normalize(r);if(i.split(`/`).includes(`..`))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must not contain ".." (path escape). Got: "${t}" resolves outside the BP root. This directory will be emptied during build.`);let a=s.resolve(e,i),o=s.relative(e,a);if(!o||o.startsWith(`..`)||s.isAbsolute(o))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir must be a directory strictly inside the BP root. Value: "${t}", resolved: "${a}". This directory will be emptied during build and must not be the BP root or a path outside it.`);if(n&&It(a,n))throw new L(`CONFIG_INVALID`,`compile.scriptOutputDir "${t}" dangerously overlaps with the source entry directory. The output directory will be emptied during build and would delete source files.`);return H(o)}function Rt(e,t,n,r=[]){let a=s.resolve(e),o=s.resolve(t),c=[o,...r.map(e=>s.resolve(e))];for(let t of c)if(It(a,t))throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" would overwrite a protected path ("${t}"). Refusing to empty this directory.`);try{if(!i(a).isDirectory())throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not a directory. Refusing to empty a non-directory path.`)}catch(e){if(e?.code!==`ENOENT`)throw e}let l=s.relative(o,a);if(!l||l.startsWith(`..`)||s.isAbsolute(l))throw new L(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not inside the BP root "${t}". Refusing to empty this directory.`)}function zt(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...Dt.filter(e=>e!==`scripts`)],n=e.packs.bp?.include??[],r=[...t,...n],i=/* @__PURE__ */ new Set;return r.filter(e=>!i.has(e)&&(i.add(e),!0))}function Bt(e,t){if(t.packs.bp)return s.join(At(e,t),`manifest.json`)}function Vt(e,t){if(t.packs.rp)return s.join(jt(e,t),`manifest.json`)}function Ht(e,t){return kt(U(e,t),t.pack.outDir)}const Ut=f()!==`win32`;function Wt(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=H(s.resolve(e)),r=Ut?n:n.toLowerCase();return!t.has(r)&&(t.add(r),!0)})}const Gt={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function Kt(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function qt(e){let t=Kt(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,Gt[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[p(r,{delimiters:[``,``]})]}function Jt(e){return{values:e?.values??{},builtins:{VERSION:e?.builtins?.VERSION??!1,NAME:e?.builtins?.NAME??!1,UUID:e?.builtins?.UUID??!1,DESCRIPTION:e?.builtins?.DESCRIPTION??!1}}}function Yt(e){let t={...e??{}};for(let[e,n]of Object.entries(t))try{Function(`return (${n});`)}catch{throw new L(`CONFIG_INVALID`,`packs.bp.compile.define["${e}"] is not a valid JavaScript expression: ${n}. Define values must be expression strings, e.g. JSON.stringify("server") or "true".`,{details:{defineKey:e,defineValue:n}})}return t}function Xt(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}const Zt=`tsc --noEmit`;function Qt(e){let t=[],n=``,r,i=!1;for(let a=0;a<e.length;a+=1){let o=e[a];if(r){o===r?r=void 0:o===`\\`&&e[a+1]===r?(a+=1,n+=r):n+=o;continue}if(o===`"`||o===`'`){r=o,i=!0;continue}if(o===`\\`&&(e[a+1]===`"`||e[a+1]===`'`)){a+=1,n+=e[a],i=!0;continue}if(/\s/.test(o)){i&&=(t.push(n),n=``,!1);continue}n+=o,i=!0}if(r)throw new L(`CONFIG_INVALID`,`Unterminated ${r===`"`?`double`:`single`} quote in typecheck command: ${e}`);return i&&t.push(n),t}function $t(e,t=[],n={}){let r=typeof e==`string`?e.trim():``;if(r===``){let e=[...Qt(Zt)],r=e.shift(),i=[...en(e,n),...t];return n.useNpx?{command:`npx`,args:[r,...i],label:`npx tsc --noEmit`,isDefault:!0}:{command:r,args:i,label:Zt,isDefault:!0}}let i=Qt(r),a=i[0];if(!a)throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${JSON.stringify(e)}`);return{command:a,args:[...i.slice(1),...t],label:r,isDefault:!1}}function en(e,t){let n=[...e];return t.tsconfigPath&&n.push(`--project`,t.tsconfigPath),t.incremental&&t.tsBuildInfoFile&&n.push(`--incremental`,`--tsBuildInfoFile`,t.tsBuildInfoFile),n}function tn(e){return[e.command,...e.args].map(e=>/\s/.test(e)?JSON.stringify(e):e).join(` `)}function nn(e,t){if(e===void 0||typeof e==`boolean`)return{typecheck:e??t.typecheck,...t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand},typecheckArgs:t.typecheckArgs??[]};if(typeof e!=`object`||!e||Array.isArray(e))throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck must be a boolean or an object { enabled?, command?, args? }, got: ${sn(e)}.`);on(e);let{enabled:n,command:r,args:i}=e;if(n!==void 0&&typeof n!=`boolean`)throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck.enabled must be a boolean, got: ${sn(n)}.`);if(r!==void 0&&typeof r!=`string`)throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a string, got: ${sn(r)}.`);if(typeof r==`string`&&r.trim()===``)throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck.command must be a non-empty command line, got: ${sn(r)}.`);let a=rn(i,`packs.bp.compile.typecheck.args`);return{typecheck:n??t.typecheck,...r===void 0?t.typecheckCommand===void 0?{}:{typecheckCommand:t.typecheckCommand}:{typecheckCommand:r},typecheckArgs:a??t.typecheckArgs??[]}}function rn(e,t){if(e!==void 0){if(!Array.isArray(e))throw new L(`CONFIG_INVALID`,`${t} must be an array of strings, got: ${sn(e)}.`);return e.map(e=>{if(typeof e!=`string`)throw new L(`CONFIG_INVALID`,`${t} entries must be strings, got: ${sn(e)}.`);return e})}}function an(e,t){if(e!==void 0){if(typeof e!=`string`||e.trim()===``)throw new L(`CONFIG_INVALID`,`${t} must be a non-empty command line string, got: ${sn(e)}.`);return e.trim()}}function on(e){let t=e;if(t.typechecker!==void 0)throw new L(`CONFIG_INVALID`,`packs.bp.compile.typecheck.typechecker was replaced by packs.bp.compile.typecheck.command: write the full command line instead, e.g. { command: "bun check" }, got: ${sn(t.typechecker)}.`)}function sn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}const cn=[Qe,$e,nt,{name:`exact-version`,match:e=>Re(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Ue(e.specifier),manifestVersion:e.specifier}}}];var ln=class e{resolvers;pluginNames=/* @__PURE__ */ new Map;constructor(e,t=[]){this.resolvers=e;for(let e of t)for(let t of e.install?.dependencyResolvers??[])this.pluginNames.set(t,e.name)}static fromConfig(t,n=[]){return new e([...t,...cn],n)}resolverMatchesCatalog(e,t){let n=e.entry.resolver;if(!n)return!0;let r=typeof n==`string`?n:n.name;return t.resolver===void 0||t.resolver===r}find(e){let t;for(let n of this.resolvers)if(this.resolverMatchesCatalog(e,n))try{if(n.match(e)){t=n;break}}catch(e){let t=this.pluginNames.get(n);throw t?new L(`PLUGIN_FAILED`,`Plugin ${t} resolver ${n.name} match failed: ${e instanceof Error?e.message:String(e)}`):e}if(!t)throw new L(`DEPENDENCY_VERSION_INVALID`,`${e.packageName} dependency version is invalid: ${e.specifier}`,{details:{package:e.packageName,specifier:e.specifier,resolver:e.entry.resolver}});return e.logger?.verbose(`Resolving ${e.packageName}@${e.specifier} with ${t.name}`),t}async resolve(e){let t=this.find(e);try{return await t.resolve(e)}catch(e){let n=this.pluginNames.get(t);throw n?new L(`PLUGIN_FAILED`,`Plugin ${n} resolver ${t.name} failed: ${e instanceof Error?e.message:String(e)}`):e}}};const un=`sapi-pro`,dn=[`@minecraft/server`,`@minecraft/server-ui`];function fn(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function pn(e){return fn(e)?`beta`:`stable`}function mn(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function hn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function gn(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...at,...e.config.install.dependencyCatalog},o=ln.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==vn),e.config.plugins);for(let[s,c]of Object.entries(t)){if(!s.startsWith(`@minecraft/`))continue;let t=i[s],l=a[s];if(!l)return r.add(s),!1;if(!t){if((l.manifest??!1)===!1)continue;return r.add(s),!1}let u;if(n.has(s)?u=n.get(s):(u=await o.resolve({packageName:s,specifier:t,target:e.target,entry:l,config:e.config,npm:e.npm,...e.logger?{logger:e.logger}:{}}),n.set(s,u)),!u||dn.includes(s)&&fn(c)!==fn(u.packageVersion)||!He(u.packageVersion,c))return!1}return!0}function _n(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!mn(e))return!1;let r=hn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>B(e,t)).reverse()}const vn={name:`sapi-pro`,resolver:`sapi-pro`,match:e=>e.specifier===`stable`||e.specifier===`beta`||/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(e.specifier),async resolve(e){let t=await e.npm.metadata(un),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set;for(let[i,a]of _n(t.versions??{},e.specifier))if(await gn(e,hn(a),n,r))return/^0\.3\./.test(i)&&e.logger?.warn(`sapi-pro@${i} uses legacy metadata; compatibility is best-effort only.`),{packageVersion:i,manifestVersion:null};throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot find a compatible ${un}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:un,specifier:e.specifier,target:e.target},suggestions:[`Explicitly declare the @minecraft packages required by sapi-pro.`,`Use a compatible target or specify an exact sapi-pro version.`]})}};function yn(){return{name:`sapi-pro`,apiVersion:1,description:`Resolve sapi-pro versions compatible with BePack Script API dependencies.`,configResolved:({config:e})=>{let t=e.packs.bp?.dependencies??{},n=t[un];if(!n)return;let r=dn.filter(e=>!t[e]);if(r.length>0)throw Error(`sapi-pro requires explicit dependencies: ${r.join(`, `)}.`);if(n===`stable`||n===`beta`)for(let e of dn){let r=t[e];if(pn(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[un]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[vn]}}}const bn={"sapi-pro":yn};function xn(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function Sn(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e==`function`?`function`:typeof e==`object`?`object`:typeof e==`string`?JSON.stringify(e):String(e)}function Cn(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...xn(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...xn(t.packs?.rp)});let r={...e.copy?.targets??{},...xn(t.copy?.targets)},i=xn(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...xn(t.install)},build:{...e.build,...xn(t.build)},dev:{...e.dev,...xn(t.dev)},copy:{...e.copy,...xn(t.copy),targets:r},pack:{...e.pack,...xn(t.pack)},hooks:{...e.hooks,...xn(t.hooks)}}}function wn(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=bn[e];if(!t)throw new L(`CONFIG_INVALID`,`Unknown built-in plugin: ${e}.`);return t()}),n=/* @__PURE__ */ new Set;for(let e of t){if(!e?.name||e.name.trim()===``)throw new L(`CONFIG_INVALID`,`Every plugin must have a non-empty name.`);if(n.has(e.name))throw new L(`CONFIG_INVALID`,`Plugin name is duplicated: ${e.name}.`);if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new L(`CONFIG_INVALID`,`Plugin ${e.name} requires unsupported BePack plugin API version ${e.apiVersion}.`);if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new L(`CONFIG_INVALID`,`Plugin ${e.name} priority must be a finite number.`);n.add(e.name)}return t.sort((e,t)=>(t.priority??0)-(e.priority??0))}function Tn(e,t){let n=/* @__PURE__ */ new Set;for(let r of[...e.map(e=>e.hooks),t])for(let e of Object.keys(r??{}))n.add(e);return Object.fromEntries([...n].map(n=>{let r=[...e.map(e=>({plugin:e,hook:e.hooks?.[n]})).filter(e=>e.hook!==void 0),...t?.[n]?[{hook:t[n]}]:[]];return[n,async(...e)=>{let t;for(let i of r)try{t=await i.hook(...e)}catch(e){let t=`plugin`in i?i.plugin:void 0;throw t?new L(`PLUGIN_FAILED`,`Plugin ${t.name} ${String(n)} hook failed: ${e instanceof Error?e.message:String(e)}`):e}return t}]}))}function En(e,t){let n={},r=/* @__PURE__ */ new Map,i=[];for(let t of e)for(let[e,a]of Object.entries(t.install?.dependencyCatalog??{})){let o=r.get(e);if(o){i.push(`dependency catalog ${e}: plugin ${o} takes precedence over plugin ${t.name}`);continue}n[e]=a,r.set(e,t.name)}for(let[e,a]of Object.entries(t)){let t=r.get(e);t&&i.push(`dependency catalog ${e}: project config overrides plugin ${t}`),n[e]=a}return{catalog:n,diagnostics:i}}function Dn(e,t,n){let r=wt,i=e?.scriptOutputDir??r.scriptOutputDir,a=s.resolve(n,e?.entry??r.entry),o=Lt(t,i,s.dirname(a)),c=an(e?.typecheckCommand,`packs.bp.compile.typecheckCommand`)??r.typecheckCommand,l=rn(e?.typecheckArgs,`packs.bp.compile.typecheckArgs`),u=nn(e?.typecheck,{typecheck:r.typecheck,...c===void 0?{}:{typecheckCommand:c},...l===void 0?{}:{typecheckArgs:l}});return{entry:e?.entry??r.entry,define:Yt(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:u.typecheck,typecheckArgs:u.typecheckArgs,...u.typecheckCommand===void 0?{}:{typecheckCommand:u.typecheckCommand},preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:p(e?.cache),scriptOutputDir:o,...e?.rolldown===void 0?{}:{rolldown:d(e.rolldown)},...e?.rolldownConfig===void 0?{}:{rolldownConfig:f(e.rolldownConfig)}};function d(e){if(typeof e==`function`||e&&typeof e==`object`&&!Array.isArray(e))return e;throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown must be a rolldown options object or a function (options, context) => options, got: ${Sn(e)}.`)}function f(e){if(typeof e!=`string`||e.trim()===``)throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldownConfig must be a non-empty path string, got: ${Sn(e)}.`);return e}function p(e){let t=St;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function On(e){if(e===void 0||e===!1)return;let t=e===!0?{}:e;if(typeof t!=`object`||!t||Array.isArray(t))throw new L(`CONFIG_INVALID`,`pack.optimize must be a boolean or an options object, got: ${Sn(e)}.`);let n=t.packOptimizationVersion;if(n!==void 0&&(typeof n!=`string`||n.trim()===``))throw new L(`CONFIG_INVALID`,`pack.optimize.packOptimizationVersion must be a non-empty string, got: ${Sn(n)}.`);return{keepLooseFiles:t.keepLooseFiles??Ct.keepLooseFiles,keepLoose:t.keepLoose!==!1&&(t.keepLoose??[]).map(kn),exclude:(t.exclude??[]).map(kn),minifyJson:t.minifyJson??Ct.minifyJson,packOptimizationVersion:n??Ct.packOptimizationVersion,allowUnsupportedTarget:t.allowUnsupportedTarget??Ct.allowUnsupportedTarget}}function kn(e){let t=String(e).replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(!t||t.includes(`/`)||t.includes(`..`)||s.posix.isAbsolute(t))throw new L(`CONFIG_INVALID`,`pack.optimize.exclude entries must be top-level folder names (no path separators, no ".."), got: ${Sn(e)}.`);return t}function An(e){let t=e?.merge??`preserve`;if(t!==`preserve`&&t!==`clean`)throw new L(`CONFIG_INVALID`,`manifest.merge must be "preserve" or "clean", got: ${String(e?.merge)}.`);let n=e?.minEngineVersion;if(n!==void 0&&!/^\d+\.\d+\.\d+$/.test(n))throw new L(`CONFIG_INVALID`,`manifest.minEngineVersion must be a SemVer string like "1.21.0", got: ${n}.`);return{merge:t,...n===void 0?{}:{minEngineVersion:n},extraDependencies:e?.extraDependencies??[],extraModules:e?.extraModules??[],extraHeader:e?.extraHeader??{}}}function jn(e,t={},n=process.cwd()){let r=Cn(e,t),i=wn(r.plugins),a=r.target??V.target;if(a===`stable`||a===`beta`)throw new L(`TARGET_INVALID`,`target must be a Minecraft game version or latest, not a Script API channel.`,{details:{target:a}});let o=!!r.packs?.bp,c=!!r.packs?.rp;if(!o&&!c)throw new L(`CONFIG_INVALID`,`At least one pack (packs.bp or packs.rp) is required.`);if(!r.name||r.name.trim()===``)throw new L(`CONFIG_INVALID`,`name is required.`);let l=r.name,u=r.version??V.version,d=r.description,f=r.packs,p=f.bp?.compile,m=f.bp,h=f.rp;if(m){if(!m.uuid)throw new L(`CONFIG_INVALID`,`packs.bp.uuid is required.`);if(m.compile&&!m.moduleUuid)throw new L(`CONFIG_INVALID`,`packs.bp.moduleUuid is required when packs.bp.compile is configured.`);if(m.root===void 0)throw new L(`CONFIG_INVALID`,`packs.bp.root is required. Set the behavior pack directory in bepack.config.ts.`);if(p?.define){let e=Object.keys(r.replace?.values??{}),t=Object.keys(p.define),n=e.filter(e=>t.includes(e));if(n.length>0)throw new L(`CONFIG_INVALID`,`Config conflict: ${n.map(e=>`"${e}"`).join(`, `)} is configured in both replace.values and packs.bp.compile.define. Use only one mechanism per key.`,{details:{overlap:n}})}}let g=s.resolve(n,r.root??`.`),_=m?s.resolve(g,m.root):void 0;if(h){if(!h.uuid||!h.moduleUuid)throw new L(`CONFIG_INVALID`,`packs.rp.uuid and packs.rp.moduleUuid are required.`);if(h.root===void 0)throw new L(`CONFIG_INVALID`,`packs.rp.root is required when packs.rp is configured.`);if(h.packScope!==void 0&&!Tt.includes(h.packScope))throw new L(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${Tt.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=En(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]),C=On(r.pack?.optimize),w=On(r.copy?.optimize);return{root:r.root??V.root,configured:{root:r.root!==void 0,packOutDir:r.pack?.outDir!==void 0},name:l,version:u,...d===void 0?{}:{description:d},replace:Jt(r.replace),target:a,plugins:i,...x.length>0?{pluginDiagnostics:x}:{},...r.manifestFormat===void 0?{}:{manifestFormat:r.manifestFormat},packs:{...m?{bp:{root:m.root,uuid:m.uuid,...m.moduleUuid===void 0?{}:{moduleUuid:m.moduleUuid},name:m.name??l,...v===void 0?{}:{description:v},...p&&_?{compile:Dn(p,_,g)}:{},manifest:An(m.manifest),dependencies:m.dependencies??{},...m.achievement===void 0?{}:{achievement:m.achievement},include:m.include??[]}}:{},...h?{rp:{root:h.root,uuid:h.uuid,moduleUuid:h.moduleUuid,name:h.name??l,...y===void 0?{}:{description:y},manifest:An(h.manifest),...h.pbr===void 0?{}:{pbr:h.pbr},...h.packScope===void 0?{}:{packScope:h.packScope},include:h.include??[]}}:{}},install:{registry:r.install?.registry??V.install.registry,saveTo:r.install?.saveTo??V.install.saveTo,packageManager:r.install?.packageManager??V.install.packageManager,runPackageManager:r.install?.runPackageManager??V.install.runPackageManager,updatePackageJson:r.install?.updatePackageJson??V.install.updatePackageJson,updateManifest:r.install?.updateManifest??V.install.updateManifest,dependencyCatalog:b,dependencyResolvers:[...S,...r.install?.dependencyResolvers??[]]},build:{copy:r.build?.copy??V.build.copy,timing:r.build?.timing??V.build.timing},dev:{copy:r.dev?.copy??V.dev.copy,...r.dev?.watch?{watch:r.dev.watch}:{}},copy:{defaultTarget:r.copy?.defaultTarget??V.copy.defaultTarget,...r.copy?.name?{name:r.copy.name}:{},...r.copy?.include?{include:r.copy.include}:{},targets:r.copy?.targets??{},...w?{optimize:w}:{}},pack:{name:r.pack?.name??V.pack.name,outDir:r.pack?.outDir??V.pack.outDir,...C?{optimize:C}:{}},hooks:Tn(i,r.hooks)}}async function Mn(e,t){if(t){let r=kt(e,t);return await n.access(r).catch(()=>{throw new L(`CONFIG_NOT_FOUND`,`Config not found: ${t}`,{details:{configPath:t}})}),r}for(let t of xt){let r=s.join(e,t);try{return await n.access(r),r}catch{}}throw new L(`CONFIG_NOT_FOUND`,`No bepack.config.ts, bepack.config.mjs, or bepack.config.js found.`,{details:{cwd:e}})}async function Nn(e){try{if(e.endsWith(`.ts`))try{return await import(`${o(e).href}?t=${Date.now()}`)}catch{let t=Pn(await n.readFile(e,`utf8`));return await import(`data:text/javascript;base64,${Buffer.from(t,`utf8`).toString(`base64`)}`)}return await import(`${o(e).href}?t=${Date.now()}`)}catch(t){throw new L(`CONFIG_INVALID`,`Failed to load config: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Use bepack.config.mjs/js for complex config logic.`,`Keep bepack.config.ts free of TypeScript-only runtime syntax.`]})}}function Pn(e){return e.replace(/^\s*import\s+type\s+[^;]+;\s*$/gm,``).replace(/\s+satisfies\s+[A-Za-z_$][\w$<>,\s.[\]|&{}]*/g,``).replace(/\((\s*[A-Za-z_$][\w$]*)\s*:\s*[^)=]+?\)\s*=>/g,`($1) =>`)}async function Fn(e,t){for(let n of e.plugins??[])if(n.configResolved)try{await n.configResolved({cwd:t,config:e})}catch(e){throw new L(`PLUGIN_FAILED`,`Plugin ${n.name} configResolved hook failed: ${e instanceof Error?e.message:String(e)}`)}}async function In(e){let t=s.resolve(e.cwd),n=await Mn(t,e.configPath),r=await Nn(n);if(r.default===void 0)throw new L(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=jn(r.default,e.overrides,t);return await Fn(i,t),{config:i,path:n,cwd:t}}function Ln(e){return{...at,...e.install.dependencyCatalog}}function Rn(e,t){let n=e[t];if(!n)throw new L(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency. Add it to install.dependencyCatalog or remove it from packs.bp.dependencies.`,{details:{package:t}});return n}function zn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var Bn=class{registry;logger;cache=/* @__PURE__ */ new Map;constructor(e,t){this.registry=e,this.logger=t}async metadata(e){let t=this.packageUrl(e),n=this.cache.get(t);if(n)return this.logger?.verbose(`Using cached metadata for ${e}`),n;zn(this.logger,`fetching ${e} metadata from ${this.registry}`);let r=await fetch(t);if(!r.ok)throw new L(`SAPI_VERSION_NOT_FOUND`,`Cannot fetch ${e} versions from registry.`,{details:{package:e,registry:this.registry,status:r.status}});let i=await r.json();return this.cache.set(t,i),this.logger?.verbose(`Fetched ${e} metadata (${Object.keys(i.versions??{}).length} versions)`),i}versions(e){return Object.keys(e.versions??{})}async versionsOf(e){return this.versions(await this.metadata(e))}distTag(e,t){let n=e[`dist-tags`]?.[t];return n&&e.versions?.[n]?n:void 0}packageUrl(e){return`${this.registry.replace(/\/$/,``)}/${encodeURIComponent(e).replace(/^%40/,`@`)}`}};function Vn(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var Hn=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new Bn(e.install.registry,t),this.catalog=Ln(e),this.pkgResolver=new Ke(this.npm,t),this.log=Vn(t)}async resolveAll(){let e={},t=this.config.packs.bp?.dependencies;if(!t||Object.keys(t).length===0)return this.log(`no BP dependencies to resolve`),e;this.log(`resolving dependencies for target ${this.config.target}`);for(let[n,r]of Object.entries(t)){let t=Rn(this.catalog,n),i=await this.resolveOne(n,r,t),a=t.manifest??!1;e[n]={specifier:r,packageVersion:i.packageVersion,manifestVersion:a?i.manifestVersion??i.packageVersion:null,manifest:a,external:a,resolver:typeof t.resolver==`string`?t.resolver:t.resolver.name},this.log(`${n}: ${r} -> package ${e[n].packageVersion}, manifest ${e[n].manifestVersion}`)}return this.logger?.verbose(`Dependency resolution complete`),e}async resolveOne(e,t,n){let r={packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config};await this.runDependencyHooks(`beforeResolveDependency`,r);let i=await ln.fromConfig(this.config.install.dependencyResolvers,this.config.plugins??[]).resolve({packageName:e,specifier:t,target:this.config.target,entry:n,config:this.config,npm:this.npm,...this.logger?{logger:this.logger}:{}});return await this.runDependencyHooks(`afterResolveDependency`,{...r,result:i}),i}async runDependencyHooks(e,t){for(let n of this.config.plugins??[]){let r=n.install?.hooks?.[e];if(r)try{await r(t)}catch(t){throw new L(`PLUGIN_FAILED`,`Plugin ${n.name} ${e} hook failed: ${t instanceof Error?t.message:String(t)}`)}}}};async function Un(e,t,n,r=!1){let i=s.join(e,`package.json`);if(!await I(i))throw new L(`PACKAGE_JSON_NOT_FOUND`,`package.json not found.`,{details:{cwd:e}});let a=await Ce(i),o=t.install.saveTo;a.dependencies=a.dependencies??{},a.devDependencies=a.devDependencies??{};for(let e of Object.keys(n))delete a.dependencies[e],delete a.devDependencies[e];a[o]=a[o]??{};for(let[e,t]of Object.entries(n))a[o][e]=t.packageVersion;return Object.keys(a.dependencies).length||delete a.dependencies,Object.keys(a.devDependencies).length||delete a.devDependencies,r||await we(i,a),{updated:!0,path:`package.json`}}const Wn=[1,21,0],Gn=[1,0,0];var Kn=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=Le(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Ne(e);this.depManager.validateBpDependencies();let r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanBp(t,r):this.buildPreserveBp(n,t,r);return this.applyAchievementMetadata(i,t),i}buildRp(e){let t=this.requireRp(),n=Ne(e),r=this.getWriteFormatVersion(n),i=t.manifest.merge===`clean`?this.buildCleanRp(t,r):this.buildPreserveRp(n,t,r);return this.applyPbrCapability(i,t),i}buildPreserveBp(e,t,n){return{...e,format_version:n,header:this.buildBpHeader(e,t,n),...t.moduleUuid?{modules:this.replaceManagedBpModules(e.modules,t,n)}:e.modules?{modules:e.modules}:{},dependencies:this.depManager.replaceBpDependencies(e.dependencies,this.config.packs.rp?.uuid,n)}}buildPreserveRp(e,t,n){return{...e,format_version:n,header:this.buildRpHeader(e,t,n),modules:this.replaceManagedRpModules(e.modules,t,n),dependencies:this.depManager.replaceRpDependencies(e.dependencies,this.config.packs.bp?.uuid,n)}}buildCleanBp(e,t){return{format_version:t,header:this.buildBpHeaderClean(e,t),...e.moduleUuid?{modules:this.buildCleanBpModules(e,t)}:{},dependencies:this.depManager.buildBpDependenciesClean(t,this.config.packs.rp?.uuid,e.manifest.extraDependencies)}}buildCleanRp(e,t){return{format_version:t,header:this.buildRpHeaderClean(e,t),modules:this.buildCleanRpModules(e,t),dependencies:this.depManager.buildRpDependenciesClean(t,this.config.packs.bp?.uuid,e.manifest.extraDependencies)}}buildBpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildRpHeaderClean(e,t){return{...e.manifest.extraHeader,name:e.name,...e.description===void 0?{}:{description:e.description},uuid:e.uuid,...e.packScope===void 0?{}:{pack_scope:e.packScope},version:this.getVersionFor(t),min_engine_version:e.manifest.minEngineVersion===void 0?this.defaultMinEngineVersion(t):this.configMinEngineVersion(e.manifest.minEngineVersion,t)}}buildCleanBpModules(e,t){return[...e.moduleUuid?[this.createScriptModule(e,t)]:[],...e.manifest.extraModules]}buildCleanRpModules(e,t){return[this.createResourcesModule(e,t),...e.manifest.extraModules]}buildBpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}buildRpHeader(e,t,n){return{...e.header??{},name:t.name,...t.description===void 0?{}:{description:t.description},uuid:t.uuid,...t.packScope===void 0?{}:{pack_scope:t.packScope},version:this.getVersionFor(n),min_engine_version:this.normalizeMinEngineVersion(e.header?.min_engine_version,n,t.manifest.minEngineVersion)}}getScriptEntry(){let e=this.config.packs.bp?.compile;return e?`${e.scriptOutputDir}/${s.basename(e.entry,s.extname(e.entry))}.js`:`scripts/main.js`}isManagedBpModule(e,t){if(e.type!==`script`||e.language!==`javascript`)return!1;let n=this.getScriptEntry();return e.uuid===t.moduleUuid||e.entry===n}isManagedRpModule(e,t){return e.type===`resources`&&e.uuid===t.moduleUuid}createScriptModule(e,t){return{type:`script`,language:`javascript`,uuid:e.moduleUuid,version:this.getModuleVersion(t),entry:this.getScriptEntry()}}createResourcesModule(e,t){return{type:`resources`,uuid:e.moduleUuid,version:this.getModuleVersion(t)}}replaceManagedBpModules(e,t,n){return[...Pe(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Pe(e).filter(e=>!this.isManagedRpModule(e,t)),this.createResourcesModule(t,n)]}applyAchievementMetadata(e,t){if(t.achievement===!0)e.metadata={...e.metadata??{},product_type:`addon`};else if(t.achievement===!1&&e.metadata){let t={...e.metadata};delete t.product_type;let n=Fe(t);n?e.metadata=n:delete e.metadata}}applyPbrCapability(e,t){if(t.pbr===!0){let t=Pe(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Pe(e.capabilities).filter(e=>e!==`pbr`);t.length>0?e.capabilities=t:delete e.capabilities}}getVersionFor(e){return e===3?this.versionStr:this.version}getModuleVersion(e){return e===3?`1.0.0`:Gn}getWriteFormatVersion(e){return this.config.manifestFormat===void 0?e.format_version??2:this.config.manifestFormat}normalizeMinEngineVersion(e,t,n){if(n!==void 0)return this.configMinEngineVersion(n,t);if(e==null)return this.defaultMinEngineVersion(t);if(Array.isArray(e))return t===3?e.join(`.`):e;if(typeof e==`string`){if(t===2){let t=this.stringToVersionTuple(e);if(t)return t}return e}return this.defaultMinEngineVersion(t)}configMinEngineVersion(e,t){return t===3?e:this.stringToVersionTuple(e)??this.defaultMinEngineVersion(t)}defaultMinEngineVersion(e){return e===3?`1.21.0`:Wn}stringToVersionTuple(e){let t=e.split(`.`).map(Number);if(t.length===3&&t.every(e=>!Number.isNaN(e)))return t}requireBp(){if(!this.config.packs.bp)throw new L(`CONFIG_INVALID`,`packs.bp is required to build the BP manifest.`);return this.config.packs.bp}requireRp(){if(!this.config.packs.rp)throw new L(`CONFIG_INVALID`,`packs.rp is required to build the RP manifest.`);return this.config.packs.rp}},qn=class e{config;catalog;installVersions;manifestVersions;version;versionStr;dependencyDiagnostics=[];constructor(e,t,n={}){this.config=e,this.catalog=t,this.installVersions=n.install??{},this.manifestVersions=n.manifest??{},this.version=Le(e.version),this.versionStr=e.version}static isAllowedSpecifier(e){return e===`stable`||e===`beta`||e===`preview`||/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}static resolveVersion(t){return e.resolveVersionDetail(t).version}static resolveVersionDetail(e){let{specifier:t,target:n,resolvedVersion:r,manifestVersion:i}=e;if(t===`stable`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,"Run `bepack install` to resolve stable manifest dependencies.",{details:{specifier:t,target:n}})}if(t===`beta`){if(ze(n))return{version:`beta`,source:`config`};if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve manifest dependencies for target ${n}.`,{details:{target:n}})}if(t===`preview`){if(r)return{version:r,source:`install`};if(i)return{version:i,source:`manifest`};throw new L(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve preview manifest dependencies for target ${n}.`,{details:{specifier:t,target:n}})}return{version:t,source:`config`}}static isAchievementCompatible(e){return e!==`beta`&&e!==`preview`}validateBpDependencies(){if(this.config.packs.bp){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[t]){let e=Object.keys(this.catalog),n=e.length>0?[`Managed packages: ${e.join(`, `)}.`,`Add a missing package to install.dependencyCatalog, or remove it from packs.bp.dependencies.`]:[`No managed packages are available. Extend install.dependencyCatalog to add one.`];throw new L(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency.`,{details:{package:t},suggestions:n})}if(!e.isAllowedSpecifier(n))throw new L(`DEPENDENCY_VERSION_INVALID`,`${t} dependency version is invalid: ${n}`,{details:{package:t,specifier:n}})}if(this.config.packs.bp.achievement){for(let[t,n]of Object.entries(this.config.packs.bp.dependencies))if(!e.isAchievementCompatible(n))throw new L(`ACHIEVEMENT_REQUIRES_STABLE_API`,`${t}: achievement requires stable Script API dependencies (${n} is not allowed).`)}}}isManagedBpDependency(e){return!!(`module_name`in e&&typeof e.module_name==`string`&&this.catalog[e.module_name]?.manifest||`uuid`in e&&typeof e.uuid==`string`&&this.config.packs.rp?.uuid===e.uuid)}isManagedRpDependency(e,t){return t!==void 0&&`uuid`in e&&typeof e.uuid==`string`&&e.uuid===t}buildManagedDependencies(){if(this.dependencyDiagnostics.length=0,!this.config.packs.bp)return[];let t=[];for(let[n,r]of Object.entries(this.config.packs.bp.dependencies)){if(!this.catalog[n]?.manifest)continue;let i=e.resolveVersionDetail({specifier:r,target:this.config.target,resolvedVersion:this.installVersions[n],manifestVersion:this.manifestVersions[n]});t.push({module_name:n,version:i.version}),this.dependencyDiagnostics.push({name:n,specifier:r,version:i.version,source:i.source})}return t}getDependencyDiagnostics(){return this.dependencyDiagnostics}getFormatAwareVersion(e){return(e??this.config.manifestFormat??2)===3?this.versionStr:this.version}replaceBpDependencies(e,t,n){let r=Pe(e).filter(e=>!this.isManagedBpDependency(e)),i=this.buildManagedDependencies();return t&&i.push({uuid:t,version:this.getFormatAwareVersion(n)}),[...r,...i]}replaceRpDependencies(e,t,n){let r=Pe(e).filter(e=>!this.isManagedRpDependency(e,t));return t?[...r,{uuid:t,version:this.getFormatAwareVersion(n)}]:r}buildBpDependenciesClean(e,t,n){let r=this.buildManagedDependencies();return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}buildRpDependenciesClean(e,t,n){let r=[];return t&&r.push({uuid:t,version:this.getFormatAwareVersion(e)}),[...r,...n]}};const Jn=Ee.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Yn(e){let t=Ln(e.config),n=e.config.packs.bp?Bt(e.cwd,e.config):void 0,r=n?await Ie.read(n):void 0,i=Zn(r,t),a=new qn(e.config,t,{...e.resolvedDeps?{install:e.resolvedDeps}:{},manifest:i}),o=new Kn(e.config,a),c={};if(e.config.packs.bp){let t=r!==void 0;e.config.manifestFormat===2&&r?.format_version===3&&(e.logger?.warn??console.warn)(`Warning: config manifestFormat is 2, but existing manifest uses format_version 3. format_version 2 does not support string versions; any string versions in the existing manifest will be preserved as-is.`);let l=o.buildBp(r),u=a.getDependencyDiagnostics().map(e=>({module_name:e.name,specifier:e.specifier,version:e.version,source:e.source,...i[e.name]===void 0?{}:{previous:i[e.name]}}));e.dryRun||await Ie.write(n,l,`bp`),Xn(u,e.logger),c.bpManifest={path:H(s.relative(e.cwd,n)),updated:!0,existed:t,dependencies:u}}if(e.config.packs.rp){let t=Vt(e.cwd,e.config),n=await Ie.read(t),r=n!==void 0,i=o.buildRp(n);e.dryRun||await Ie.write(t,i,`rp`),c.rpManifest={path:H(s.relative(e.cwd,t)),updated:!0,existed:r}}return c}function Xn(e,t){if(t)for(let n of e){let e=Jn.cyan(n.module_name);n.previous!==void 0&&n.previous!==n.version?t.info(`manifest ${e}: ${n.previous} ${Jn.dim(`->`)} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`):n.source===`manifest`?t.info(`manifest ${e} ${n.version} ${Jn.dim(`kept from manifest`)} (specifier ${JSON.stringify(n.specifier)}) — run \`bepack install\` to refresh`):t.verbose(`manifest ${e} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`)}}function Zn(e,t){let n={};for(let r of e?.dependencies??[])`module_name`in r&&typeof r.module_name==`string`&&typeof r.version==`string`&&t[r.module_name]?.manifest&&r.version!==`stable`&&(n[r.module_name]=r.version);return n}function Qn(e){if(e==null||e===``)return`hook ran`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function $n(e,t){let n={dist:Ht(e,t)};if(t.packs.bp&&(n.bpRoot=At(e,t),n.bpManifest=Bt(e,t),Mt(t))){let r=Nt(e,t);r&&(n.srcEntry=r);let i=Ft(e,t);i&&(n.scriptOutFile=i);let a=Pt(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=jt(e,t),n.rpManifest=Vt(e,t)),n}async function G(e,t,n,r,i,a={}){let o=r.hooks[e];if(o)try{let s=await o({command:t,cwd:n,...a.mode===void 0?{}:{mode:a.mode},target:r.target,dryRun:!!a.dryRun,config:r,paths:$n(n,r),logger:i});i.hook(String(e),Qn(s))}catch(t){throw new L(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function er(e){let{command:t,logger:n,mode:r,...i}=e,a={...r===void 0?{}:{mode:r},dryRun:!!i.dryRun};await G(`beforeManifest`,t,i.cwd,i.config,n,a);let o=await Yn({...i,logger:n});return await G(`afterManifest`,t,i.cwd,i.config,n,a),o}function tr(e){let t=[],n={};for(let[r,i]of Object.entries(e)){if(r.toLowerCase()===`npm_config_allow_scripts`){t.push(r);continue}n[r]=i}return{env:n,removed:t}}var nr=class{cwd;registry;logger;constructor(e,t,n){this.cwd=e,this.registry=t,this.logger=n}async detect(e){if(e!==`auto`)return e;let t=s.join(this.cwd,`package.json`);if(await I(t)){let e=(await Ce(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await I(s.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await I(s.join(this.cwd,`yarn.lock`))?`yarn`:await I(s.join(this.cwd,`bun.lock`))||await I(s.join(this.cwd,`bun.lockb`))?`bun`:`npm`}async install(e){let{command:t,args:n}=this.commandForPlatform(e,this.installArgs(e)),{env:r,removed:i}=tr(process.env);return i.length>0&&this.logger?.warn(`Ignoring inherited ${i.join(`, `)}: npm rejects --allow-scripts for project-scoped installs. Declare allowed packages in package.json "allowScripts" or in .npmrc instead.`),await new Promise((i,a)=>{let o;try{o=m(t,n,{cwd:this.cwd,stdio:`inherit`,env:r})}catch(t){a(new L(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t instanceof Error?t.message:String(t)}}));return}o.on(`error`,t=>a(new L(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t.message}}))),o.on(`exit`,t=>{t&&t!==0?a(new L(`PACKAGE_MANAGER_FAILED`,`${e} install failed.`,{details:{manager:e,registry:this.registry,exitCode:t}})):i(t??0)})})}commandForPlatform(e,t){return process.platform===`win32`?{command:process.env.ComSpec??`cmd.exe`,args:[`/d`,`/s`,`/c`,e,...t]}:{command:e,args:t}}installArgs(e){let t=[`install`];return this.registry&&(e===`npm`||e===`pnpm`||e===`bun`||e===`yarn`)&&t.push(`--registry`,this.registry),t}};async function rr(e){let t=new z({...e,silent:e.silent||e.json}),n={target:e.target};(e.registry||e.pm||e.saveTo||e.skipPm||e.skipManifest||e.skipPackageJson)&&(n.install={...e.registry?{registry:e.registry}:{},...e.pm?{packageManager:e.pm}:{},...e.saveTo?{saveTo:e.saveTo}:{},...e.skipPm?{runPackageManager:!1}:{},...e.skipManifest?{updateManifest:!1}:{},...e.skipPackageJson?{updatePackageJson:!1}:{}});let{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await G(`beforeInstall`,`install`,r,i,t,{dryRun:!!e.dryRun});let a=await new Hn(i,t).resolveAll(),o=Object.fromEntries(Object.entries(a).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion])),s={};i.install.updatePackageJson&&(s.packageJson=await Un(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await er({cwd:r,config:i,command:`install`,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new nr(r,i.install.registry,t),l=await c.detect(i.install.packageManager),u={ran:!1,manager:l,exitCode:null};return!e.dryRun&&i.install.runPackageManager&&(t.progress(`Install`,`running ${l} install with registry ${i.install.registry}`),u={ran:!0,manager:l,exitCode:await c.install(l)}),await G(`afterInstall`,`install`,r,i,t,{dryRun:!!e.dryRun}),t.success(`Install`,`done`),{ok:!0,command:`install`,target:i.target,packageManager:l,resolved:a,files:s,packageInstall:u}}async function ir(e){let t=new z({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}}),i=await er({cwd:n,config:r,command:`manifest`,dryRun:e.dryRun,logger:t});return t.success(`Manifest`,e.dryRun?`dry-run complete`:`updated manifest.json`),{ok:!0,command:`manifest`,target:r.target,files:i}}const ar=10485760;async function or(e,t={}){let n=vr(t.command),r=t.tsconfigPath??`tsconfig.json`,i=s.resolve(e,r),a=await I(i),o=$t(t.command,t.args??[],n?{tsconfigPath:i,incremental:!!t.incremental,useNpx:!!t.useNpx,...t.tsBuildInfoFile?{tsBuildInfoFile:t.tsBuildInfoFile}:{}}:{});if(!a){if(n)throw new L(`TYPECHECK_FAILED`,`TypeScript config not found: ${r}. Create it or run build with --skip-typecheck.`,{details:{path:r,command:o.label}});t.warn?.(`TypeScript config not found: ${r} — running \`${o.label}\` anyway.`)}t.incremental&&t.tsBuildInfoFile&&n&&await _(s.dirname(t.tsBuildInfoFile),{recursive:!0});let c=tn(o),l=await dr(o.command,e);if(!l)throw new L(`TYPECHECK_FAILED`,`Cannot find ${o.command}.`,{details:{command:c,label:o.label},suggestions:_r(o)});let u=process.platform===`win32`&&/\.(cmd|bat)$/i.test(l),d=u?sr(l,o.args):l,f=u?[]:o.args,p;try{p=m(d,f,{cwd:e,windowsHide:!0,shell:u,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw new L(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e instanceof Error?e.message:String(e)},suggestions:_r(o)})}return await new Promise((e,n)=>{let r=``,i=``,a=0,s=e=>{let t=Buffer.isBuffer(e)?e:Buffer.from(String(e)),n=ar-a;return n<=0?``:t.length<=n?(a+=t.length,t.toString(`utf8`)):(a=ar,t.subarray(0,n).toString(`utf8`))};p.stdout?.on(`data`,e=>{r+=s(e),t.quiet||process.stdout.write(e)}),p.stderr?.on(`data`,e=>{i+=s(e),t.quiet||process.stderr.write(e)}),p.on(`error`,e=>{n(new L(`TYPECHECK_FAILED`,`Cannot start ${c}.`,{details:{command:c,label:o.label,cause:e.message},suggestions:_r(o)}))}),p.on(`close`,t=>{if(t===0){e();return}let a=[r.trim(),i.trim()].filter(Boolean).join(`
|
|
10
|
+
`),s=ur(a);n(new L(`TYPECHECK_FAILED`,s?`Cannot find ${o.command}.`:`${c} failed.`,{details:{command:c,label:o.label,exitCode:typeof t==`number`?t:null,...a?{diagnostics:a}:{}},...s?{suggestions:_r(o)}:{}}))})}),{...o,commandLine:c}}function sr(e,t){let n=process.platform===`win32`?cr:lr;return[e,...t].map(n).join(` `)}function cr(e){if(e===``)return`""`;if(!/[\s"&|<>^()!,;=]/.test(e))return e.replace(/%/g,`^%`);let t=`"`,n=0;for(let r of e){if(r===`\\`){n+=1;continue}if(r===`%`){t+=`\\`.repeat(n*2)+`"^%"`,n=0;continue}if(r===`"`){t+=`\\`.repeat(n*2+1)+`"`,n=0;continue}t+=`\\`.repeat(n)+r,n=0}return t+=`\\`.repeat(n*2)+`"`,t}function lr(e){return e===``?`''`:/[\s"'\\$`!*?[\]{}();&|<>~#]/.test(e)?`'${e.replace(/'/g,`'\\''`)}'`:e}function ur(e){return e.includes(`ENOENT`)||e.includes(`is not recognized`)||e.includes(`不是内部或外部命令`)||e.includes(`command not found`)}async function dr(e,t){let n=e.includes(`/`)||e.includes(`\\`);if(s.isAbsolute(e)||n){let n=s.resolve(t,e);if(await fr(n)){if(process.platform===`win32`&&!pr(n)){let e=await hr(n);if(e)return e}return n}return}let r=process.env.PATH??``,i=process.platform===`win32`?(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD`).split(`;`).filter(Boolean):[``];for(let n of r.split(s.delimiter)){let r=n?s.resolve(t,n):t,a=s.join(r,e);if((process.platform!==`win32`||s.extname(e))&&await fr(a))return a;for(let t of i){if(t&&s.extname(e))continue;let n=s.join(r,e+t);if(await fr(n))return n}}}async function fr(t){try{return await g(t,e.X_OK),!0}catch{return!1}}function pr(e){let t=s.extname(e).toLowerCase();return t===`.cmd`||t===`.bat`?!1:t!==``||!mr(e)}function mr(e){try{let t=r(e);return t.subarray(0,t.indexOf(10)).toString(`utf8`).startsWith(`#!`)}catch{return!1}}async function hr(e){let t=s.dirname(e),n=s.basename(e);for(let e of gr){let r=s.join(t,n+e);if(await fr(r))return r}}const gr=[`.cmd`,`.bat`,`.exe`];function _r(e){return[`Install the checker so \`${e.command}\` is available, or point packs.bp.compile.typecheck.command at a command you do have (for example "bun check", "tsc-rs --noEmit", "npx tsc --noEmit").`,`Run with --skip-typecheck to build without checking (the bundle is still produced).`]}function vr(e){return typeof e!=`string`||e.trim()===``}const yr=/* @__PURE__ */ new Set([`plugins`]),br=/* @__PURE__ */ new Set([`external`]),xr=/* @__PURE__ */ new Set([`output`,`resolve`,`transform`,`experimental`,`checks`,`optimization`,`watch`,`moduleTypes`]),Sr=[{key:`file`,suggestion:`The output file is derived from packs.bp.compile.entry and scriptOutputDir.`},{key:`dir`,suggestion:`The output directory is derived from packs.bp.compile.scriptOutputDir.`},{key:`format`,suggestion:`Minecraft Script API modules must be ESM, so BePack always writes format: "esm".`},{key:`preserveModules`,suggestion:`Use packs.bp.compile.preserveModules instead.`},{key:`preserveModulesRoot`,suggestion:`The modules root is always the entry file directory.`},{key:`entryFileNames`,suggestion:"Manifest script entries assume one `.js` file per source module."}];function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cr(e){return e==null||e===!1?[]:Array.isArray(e)?e:[e]}function wr(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function Tr(e,t,n){return typeof e!=`string`||typeof t!=`string`?!1:wr(s.resolve(n,e),s.resolve(n,t))}function Er(e){if(e instanceof Error){let t=e.cause;return t instanceof Error&&t.message?t.message:e.message}return String(e)}function Dr(e,t){if(typeof e==`function`||typeof t==`function`)return t;let n=[],r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let a of[...Cr(e),...Cr(t)])if(typeof a==`string`){if(r.has(a))continue;r.add(a),n.push(a)}else if(a instanceof RegExp){let e=`${a.source}/${a.flags}`;if(i.has(e))continue;i.add(e),n.push(a)}return n}function Or(e,t){if(!K(t))return t;let n=K(e)?e:{},r={...n,...t},i=K(n.define)?n.define:{};return K(t.define)&&(r.define={...i,...t.define}),r}function kr(e,t){if(!t)return{...e};let n={...e};for(let[e,r]of Object.entries(t)){if(r===void 0)continue;let t=n[e];n[e]=yr.has(e)?[...Cr(t),...Cr(r)]:br.has(e)?Dr(t,r):e===`transform`?Or(t,r):xr.has(e)&&K(t)&&K(r)?{...t,...r}:r}return n}function Ar(e){if(!e.packs.bp?.compile)return[];let t=[...e.packs.bp.compile.external],n=new Set(t.filter(e=>typeof e==`string`));for(let[r,i]of Object.entries(Ln(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function jr(e){let t=e.packs.bp?.compile;if(!t)throw new L(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);return t}function Mr(e,t){let n=jr(t),r=Nt(e,t);if(!r)throw new L(`BUILD_FAILED`,`packs.bp.compile.entry could not be resolved.`);return{input:r,external:Ar(t),plugins:qt(t),...Xt(n.define)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:n.preserveModules?`none`:`simple`}}}function Nr(e,t){let n=jr(t),r=Nt(e,t),i=Pt(e,t),a=Ft(e,t);if(!r||!i||!a)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);return n.preserveModules?{dir:i,format:`esm`,preserveModules:!0,preserveModulesRoot:s.dirname(r),entryFileNames:`[name].js`,minify:n.minify}:{file:a,format:`esm`,minify:n.minify}}function Pr(e,t){if(typeof e==`string`)return[s.resolve(t,e)];if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e.map(e=>s.resolve(t,e)).sort():void 0;if(K(e)){let n=Object.values(e);return n.every(e=>typeof e==`string`)?n.map(e=>s.resolve(t,e)).sort():void 0}}function Fr(e,t,n){if(e.input===void 0)return;let r=Pr(e.input,n),i=Pr(t.input,n);if(!(r!==void 0&&i!==void 0&&r.length===i.length&&r.every((e,t)=>wr(e,i[t]))))throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "input" — the bundle entry is managed by BePack.`,{details:{input:e.input,expected:t.input},suggestions:[`Set the entry file via packs.bp.compile.entry instead.`]})}function Ir(e,t,n){for(let{key:r,suggestion:i}of Sr){let a=e[r];if(a===void 0)continue;let o=t[r];if(!(r===`file`||r===`dir`||r===`preserveModulesRoot`?Tr(a,o,n):Object.is(a,o)||r===`preserveModules`&&o===void 0&&a===!1))throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldown cannot override "output.${r}" — it is managed by BePack.`,{details:{key:r,value:a,expected:o},suggestions:[i]})}}function Lr(e,t){if(K(e)&&e.__esModule===!0&&`default`in e)return Lr(e.default,t);if(typeof e==`function`)return e;if(Array.isArray(e)){if(e.length===0)throw new L(`CONFIG_INVALID`,`rolldown config file exports an empty array: ${t}`,{details:{file:t},suggestions:[`Export a single rolldown options object.`]});if(e.length>1)throw new L(`CONFIG_INVALID`,`rolldown config file exports ${e.length} configs, but BePack builds a single behavior pack per run: ${t}`,{details:{file:t,count:e.length},suggestions:[`Export a single rolldown options object.`]});if(!K(e[0]))throw new L(`CONFIG_INVALID`,`rolldown config file must export an options object or function: ${t}`);return e[0]}if(K(e))return e;throw new L(`CONFIG_INVALID`,`rolldown config file must default-export a rolldown options object, a function, or a single-element array: ${t}`)}async function Rr(e){if(!await I(e))throw new L(`CONFIG_INVALID`,`rolldown config file not found: ${e}`,{details:{path:e},suggestions:[`Check the path in packs.bp.compile.rolldownConfig or --rolldown-config.`]});let t;try{t=await b(e)}catch(t){throw new L(`CONFIG_INVALID`,`Failed to load rolldown config file "${e}": ${Er(t)}`)}return Lr(t,e)}async function zr(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new L(`BUILD_FAILED`,`compile.rolldown customization function failed: ${Er(e)}`)}if(r==null)return t;if(!K(r))throw new L(`CONFIG_INVALID`,`compile.rolldown customization function must return a rolldown options object (or nothing).`);return kr(t,r)}async function Br(e){let{cwd:t,config:n}=e,r=jr(n),i=U(t,n),a=Nt(t,n),o=Pt(t,n),c=Ft(t,n);if(!a||!o||!c)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);let l=Mr(t,n),u=Nr(t,n),d={command:e.command??`build`,...e.mode===void 0?{}:{mode:e.mode},target:n.target,entry:a,outDir:o,outFile:c,preserveModules:r.preserveModules},f=r.rolldown,p=e.configPath??r.rolldownConfig,m=p?await Rr(s.resolve(i,p)):void 0,h=kr(l,typeof f==`function`?void 0:f);h=kr(h,typeof m==`function`?void 0:m),typeof f==`function`&&(h=await zr(f,h,d)),typeof m==`function`&&(h=await zr(m,h,d));let{output:g,input:_,...v}=h;if(Array.isArray(g))throw new L(`CONFIG_INVALID`,"packs.bp.compile.rolldown cannot declare multiple outputs (an `output` array) — BePack writes exactly one output.",{suggestions:["Declare a single `output` object."]});if(g!==void 0&&!K(g))throw new L(`CONFIG_INVALID`,"packs.bp.compile.rolldown `output` must be an object.",{details:{output:g}});Fr({input:_},l,i);let y=kr(u,g);return Ir(y,u,i),{inputOptions:{...v,input:l.input},outputOptions:y}}function Vr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(2)} MB`}function Hr(e,n){let r=s.resolve(e),i=s.resolve(n),a=s.relative(r,i);if(!a||a.startsWith(`..`)||s.isAbsolute(a))return;try{if(t(r).isSymbolicLink())throw new L(`BUILD_FAILED`,`Safety check failed: BP root is a symbolic link or junction: "${r}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e instanceof L)throw e;if(e?.code===`ENOENT`)return;throw e}let o=r;for(let e of a.split(s.sep)){o=s.join(o,e);try{if(t(o).isSymbolicLink())throw new L(`BUILD_FAILED`,`Safety check failed: script output path contains a symbolic link: "${o}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e.code===`ENOENT`)break;throw e}}}function Ur(e,t,n){let r=s.resolve(e),i=s.resolve(t);if(It(r,i)||It(i,r))throw new L(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function Wr(e,t,n,r){let i=U(e,t),a=At(e,t),o=s.join(a,`manifest.json`),c=[s.join(i,`.git`),s.join(a,`.git`)];for(let e of c)Ur(r,e,`.git metadata`);if(t.packs.rp){let e=W(i,t,`rp`);s.resolve(e)!==s.resolve(a)&&Ur(r,e,`RP root`)}Ur(r,o,`BP manifest`);let l=s.dirname(n),u=s.relative(a,l);Rt(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!s.isAbsolute(u)?[l]:[]),Hr(a,r)}async function Gr(e,t,n,r={}){if(!Mt(t))throw new L(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let i=Nt(e,t),a=Pt(e,t),o=Ft(e,t);if(!i||!a||!o)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);try{let{inputOptions:o,outputOptions:s}=await Br({cwd:e,config:t,...r.command===void 0?{}:{command:r.command},...r.mode===void 0?{}:{mode:r.mode},...r.rolldownConfig===void 0?{}:{configPath:r.rolldownConfig}});Wr(e,t,i,a),await Se(a);let c=await y(o);try{await c.write(s)}finally{await c.close()}await Kr(a,n)}catch(e){throw e instanceof L?e:new L(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function Kr(e,t){let n=[];async function r(t){let i=await h.readdir(t,{withFileTypes:!0});for(let a of i){let i=s.join(t,a.name);if(a.isDirectory())await r(i);else if(a.isFile()&&a.name.endsWith(`.js`)){let t=await h.stat(i);n.push({path:s.relative(e,i),size:t.size})}}}if(await r(e),n.length===0)return;n.sort((e,t)=>t.size-e.size);let i=n.reduce((e,t)=>e+t.size,0);t?.rolldown(n.length===1?`${n[0].path} (${Vr(n[0].size)})`:`${n.length} files, total ${Vr(i)}`)}async function qr(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function Jr(e){let t=Date.now(),n=e.config.build.timing,r=U(e.cwd,e.config),i=Mt(e.config),a=e.command??`build`,o={...e.mode===void 0?{}:{mode:e.mode},dryRun:!!e.dryRun};await qr(`manifest`,()=>er({cwd:e.cwd,config:e.config,command:a,logger:e.logger,dryRun:!!e.dryRun,...e.mode===void 0?{}:{mode:e.mode},...e.resolvedDeps?{resolvedDeps:e.resolvedDeps}:{}}),e.logger,n);let c=[];e.config.packs.bp&&c.push(`bp`),e.config.packs.rp&&c.push(`rp`),e.logger.manifest(`manifest.json updated (${c.join(`, `)})`),await G(`beforeBuild`,a,e.cwd,e.config,e.logger,o);let l=!1,u;if(i&&!e.dryRun&&e.typecheck!==!1){let t=e.config.packs.bp.compile,i=e.cache?s.resolve(r,t.cache.file):void 0,a=e.typecheckCommand??(e.useNpx?void 0:t.typecheckCommand),o=e.typecheckCommand===void 0&&(!!e.useNpx||a===void 0&&t.useNpx),c=await qr(`typecheck`,()=>or(r,{quiet:!!e.quiet,...a===void 0?{}:{command:a},useNpx:o,args:e.typecheckCommand!==void 0||e.useNpx?[]:t.typecheckArgs,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{},warn:t=>e.logger.warn(t)}),e.logger,n);l=!0,u=c.commandLine,e.logger.typescript(`typecheck complete (${c.commandLine})`)}i&&!e.dryRun&&(await qr(`rolldown`,()=>Gr(e.cwd,e.config,e.logger,{...e.command===void 0?{}:{command:e.command},...e.mode===void 0?{}:{mode:e.mode},...e.rolldownConfig===void 0?{}:{rolldownConfig:e.rolldownConfig}}),e.logger,n),e.logger.rolldown(e.config.packs.bp.compile.preserveModules?`preserve modules build complete`:`bundle complete`)),await G(`afterBuild`,a,e.cwd,e.config,e.logger,o);let d=Date.now()-t;return{script:i?H(Ft(e.cwd,e.config)):void 0,compiled:i,typecheck:l,...u?{typecheckCommand:u}:{},durationMs:d}}async function Yr(e,t=``){let r={},i=await n.readdir(e,{withFileTypes:!0});for(let a of i){let i=s.join(e,a.name),o=t?`${t}/${a.name}`:a.name;a.isDirectory()?Object.assign(r,await Yr(i,o)):r[o]=new Uint8Array(await n.readFile(i))}return r}async function Xr(e,t){let r={};for(let i of t){let t=s.join(e,i);try{(await n.stat(t)).isDirectory()?Object.assign(r,await Yr(t,i)):r[i]=new Uint8Array(await n.readFile(t))}catch{}}return r}async function Zr(e,t){return t?await t(e):e}function Qr(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}/${r}`]=i;return n}function $r(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function ei(e,t){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0});for(let[r,i]of Object.entries(t)){let t=s.join(e,r);await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,i)}}var ti=te((()=>{}));ti();const ni=new TextEncoder;new TextDecoder;function ri(e){let t=16+e.length*256,n=0,r=[];for(let t of e){let e=ni.encode(t.name);if(e.length===0)throw new L(`PACK_FAILED`,`brarchive entry names must not be empty.`);if(e.length>247)throw new L(`PACK_FAILED`,`brarchive entry name is too long (max 247 bytes): ${t.name}`,{details:{name:t.name,bytes:e.length}});r.push(e),n+=t.data.length}let i=new Uint8Array(t+n),a=new DataView(i.buffer);a.setBigUint64(0,9018218223661903910n,!1),a.setUint32(8,e.length,!0),a.setUint32(12,1,!0);let o=0;return e.forEach((e,n)=>{let s=16+n*256,c=r[n];a.setUint8(s,c.length),i.set(c,s+1),a.setUint32(s+248,o,!0),a.setUint32(s+252,e.data.length,!0),i.set(e.data,t+o),o+=e.data.length}),i}const ii=[`functions`,`loot_tables`,`structures`,`texts`],ai=[`font`,`materials`,`sounds`,`texts`,`textures`],oi=[1,26,40],si=oi.join(`.`),ci=new TextEncoder,li=new TextDecoder,ui=new TextDecoder(`utf-16le`),di=new TextDecoder(`utf-16be`);function fi(e){if(e.length>=2){if(e[0]===255&&e[1]===254)return ui.decode(e.subarray(2));if(e[0]===254&&e[1]===255)return di.decode(e.subarray(2))}return li.decode(e)}function pi(e){return e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255)}function mi(e){return e.startsWith(``)?e.slice(1):e}function hi(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function gi(e){if(typeof e==`string`){let t=e.split(`.`).map(e=>Number.parseInt(e,10));return t.length>=3&&t.slice(0,3).every(e=>Number.isInteger(e))?[t[0],t[1],t[2]]:void 0}if(Array.isArray(e)&&e.length>=3){let t=e.slice(0,3);if(t.every(e=>typeof e==`number`&&Number.isInteger(e)))return t}}function _i(e,t){for(let n=0;n<3;n++){let r=(e[n]??0)-(t[n]??0);if(r!==0)return r}return 0}function vi(e){if(e)try{return hi(JSON.parse(mi(fi(e))))}catch{return}}function yi(e){return gi(hi(e?.header)?.min_engine_version)}function bi(e){let t=e?.modules;return Array.isArray(t)?t.some(e=>hi(e)?.type===`resources`):!1}function xi(e,t,n){if(t.allowUnsupportedTarget)return;let r=yi(e);if(r&&_i(r,oi)>=0)return;let i=r?r.join(`.`):`(not declared)`;n?.warn(`pack optimization: header.min_engine_version is ${i}, below ${si}. The archives still load on 1.26.40+, but older clients cannot read __brarchive/ and will show missing content. Set allowUnsupportedTarget: true to silence this warning.`)}function Si(e,t,n){if(!e.toLowerCase().endsWith(`.json`))return t;try{let e=JSON.parse(mi(fi(t)));return ci.encode(JSON.stringify(e))}catch(r){let i=r instanceof Error?r.message:String(r),a=pi(t)?` (UTF-16)`:``;return n?.warn(`pack optimization: could not minify ${e}${a}, storing it unchanged. ${i}. Fix the JSON to have it minified.`),t}}function Ci(e,t){if(!e)throw new L(`PACK_FAILED`,`Pack optimization needs a manifest.json to write header.pack_optimization_version into.`);let n;try{let t=hi(JSON.parse(mi(fi(e))));if(!t)throw Error(`manifest is not an object`);n=t}catch{throw new L(`PACK_FAILED`,`Cannot write header.pack_optimization_version: the pack's manifest.json is not valid JSON.`)}let r={...hi(n.header)??{}};return r.pack_optimization_version=t,n.header=r,ci.encode(JSON.stringify(n))}function wi(e,t,n,r){let i=e[`manifest.json`]??r,a=vi(i);xi(a,t,n);let o=new Set(t.exclude),s=t.keepLoose===!1?/* @__PURE__ */ new Set:/* @__PURE__ */ new Set([...bi(a)?ai:ii,...t.keepLoose]),c=/* @__PURE__ */ new Map,l={},u={},d=0,f=0;for(let r of Object.keys(e).sort()){let i=e[r],a=r.split(`/`),p=a[0];if(a.length<2||p===`__brarchive`||o.has(p)){l[r]=i;continue}let m=a.slice(0,-1).join(`/`),h=a[a.length-1],g=c.get(m)??[],_=t.keepLooseFiles||s.has(p);s.has(p)&&!t.keepLooseFiles?(g.push({name:h,data:/* @__PURE__ */ new Uint8Array}),u[r]=i,f++):(g.push({name:h,data:t.minifyJson?Si(h,i,n):i}),d++,_&&(u[r]=i)),c.set(m,g)}let p={...l,...u};for(let e of[...c.keys()].sort())p[`__brarchive/${e}.brarchive`]=ri(c.get(e));p[`manifest.json`]=Ci(i,t.packOptimizationVersion);let m=Object.keys(u).length,h=f>0?`, ${f} name-stub${f===1?``:`s`}`:``;return n?.pack(`optimized into ${c.size} archive${c.size===1?``:`s`} (${d} file${d===1?``:`s`} archived${h}, ${m} kept loose)`),$r(p)}function Ti(e,t,n){return r=>wi(r,e,t,n)}const Ei={win:()=>({type:`gameRoot`,path:s.join(`C:/Users`,d.userInfo().username,`AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang`)}),winold:()=>{let e=process.env.LOCALAPPDATA;if(!e)throw new L(`COPY_TARGET_NOT_FOUND`,`%LOCALAPPDATA% is required for winold copy target.`);return{type:`gameRoot`,path:s.join(e,`Packages`,`Microsoft.MinecraftUWP_8wekyb3d8bbwe`,`LocalState`,`games`,`com.mojang`)}}};function Di(e,t){return{type:`custom`,bp:s.join(t.path,`development_behavior_packs`),...e.packs.rp?{rp:s.join(t.path,`development_resource_packs`)}:{}}}function Oi(e,t){let n=t??e.copy.defaultTarget;if(!n)throw new L(`COPY_TARGET_NOT_FOUND`,`No copy target configured. Set copy.defaultTarget or copy.targets in bepack.config.ts, or pass --target.`,{suggestions:[`Add copy.defaultTarget to your config file.`,`Or set build.copy / dev.copy to a target name instead of true.`,`Built-in targets: win, winold.`]});let r=e.copy.targets[n]??Ei[n]?.();if(!r)throw new L(`COPY_TARGET_NOT_FOUND`,`Copy target not found: ${n}`,{details:{target:n}});let i=e.copy.targets[n]?.name,a=e.copy.name,o=e=>typeof e==`string`?{bp:e,rp:e}:e??{},s=o(i),c=o(a),l={},u=s.bp??c.bp,d=s.rp??c.rp;return u&&(l.bp=u),d&&(l.rp=d),r.type===`gameRoot`?{name:n,target:Di(e,r),names:l}:{name:n,target:r,names:l}}const ki=/* @__PURE__ */ new Set([`node_modules`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lock`,`bun.lockb`,`tsconfig.json`,...xt]);function Ai(e,t,n){let r=W(U(e,t),t,n);if(!r)return[];let i=Nt(e,t),a=[Ht(e,t),i?s.dirname(i):void 0],o=[];for(let e of a){if(!e)continue;let t=s.relative(r,e);if(!t||t.startsWith(`..`)||s.isAbsolute(t))continue;let n=t.split(s.sep)[0];n&&o.push(n)}return o}async function ji(e,t,r=[]){let i;try{i=await n.readdir(e,{withFileTypes:!0})}catch{return[]}let a=new Set(t);return i.map(e=>e.name).filter(e=>!a.has(e)).filter(e=>!e.startsWith(`.`)&&!ki.has(e)).filter(e=>!r.includes(e)).sort((e,t)=>e.localeCompare(t))}function Mi(e){return e===`bp`?`packs.bp.include`:`packs.rp.include`}async function Ni(e){let{logger:t,packType:n,root:r,items:i,action:a}=e;if(!t)return;let o=await ji(r,i,e.ignore??[]);if(o.length===0)return;let s=e.limit??8,c=o.slice(0,s).join(`, `),l=o.length>s?`, +${o.length-s} more`:``,u=n===`bp`?`behavior pack`:`resource pack`;t.warn(`${u} ${a} only includes ${i.length} configured item(s); ${o.length} entr${o.length===1?`y`:`ies`} in "${Pi(r,e.cwd)}" ${o.length===1?`is`:`are`} skipped: ${c}${l}. Add them to ${Mi(n)} to include them.`)}function Pi(e,t){if(!t)return e;let n=s.relative(t,e).replace(/\\/g,`/`);return n&&!n.startsWith(`..`)&&!s.isAbsolute(n)?n:e}ti();const Fi=Ee.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Ii(e,t,r){await n.rm(t,{recursive:!0,force:!0}),await n.mkdir(t,{recursive:!0});for(let i of r){let r=s.join(e,i),a=s.join(t,i);try{await n.cp(r,a,{recursive:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}function Li(e,t){let n=s.resolve(e),r=s.resolve(t);if(It(n,r)||It(r,n))throw new L(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function Ri(e,t){let n=s.resolve(e),r=s.resolve(n,t);if(r===n||!It(n,r))throw new L(`COPY_FAILED`,`Copy folder name "${t}" must resolve to a directory inside "${e}".`,{details:{targetDir:n,folderName:t,destination:r}});return r}async function zi(e,t){if(!await I(e))throw new L(`COPY_FAILED`,`Copy target directory does not exist: ${e}`,{details:{dir:e,label:t},suggestions:[`Create the target directory: mkdir -p "${e}"`,`Or check the copy target path in bepack.config.ts.`]})}function Bi(e,t){if(t===`bp`)return zt(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...Ot,...i]:[]}async function Vi(e){try{return new Uint8Array(await n.readFile(s.join(e,`manifest.json`)))}catch{return}}async function Hi(e,t,n,r,i,a,o,s,c){let l=Bi(i,e),u=Ri(n,r);Li(t,u);let d=e===`bp`||l.length>0;d&&await Ni({...s?{logger:s}:{},packType:e,root:t,items:l,action:`copy`,cwd:o,ignore:Ai(o,i,e)});let f=c===void 0?i.copy.optimize:c?i.copy.optimize??Ct:void 0;if(!a){if(f){let e=d?await Xr(t,l):await Yr(t),n=Ti(f,s,await Vi(t));try{await ei(u,await Zr(e,n))}catch(e){throw e instanceof L?new L(e.code===`PACK_FAILED`?`COPY_FAILED`:e.code,e.message,{...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions}}):e}}else d?await Ii(t,u,l):await Te(t,u)}let p=l.length>0?l.length:void 0;return s?.copy(`${a?`would copy`:`copied`} ${e}${p?` (${p} items)`:``} -> ${Fi.gray(u)}`),u}async function Ui(e,t,n,r=!1,i,a={}){let{name:o,target:s,names:c}=Oi(t,n),l=[],u=U(e,t),d=Et(t);for(let n of d){let o;if(o=n.type===`bp`?s.bp:s.rp,!o)continue;await zi(o,n.type);let d=c[n.type]??n.name,f=W(u,t,n.type),p=await Hi(n.type,f,o,d,t,r,e,i,a.optimize);l.push(p)}return{target:o,copied:l}}async function Wi(e){let{command:t,cwd:n,config:r,logger:i,targetName:a,mode:o,optimize:s}=e,c=!!e.dryRun,l={...o===void 0?{}:{mode:o},dryRun:c};await G(`beforeCopy`,t,n,r,i,l);let u=await Ui(n,r,a,c,i,s===void 0?{}:{optimize:s});return await G(`afterCopy`,t,n,r,i,l),u}function Gi(e,t){return ka(e,t||{},0,0)}function Ki(e,t){if(t){for(var n=new q(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Ma)return Ma.encode(e);for(var i=e.length,a=new q(e.length+(e.length>>1)),o=0,s=function(e){a[o++]=e},r=0;r<i;++r){if(o+5>a.length){var c=new q(o+8+(i-r<<1));c.set(a),a=c}var l=e.charCodeAt(r);l<128||t?s(l):l<2048?(s(192|l>>6),s(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|e.charCodeAt(++r)&1023,s(240|l>>18),s(128|l>>12&63),s(128|l>>6&63),s(128|l&63)):(s(224|l>>12),s(128|l>>6&63),s(128|l&63))}return pa(a,0,o)}function qi(e,t){t||={};var n={},r=[];ja(e,``,n,t);var i=0,a=0;for(var o in n){var s=n[o],c=s[0],l=s[1],u=l.level==0?0:8,d=Ki(o),f=d.length,p=l.comment,m=p&&Ki(p),h=m&&m.length,g=Pa(l.extra);f>65535&&ha(11);var _=u?Gi(c,l):c,v=_.length,y=Oa();y.p(c),r.push(Aa(l,{size:c.length,crc:y.d(),c:_,f:d,m,u:f!=o.length||m&&p.length!=h,o:i,compression:u})),i+=30+f+g+v,a+=76+2*(f+g)+(h||0)+v}for(var b=new q(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];Fa(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+Pa(d.extra);b.set(d.c,d.o+w),Fa(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return Ia(b,i,r.length,S,x),b}var Ji,Yi,q,J,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,Y,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,X,ja,Ma,Na,Pa,Fa,Ia,La=te((()=>{Ji=x(`/`);try{Yi=Ji("worker_threads"),Yi.Worker,Yi.isMarkedAsUntransferable}catch{}for(q=Uint8Array,J=Uint16Array,Xi=Int32Array,Zi=new q([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Qi=new q([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),$i=new q([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ea=function(e,t){for(var n=new J(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Xi(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Yi=ea(Zi,2),ta=Yi.b,na=Yi.r,ta[28]=258,na[258]=28,ra=ea(Qi,0),ra.b,ia=ra.r,aa=new J(32768),Y=0;Y<32768;++Y)oa=(Y&43690)>>1|(Y&21845)<<1,oa=(oa&52428)>>2|(oa&13107)<<2,oa=(oa&61680)>>4|(oa&3855)<<4,aa[Y]=((oa&65280)>>8|(oa&255)<<8)>>1;for(sa=(function(e,t,n){for(var r=e.length,i=0,a=new J(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new J(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new J(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[aa[d]>>c]=l}else for(s=new J(r),i=0;i<r;++i)e[i]&&(s[i]=aa[o[e[i]-1]++]>>15-e[i]);return s}),ca=new q(288),Y=0;Y<144;++Y)ca[Y]=8;for(Y=144;Y<256;++Y)ca[Y]=9;for(Y=256;Y<280;++Y)ca[Y]=7;for(Y=280;Y<288;++Y)ca[Y]=8;for(la=new q(32),Y=0;Y<32;++Y)la[Y]=5;ua=/*#__PURE__*/ sa(ca,9,0),da=/*#__PURE__*/ sa(la,5,0),fa=function(e){return(e+7)/8|0},pa=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new q(e.subarray(t,n))},ma=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],ha=function(e,t,n){var r=Error(t||ma[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ha),!n)throw r;return r},ga=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},_a=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},va=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,a=n.slice();if(!i)return{t:Ta,l:0};if(i==1){var o=new q(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(e,t){return e.f-t.f}),n.push({s:-1,f:25001});var s=n[0],c=n[1],l=0,u=1,d=2;for(n[0]={s:-1,f:s.f+c.f,l:s,r:c};u!=i-1;)s=n[n[l].f<n[d].f?l++:d++],c=n[l!=u&&n[l].f<n[d].f?l++:d++],n[u++]={s:-1,f:s.f+c.f,l:s,r:c};for(var f=a[0].s,r=1;r<i;++r)a[r].s>f&&(f=a[r].s);var p=new J(f+1),m=ya(n[u-1],p,0);if(m>t){var r=0,h=0,g=m-t,_=1<<g;for(a.sort(function(e,t){return p[t.s]-p[e.s]||e.f-t.f});r<i;++r){var v=a[r].s;if(p[v]>t)h+=_-(1<<m-p[v]),p[v]=t;else break}for(h>>=g;h>0;){var y=a[r].s;p[y]<t?h-=1<<t-p[y]++-1:++r}for(;r>=0&&h;--r){var b=a[r].s;p[b]==t&&(--p[b],++h)}m=t}return{t:new q(p),l:m}},ya=function(e,t,n){return e.s==-1?Math.max(ya(e.l,t,n+1),ya(e.r,t,n+1)):t[e.s]=n},ba=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new J(++t),r=0,i=e[0],a=1,o=function(e){n[r++]=e},s=1;s<=t;++s)if(e[s]==i&&s!=t)++a;else{if(!i&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(i),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(i);a=1,i=e[s]}return{c:n.subarray(0,r),n:t}},xa=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Sa=function(e,t,n){var r=n.length,i=fa(t+2);e[i]=r&255,e[i+1]=r>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var a=0;a<r;++a)e[i+a+4]=n[a];return(i+4+r)*8},Ca=function(e,t,n,r,i,a,o,s,c,l,u){ga(t,u++,n),++i[256];for(var d=va(i,15),f=d.t,p=d.l,m=va(a,15),h=m.t,g=m.l,_=ba(f),v=_.c,y=_.n,b=ba(h),x=b.c,S=b.n,C=new J(19),w=0;w<v.length;++w)++C[v[w]&31];for(var w=0;w<x.length;++w)++C[x[w]&31];for(var T=va(C,7),E=T.t,ee=T.l,D=19;D>4&&!E[$i[D-1]];--D);var te=l+5<<3,O=xa(i,ca)+xa(a,la)+o,k=xa(i,f)+xa(a,h)+o+14+3*D+xa(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&te<=O&&te<=k)return Sa(t,u,e.subarray(c,c+l));var A,j,M,ne;if(ga(t,u,1+(k<O)),u+=2,k<O){A=sa(f,p,0),j=f,M=sa(h,g,0),ne=h;var re=sa(E,ee,0);ga(t,u,y-257),ga(t,u+5,S-1),ga(t,u+10,D-4),u+=14;for(var w=0;w<D;++w)ga(t,u+3*w,E[$i[w]]);u+=3*D;for(var N=[v,x],ie=0;ie<2;++ie)for(var ae=N[ie],w=0;w<ae.length;++w){var P=ae[w]&31;ga(t,u,re[P]),u+=E[P],P>15&&(ga(t,u,ae[w]>>5&127),u+=ae[w]>>12)}}else A=ua,j=ca,M=da,ne=la;for(var w=0;w<s;++w){var F=r[w];if(F>255){var P=F>>18&31;_a(t,u,A[P+257]),u+=j[P+257],P>7&&(ga(t,u,F>>23&31),u+=Zi[P]);var oe=F&31;_a(t,u,M[oe]),u+=ne[oe],oe>3&&(_a(t,u,F>>5&8191),u+=Qi[oe])}else _a(t,u,A[F]),u+=j[F]}return _a(t,u,A[256]),u+j[256]},wa=/*#__PURE__*/ new Xi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ta=/*#__PURE__*/ new q(0),Ea=function(e,t,n,r,i,a){var o=a.z||e.length,s=new q(r+o+5*(1+Math.ceil(o/7e3))+i),c=s.subarray(r,s.length-i),l=a.l,u=(a.r||0)&7;if(t){u&&(c[0]=a.r>>3);for(var d=wa[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new J(32768),g=a.h||new J(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Xi(25e3),x=new J(288),S=new J(32),C=0,w=0,T=a.i||0,E=0,ee=a.w||0,D=0;T+2<o;++T){var te=y(T),O=T&32767,k=g[te];if(h[O]=k,g[te]=O,ee<=T){var A=o-T;if((C>7e3||E>24576)&&(A>423||!l)){u=Ca(e,c,0,b,x,S,w,E,D,T-D,u),E=C=w=0,D=T;for(var j=0;j<286;++j)x[j]=0;for(var j=0;j<30;++j)S[j]=0}var M=2,ne=0,re=p,N=O-k&32767;if(A>2&&te==y(T-N))for(var ie=Math.min(f,A)-1,ae=Math.min(32767,T),P=Math.min(258,A);N<=ae&&--re&&O!=k;){if(e[T+M]==e[T+M-N]){for(var F=0;F<P&&e[T+F]==e[T+F-N];++F);if(F>M){if(M=F,ne=N,F>ie)break;for(var oe=Math.min(N,F-2),se=0,j=0;j<oe;++j){var ce=T-N+j&32767,le=ce-h[ce]&32767;le>se&&(se=le,k=ce)}}}O=k,k=h[O],N+=O-k&32767}if(ne){b[E++]=268435456|na[M]<<18|ia[ne];var ue=na[M]&31,de=ia[ne]&31;w+=Zi[ue]+Qi[de],++x[257+ue],++S[de],ee=T+M,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,ee);T<o;++T)b[E++]=e[T],++x[e[T]];u=Ca(e,c,l,b,x,S,w,E,D,T-D,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=ee)}else{for(var T=a.w||0;T<o+l;T+=65535){var fe=T+65535;fe>=o&&(c[u/8|0]=l,fe=o),u=Sa(c,u+1,e.subarray(T,fe))}a.i=o}return pa(s,0,r+fa(u)+i)},Da=/*#__PURE__*/ (function(){for(var e=/* @__PURE__ */ new Int32Array(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),Oa=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=Da[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},ka=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new q(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return Ea(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,r,i)},Aa=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},X=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},ja=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=Aa(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new q(0),s],ja(a,o,n,r))}},Ma=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,Na=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{Na.decode(Ta,{stream:!0})}catch{}Pa=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&ha(9),t+=r+4}return t},Fa=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=Pa(l);X(e,t,o==null?67324752:33639248),t+=4,o!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(a<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),p=f.getFullYear()-1980;if((p<0||p>119)&&ha(10),X(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(X(e,t,n.crc),X(e,t+4,a<0?-a-2:a),X(e,t+8,n.size)),X(e,t+12,c),X(e,t+14,d),t+=16,o!=null&&(X(e,t,u),X(e,t+6,n.attrs),X(e,t+10,o),t+=14),e.set(r,t),t+=c,d)for(var m in l){var h=l[m],g=h.length;X(e,t,+m),X(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},Ia=function(e,t,n,r,i){X(e,t,101010256),X(e,t+8,n),X(e,t+10,n),X(e,t+12,r),X(e,t+16,i)}}));async function Ra(e,t){await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,qi($r(e)))}async function za(e,t,n){await Ra(await Zr(await Yr(e),n),t)}async function Ba(e,t,n,r){await Ra(await Zr(await Xr(e,t),r),n)}async function Va(e,t){let n={};for(let t of e){let e=await Zr(await Xr(t.source,t.items),t.transform);Object.assign(n,Qr(e,s.basename(s.resolve(t.source))))}await Ra(n,t)}async function Ha(e,t,n){let r={};for(let t of e){let e=await Zr(await Xr(t.source,t.items),t.transform);Object.assign(r,Qr(e,s.basename(s.resolve(t.source))))}for(let e of t){let t=await Zr(await Yr(e.dir),e.transform);Object.assign(r,Qr(t,s.basename(s.resolve(e.dir))))}await Ra(r,n)}var Ua=te((()=>{La(),ti()})),Wa=/* @__PURE__ */ k({packMcpack:()=>Ga});async function Ga(e,t,n,r=!1,i){let a=s.join(t,`${n}.mcpack`);return r||await za(e,a,i),a}var Ka=te((()=>{Ua()}));Ua();function qa(e,t,n){let r=s.resolve(e),i=s.resolve(t),a=s.relative(i,r);if(a&&!a.startsWith(`..`)&&!s.isAbsolute(a))throw new L(`PACK_FAILED`,`pack output must not be inside ${n} directory.`,{details:{output:r,dir:i},suggestions:[`Set pack.outDir to a path outside ${n}: ${i}`]})}function Ja(e,t,n){let r=s.resolve(e),i=s.resolve(t);for(let e of n){let t=s.resolve(i,e),n=s.relative(t,r);if(n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n))throw new L(`PACK_FAILED`,`pack output must not be included in the BP archive.`,{details:{output:r,includedPath:t},suggestions:[`Set pack.outDir outside the selected BP include path: ${t}`]})}}function Ya(e,t){let n=s.relative(s.resolve(t),s.resolve(e));if(n.startsWith(`..`)||s.isAbsolute(n))throw new L(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:s.resolve(e),dist:s.resolve(t)}})}function Xa(e,t){if(t===`bp`)return{items:zt(e),selective:!0};let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?{items:[...Ot,...i],selective:!0}:{items:[],selective:!1}}async function Za(e,t,n={}){let r=U(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=Ht(e,t);if(Et(t).length===0)throw new L(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let o=n.optimize===void 0?t.pack.optimize:n.optimize?t.pack.optimize??Ct:void 0,c=o?Ti(o,n.logger):void 0,l=t.packs.bp?{root:W(r,t,`bp`),config:t}:void 0,u=t.packs.rp?{root:W(r,t,`rp`),config:t}:void 0,d=l?Xa(t,`bp`):void 0;if(l&&d?.selective&&await Ni({...n.logger?{logger:n.logger}:{},packType:`bp`,root:l.root,items:d.items,action:`pack`,cwd:e,ignore:Ai(e,t,`bp`)}),u){let r=Xa(t,`rp`);r.selective&&await Ni({...n.logger?{logger:n.logger}:{},packType:`rp`,root:u.root,items:r.items,action:`pack`,cwd:e,ignore:Ai(e,t,`rp`)})}if(l&&u){if(!d)throw new L(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcaddon`);if(Ya(e,a),d?.selective&&Ja(e,l.root,d.items),qa(e,u.root,`RP`),!n.dryRun){let n=Xa(t,`rp`);n.selective?await Va([{source:l.root,items:d.items,...c?{transform:c}:{}},{source:u.root,items:n.items,...c?{transform:c}:{}}],e):await Ha([{source:l.root,items:d.items,...c?{transform:c}:{}}],[{dir:u.root,...c?{transform:c}:{}}],e)}return e}if(l){if(!d)throw new L(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcpack`);return Ya(e,a),d?.selective&&Ja(e,l.root,d.items),n.dryRun||await Ba(l.root,d.items,e,c),e}if(u){let e=s.join(a,`${i}.mcpack`);if(Ya(e,a),qa(e,u.root,`RP`),!n.dryRun){let r=Xa(t,`rp`);if(r.selective)await Ba(u.root,r.items,e,c);else{let{packMcpack:e}=await Promise.resolve().then(()=>(Ka(),Wa));return await e(u.root,a,i,n.dryRun,c)}}return e}throw new L(`PACK_FAILED`,`No packs configured.`)}async function Qa(e,t,n,r={}){let i=Date.now();await G(`beforePack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let a=await Za(e,t,{...r,logger:n});await G(`afterPack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let o=Date.now()-i;return n.done(`pack`,r.dryRun?`dry-run: would pack ${a} (no file written)`:`packed ${a} in ${n.formatDuration(o)}`),{output:a,durationMs:o,dryRun:!!r.dryRun}}async function $a(e){let t=new z({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config}),i=e.build===!1||!!e.skipBuild,a=null;if(!i){let i=e.skipTypecheck?!1:e.typecheck?!0:r.packs.bp?.compile?.typecheck,o=e.cache===void 0?r.packs.bp?.compile?.cache.build??!1:!!e.cache,s=e.typecheckCommand;a=await Jr({cwd:n,config:r,logger:t,command:`build`,...i===void 0?{}:{typecheck:i},...s===void 0?{}:{typecheckCommand:s},...e.cache===void 0?{}:{cache:o},dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{}})}let{output:o,durationMs:s}=await Qa(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}});return{ok:!0,command:`pack`,durationMs:s,output:o,built:!i,build:a}}function eo(e){for(let t of[[`copy`,`skipCopy`],[`pack`,`skipPack`],[`typecheck`,`skipTypecheck`],[`install`,`skipInstall`]]){let[n,r]=t;if(e[n]&&e[r])throw new L(`CLI_ARGUMENT_CONFLICT`,`--${n} and --${r} cannot be used together.`)}}async function to(e){eo(e);let t=new z({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target,...e.timing===void 0?{}:{build:{timing:e.timing}}}});t.bepack(`build`,`target ${r.target}`);let i;if(e.install){let t=await rr({...e,cwd:n,config:void 0,silent:e.silent||e.json});i=Object.fromEntries(Object.entries(t.resolved).filter(([,e])=>e.manifestVersion!==null).map(([e,t])=>[e,t.manifestVersion]))}let a=r.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=e.cache===void 0?a?.cache.build??!1:e.cache,l=await Jr({cwd:n,config:r,logger:t,mode:e.mode,command:`build`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},...e.useNpx?{useNpx:!0}:{},cache:!!c,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),u=null,d=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;d&&(u=await Wi({command:`build`,cwd:n,config:r,logger:t,...e.mode===void 0?{}:{mode:e.mode},targetName:e.copyTarget??(typeof d==`string`?d:void 0),dryRun:!!e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}}));let f=null;return!e.skipPack&&e.pack&&(f=await Qa(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}})),t.done(`build`,`complete in ${t.formatDuration(l.durationMs)}`),{ok:!0,command:`build`,durationMs:l.durationMs,build:l,copy:u,pack:f}}async function no(e){let t=Date.now(),n=new z({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});await G(`beforeCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let a=e.all?[`win`,`winold`,...Object.keys(i.copy.targets)]:[e.target??i.copy.defaultTarget],o={...e.optimize===void 0?{}:{optimize:!!e.optimize}},s=[];for(let t of a)s.push(await Ui(r,i,t,e.dryRun,n,o));await G(`afterCopy`,`copy`,r,i,n,{dryRun:!!e.dryRun});let c=Date.now()-t;return n.done(`copy`,`${e.dryRun?`dry-run complete`:`complete`} in ${n.formatDuration(c)}`),{ok:!0,command:`copy`,durationMs:c,results:s}}const ro=/[/\\]rolldown\.config\.[A-Za-z0-9_-]+\.js$/;function io(e,t){return H(s.relative(e,t))}function ao(e,t,n,r){let i=U(e,t),a=Mt(t),o=[];if(a){let n=Nt(e,t);n&&o.push(io(e,s.dirname(n)))}if(r.copy){for(let n of Et(t))if(W(i,t,n.type)){let r=oo(e,t,n.type,i);o.push(...r)}}let c=t.dev.watch?.include??[];o.push(...c);let l=Wt(o.map(t=>s.resolve(e,t))).map(t=>io(e,t));if(l.length===0)throw new L(`DEV_NO_WATCH_TARGETS`,`Nothing to watch: no compile entry, no copy-enabled pack directories and no dev.watch.include paths.`,{suggestions:[`Configure packs.bp.compile.entry to watch TypeScript sources.`,"Enable copying (packs.rp/bp, dev.copy or `bepack dev --copy`) to watch pack folders.",`Add paths explicitly with dev.watch.include.`]});let u=[`node_modules`,`.git`,io(e,Ht(e,t))];for(let n of Et(t)){let r=W(i,t,n.type);if(r&&(u.push(io(e,s.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=W(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push(io(e,s.join(n,r)))}}let d=S.watch(l,{cwd:e,ignored:[...u,ro],ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await Wi({command:`dev`,cwd:e,config:t,logger:n,targetName:r.copyTarget,dryRun:r.dryRun,...r.mode===void 0?{}:{mode:r.mode},...r.optimize===void 0?{}:{optimize:r.optimize}})},g=async()=>{await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},_=async()=>{a?await Jr({cwd:e,config:t,logger:n,command:`dev`,typecheck:r.typecheck,cache:r.cache,dryRun:r.dryRun,quiet:!!r.quiet,...r.mode===void 0?{}:{mode:r.mode},...r.typecheckCommand===void 0?{}:{typecheckCommand:r.typecheckCommand},...r.rolldownConfig===void 0?{}:{rolldownConfig:r.rolldownConfig}}):await er({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},v=async()=>{for(;p||m;){let e=p;p=!1,m=!1;let t=Date.now();try{n.clear(),e?(n.bepack(`dev`,`rebuilding (pending changes)`),await _(),n.done(`dev`,`rebuild done in ${n.formatDuration(Date.now()-t)}`)):await g()}catch(e){n.error(e instanceof Error?e.message:String(e))}}};d.on(`all`,async(r,i)=>{let o=H(i),c=a?Nt(e,t):void 0,l=c?s.dirname(c):void 0,u=s.resolve(e,o),d=l?u===l||u.startsWith(l+s.sep):!1;if(f){d?p=!0:m=!0;return}f=!0;let h=Date.now();try{n.clear(),n.bepack(`dev`,`changed ${s.normalize(i)}`),d&&a?await _():await g(),n.done(`dev`,`updated after ${s.normalize(i)} in ${n.formatDuration(Date.now()-h)}`)}catch(e){n.error(e instanceof Error?e.message:String(e))}finally{try{await v()}finally{f=!1}}});let y=t.packs.bp?H(s.relative(e,W(i,t,`bp`))):null,b=t.packs.rp?H(s.relative(e,W(i,t,`rp`))):null,x=a&&Nt(e,t)?io(e,s.dirname(Nt(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)y&&(e===y||e.startsWith(y+`/`))?(T++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):b&&(e===b||e.startsWith(b+`/`))?(E++,x&&(e===x||e.startsWith(x+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))||w.push(e);return x&&!C&&w.unshift(x),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function oo(e,t,n,r){let i=W(r,t,n);if(!i)return[];if(n===`bp`)return zt(t).filter(e=>e!==`manifest.json`).map(t=>H(s.relative(e,s.join(i,t))));let a=t.packs.rp;return a?a.include&&a.include.length>0?a.include.filter(e=>e!==`manifest.json`).map(t=>H(s.relative(e,s.join(i,t)))):[H(s.relative(e,i))]:[]}async function so(e){let t=Date.now(),n=new z({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{...e.timing===void 0?{}:{build:{timing:e.timing}}}});n.clear(),n.bepack(`dev`,`target ${i.target}`),n.progress(`dev`,`initial build started`);let a=i.packs.bp?.compile,o=e.skipTypecheck?!1:e.typecheck?!0:a?.typecheck??!1,s=e.typecheckCommand,c=!e.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),l=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),u=a?.cache.dev??!0,d=!!e.dryRun,f=!!(e.json||e.silent),p=e.optimize===void 0?{}:{optimize:!!e.optimize};return await Jr({cwd:r,config:i,logger:n,mode:e.mode,command:`dev`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),c&&await Wi({command:`dev`,cwd:r,config:i,logger:n,targetName:l,dryRun:d,...e.mode===void 0?{}:{mode:e.mode},...p}),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),ao(r,i,n,{copy:c,mode:e.mode,...l?{copyTarget:l}:{},...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},...p,typecheck:!!o,...s===void 0?{}:{typecheckCommand:s},cache:u,dryRun:d,quiet:f}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}function co(e){let t=/* @__PURE__ */ new WeakSet;function n(e){if(typeof e==`function`)return`[function]`;if(e instanceof RegExp)return e.toString();if(typeof e!=`object`||!e)return e;if(t.has(e))return`[circular]`;t.add(e);let r=Array.isArray(e)?e.map(n):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)]));return t.delete(e),r}return n(e)}async function lo(e){let t=new z({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await In({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:co(r)};if(e.summary){t.bepack(`config`,i),t.info(`root: ${r.root}`),t.info(`name: ${r.name}`),t.info(`version: ${r.version}`),r.description&&t.info(`description: ${r.description}`),t.info(`target: ${r.target}`);let e=[];if(r.packs.bp&&e.push(`bp`),r.packs.rp&&e.push(`rp`),t.info(`packs: ${e.join(`, `)}`),r.packs.bp?.compile){let e=r.packs.bp.compile;t.info(`compile.entry: ${e.entry}`),t.info(`compile.scriptOutputDir: ${e.scriptOutputDir}`),t.info(`compile.preserveModules: ${e.preserveModules}`),t.info(`compile.typecheck: ${e.typecheck}`),e.typecheckCommand&&t.info(`compile.typecheckCommand: ${e.typecheckCommand}`),e.typecheckArgs.length>0&&t.info(`compile.typecheckArgs: [${e.typecheckArgs.join(`, `)}]`),e.external.length>0&&t.info(`compile.external: [${e.external.map(e=>typeof e==`string`?e:e.toString()).join(`, `)}]`)}let n=Object.keys(r.hooks);n.length>0?t.info(`hooks: ${n.join(`, `)}`):t.info(`hooks: (none)`);let a=r.plugins??[];if(a.length>0){t.info(`plugins: ${a.map(e=>`${e.name} (priority ${e.priority??0})`).join(`, `)}`);for(let e of r.pluginDiagnostics??[])t.warn(`plugin conflict: ${e}`)}else t.info(`plugins: (none)`);t.info(`install.registry: ${r.install.registry}`);let o=Object.keys(Ln(r));return o.length>0?t.info(`install.dependencyCatalog: ${o.join(`, `)}`):t.info(`install.dependencyCatalog: (none)`),t.info(`pack.outDir: ${r.pack.outDir}`),r.copy.defaultTarget&&t.info(`copy.defaultTarget: ${r.copy.defaultTarget}`),r.build.copy&&t.info(`build.copy: ${r.build.copy}`),r.dev.copy&&t.info(`dev.copy: ${r.dev.copy}`),{ok:!0,command:`config`}}let a=co(r),o=JSON.stringify(a,null,2);return t.bepack(`config`,i),t.info(`cwd: ${n}`),t.info(`configFile: ${i}`),t.info(``),t.info(o),{ok:!0,command:`config`}}function Z(e,t,n){throw new L(`PROFILE_INVALID`,`${e}: ${t}`,{...n===void 0?{}:{details:n},suggestions:[`Check that the file was produced by a V8 profiler and is valid JSON.`]})}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fo(e,t,n){return(typeof e!=`number`||!Number.isFinite(e))&&Z(n,`${t} must be a finite number`),e}function po(e,t,n){let r=fo(e,t,n);return Number.isInteger(r)||Z(n,`${t} must be an integer`),r}function mo(e,t,n,r){let i=e[t];if(i!==void 0)return fo(i,`${n}.${t}`,r)}function ho(e,t,n,r){let i=e[t];if(i!==void 0)return po(i,`${n}.${t}`,r)}function go(e,t,n){uo(e)||Z(n,`${t} must be an object`);let r=e.functionName??``;typeof r!=`string`&&Z(n,`${t}.functionName must be a string`);let i=e.url??``;typeof i!=`string`&&Z(n,`${t}.url must be a string`);let a=e.scriptId,o;a===void 0?o=`0`:typeof a==`number`&&Number.isFinite(a)?o=String(a):typeof a==`string`?o=a:Z(n,`${t}.scriptId must be a string`);let s=e.lineNumber??-1;(typeof s!=`number`||!Number.isFinite(s))&&Z(n,`${t}.lineNumber must be a finite number`);let c=e.columnNumber??-1;return(typeof c!=`number`||!Number.isFinite(c))&&Z(n,`${t}.columnNumber must be a finite number`),{functionName:r,scriptId:o,url:i,lineNumber:s,columnNumber:c}}function _o(e,t,n){let r=`nodes[${t}]`;uo(e)||Z(n,`${r} must be an object`);let i=po(e.id,`${r}.id`,n),a=go(e.callFrame,`${r}.callFrame`,n),o=ho(e,`hitCount`,r,n),s=ho(e,`locationId`,r,n),c;return e.children!==void 0&&(Array.isArray(e.children)||Z(n,`${r}.children must be an array`),c=e.children.map((e,t)=>po(e,`${r}.children[${t}]`,n))),{id:i,callFrame:a,...o===void 0?{}:{hitCount:o},...c===void 0?{}:{children:c},...s===void 0?{}:{locationId:s}}}function vo(e,t=`<profile>`){uo(e)||Z(t,`profile root must be a JSON object`),Array.isArray(e.nodes)||Z(t,`missing nodes array`),Array.isArray(e.samples)||Z(t,`missing samples array`),Array.isArray(e.timeDeltas)||Z(t,`missing timeDeltas array`);let n=e.nodes.map((e,n)=>_o(e,n,t)),r=/* @__PURE__ */ new Set;for(let e of n)r.has(e.id)&&Z(t,`duplicate node id ${e.id}`),r.add(e.id);for(let e of n)for(let n of e.children??[])r.has(n)||Z(t,`node ${e.id} references unknown child node ${n}`);e.timeDeltas.length!==e.samples.length&&Z(t,`samples and timeDeltas must have the same length (${e.samples.length} != ${e.timeDeltas.length})`);let i=e.samples.map((e,n)=>{let i=po(e,`samples[${n}]`,t);return r.has(i)||Z(t,`samples[${n}] references unknown node ${i}`),i}),a=e.timeDeltas.map((e,n)=>{let r=fo(e,`timeDeltas[${n}]`,t);return r<0&&Z(t,`timeDeltas[${n}] must not be negative`),r}),o=mo(e,`startTime`,`profile`,t),s=mo(e,`endTime`,`profile`,t);return{nodes:n,samples:i,timeDeltas:a,...o===void 0?{}:{startTime:o},...s===void 0?{}:{endTime:s}}}function yo(e,t,n){let r=[],i=/* @__PURE__ */ new Set,a=e.id;for(;a!==void 0&&!i.has(a);){i.add(a);let e=n.get(a);if(!e)break;r.push(e),a=t.get(a)}return r}function bo(e){let t=e[0],n=e[e.length-1];if(!t||!n)throw Error(`cannot create a burst from an empty sample run`);let r=e.reduce((e,t)=>e+t.deltaMs,0);return{startMs:t.timeMs,endMs:n.timeMs,spanMs:n.timeMs-t.timeMs,busyMs:r,samples:e.length,run:e}}function xo(e,t){let n=[],r=[];for(let i of e){if(i.active){r.push(i);continue}r.length>0&&r.length>=t&&n.push(bo(r)),r=[]}return r.length>0&&r.length>=t&&n.push(bo(r)),n}function So(e,t,n){let r=vo(e,t),i=n.gapMs??5,a=n.minSamples??20,o=new Map(r.nodes.map(e=>[e.id,e])),s=/* @__PURE__ */ new Map;for(let e of r.nodes)for(let t of e.children??[])s.set(t,e.id);let c=i*1e3,l=0,u=[];for(let e=0;e<r.samples.length;e++){let t=r.timeDeltas[e]??0;l+=t;let n=o.get(r.samples[e]??-1);n&&u.push({index:e,timeMs:l/1e3,deltaMs:t/1e3,active:t<=c,node:n,stack:yo(n,s,o)})}let d=u.filter(e=>e.active),f=u.filter(e=>!e.active);return{file:t,raw:r,samples:u,activeSamples:d,gapSamples:f,busyMs:d.reduce((e,t)=>e+t.deltaMs,0),idleMs:f.reduce((e,t)=>e+t.deltaMs,0),durationMs:l/1e3,gapMs:i,minSamples:a,bursts:xo(u,a)}}async function Co(e,t={}){let n;try{n=await v(e,`utf8`)}catch(t){throw new L(`PROFILE_READ_FAILED`,`Cannot read profile ${e}: ${t instanceof Error?t.message:String(t)}`,{details:{file:e},suggestions:[`Check the path and that the file is readable.`]})}let r;try{r=JSON.parse(n)}catch(t){Z(e,`not valid JSON: ${t instanceof Error?t.message:String(t)}`)}return So(r,e,t)}function wo(e){let t=e.callFrame;return`${t.functionName||`(anonymous)`}\u0000${t.url||`(unknown)`}\u0000${t.lineNumber}`}function To(e,{by:t,gapMs:n}){let r=/* @__PURE__ */ new Map,i=0,a=0;for(let o of e){if(o.deltaMs>n)continue;if(i++,a+=o.deltaMs,t===`self`){let e=o.stack[0];if(!e)continue;let t=wo(e),n=r.get(t)??{node:e,count:0,ms:0};n.count++,n.ms+=o.deltaMs,r.set(t,n);continue}let e=/* @__PURE__ */ new Set;for(let t of o.stack){let n=wo(t);if(e.has(n))continue;e.add(n);let i=r.get(n)??{node:t,count:0,ms:0};i.count++,i.ms+=o.deltaMs,r.set(n,i)}}return{rows:[...r.values()].map(e=>({node:e.node,count:e.count,share:a===0?0:e.ms/a,ms:e.ms})).sort((e,t)=>t.ms-e.ms||t.count-e.count||e.node.callFrame.functionName.localeCompare(t.node.callFrame.functionName)),active:i,busyMs:a}}function Eo(e,t,n){let r=/* @__PURE__ */ new Map,i=0;for(let n of e){if(n.deltaMs>t)continue;i+=n.deltaMs;let e=n.stack.map(e=>wo(e)).join(`
|
|
11
|
+
`),a=r.get(e)??{sample:n,count:0,ms:0};a.count++,a.ms+=n.deltaMs,r.set(e,a)}return[...r.values()].sort((e,t)=>t.ms-e.ms||t.count-e.count).slice(0,n).map(e=>({sample:e.sample,count:e.count,share:i===0?0:e.ms/i,ms:e.ms}))}function Do(e){return e.bursts.reduce((e,t)=>e?t.busyMs===e.busyMs?t.samples>e.samples?t:e:t.busyMs>e.busyMs?t:e:t,void 0)}function Q(e){return e>=1e3?`${(e/1e3).toFixed(2)} s`:`${e.toFixed(1)} ms`}function Oo(e){return`${(e*100).toFixed(1)}%`}function ko(e,t){let n=e.callFrame,r=n.url||`(unknown)`,i=r.replace(/\\/g,`/`),a=t.replace(/\\/g,`/`).replace(/\/+$/,``),o=process.platform===`win32`?i.toLowerCase():i,s=[a];process.platform===`win32`&&/^[a-z]:/i.test(a)&&s.push(a.slice(2));let c=s.find(e=>{let t=process.platform===`win32`?e.toLowerCase():e;return o===t||t!==`/`&&o.startsWith(`${t}/`)||t===`/`&&o.startsWith(`/`)});return r=c===`/`?i.slice(1):c?o===(process.platform===`win32`?c.toLowerCase():c)?`.`:i.slice(c.length+1):!a&&i.startsWith(`/`)?i.slice(1):i,{functionName:n.functionName||`(anonymous)`,url:r,line:n.lineNumber>=0?n.lineNumber+1:null}}function Ao(e){return`${e.functionName} ${e.url}${e.line===null?``:`:${e.line}`}`}function jo(e){return Ao(e)}function Mo(e,t){return{...ko(e.node,t),count:e.count,share:e.share,ms:e.ms}}function No(e,t){return e.sample.stack.map(e=>{let n=ko(e,t);return`${n.functionName} (${n.url}${n.line===null?``:`:${n.line}`})`}).join(` <- `)}function Po(e,t){return{count:e.count,share:e.share,ms:e.ms,stack:No(e,t),frames:e.sample.stack.map(e=>{let n=ko(e,t);return`${n.functionName} (${n.url}${n.line===null?``:`:${n.line}`})`})}}function Fo(e,t){return`${t}${String(e.count).padStart(4)} ${Oo(e.share).padStart(6)} ${Q(e.ms).padStart(9)} ${jo(e)}`}function Io(e,t){return`${t}${String(e.count).padStart(4)} ${Oo(e.share).padStart(6)} ${Q(e.ms).padStart(9)} ${e.stack}`}function Lo(e,t=``){return`${t}${e.startMs.toFixed(1)}-${e.endMs.toFixed(1)} ms | ${e.samples} samples | span ${Q(e.spanMs)} | busy ${Q(e.busyMs)}`}function Ro(e,t,n){return{startMs:t.startMs,endMs:t.endMs,spanMs:t.spanMs,busyMs:t.busyMs,samples:t.samples,topSelf:To(t.run,{by:`self`,gapMs:e.gapMs}).rows.slice(0,n.limit).map(e=>Mo(e,n.root)),topStacks:Eo(t.run,e.gapMs,n.stacks).map(e=>Po(e,n.root))}}function zo(e,t){let n=e.map(e=>{let n=[...e.bursts].sort((e,t)=>t.busyMs-e.busyMs).map(n=>Ro(e,n,{limit:t.limit,stacks:0,root:t.root}));return{file:e.file,durationMs:e.durationMs,samples:e.samples.length,activeSamples:e.activeSamples.length,busyMs:e.busyMs,idleMs:e.idleMs,gapMs:e.gapMs,minSamples:e.minSamples,bursts:n}});return{text:n.map(e=>{let t=[`profile: ${e.file}`,`duration: ${Q(e.durationMs)} | samples: ${e.samples} | active: ${e.activeSamples} (${Q(e.busyMs)}) | gaps: ${e.samples-e.activeSamples} (${Q(e.idleMs)})`,`gap threshold: ${e.gapMs} ms | bursts: ${e.bursts.length} (>= ${e.minSamples} samples)`];for(let n of e.bursts){t.push(` @ ${Lo(n)}`);for(let e of n.topSelf)t.push(Fo(e,` `))}return t.join(`
|
|
12
12
|
`)}).join(`
|
|
13
|
-
`),data:{profiles:n}}}function
|
|
14
|
-
`);let t=[];for(let[n,r]of e.bursts.entries()){t.push(`burst #${n+1}: ${
|
|
13
|
+
`),data:{profiles:n}}}function Bo(e,t){let n=e.map(e=>{let n=e.bursts.map(n=>Ro(e,n,t)),r=e.bursts.map(e=>e.startMs);return{file:e.file,minSamples:e.minSamples,bursts:n,intervals:r.slice(1).map((e,t)=>e-(r[t]??e))}});return{text:n.map(e=>{if(e.bursts.length===0)return[`profile: ${e.file}`,`no bursts with >= ${e.minSamples} active samples`].join(`
|
|
14
|
+
`);let t=[];for(let[n,r]of e.bursts.entries()){t.push(`burst #${n+1}: ${Lo(r)}`),t.push(` top self:`);for(let e of r.topSelf)t.push(Fo(e,` `));t.push(` top stacks:`);for(let e of r.topStacks)t.push(Io(e,` `));t.push(``)}return e.bursts.length>1&&t.push(`burst intervals: ${e.intervals.map(e=>e.toFixed(1)).join(`, `)} ms`),t.join(`
|
|
15
15
|
`)}).join(`
|
|
16
|
-
`),data:{profiles:n}}}function
|
|
17
|
-
`),data:{profile:{file:e.file,window:{fromMs:t.fromMs??null,toMs:t.toMs??null},by:t.by,activeSamples:r,busyMs:i,rows:a}}}}function
|
|
18
|
-
`),data:{before:d,after:f,compared:u?`burst`:`active`,changes:l}}}const
|
|
16
|
+
`),data:{profiles:n}}}function Vo(e,t){let{rows:n,active:r,busyMs:i}=To(e.samples.filter(e=>!(t.fromMs!==void 0&&e.timeMs<t.fromMs||t.toMs!==void 0&&e.timeMs>t.toMs)),{by:t.by,gapMs:e.gapMs}),a=n.slice(0,t.limit).map(e=>Mo(e,t.root)),o=t.fromMs===void 0&&t.toMs===void 0?`whole profile`:`${t.fromMs??0}-${t.toMs??`end`} ms`;return{text:[`profile: ${e.file}`,`window: ${o} | active: ${r} samples | busy: ${Q(i)} | by: ${t.by}`,...a.map(e=>Fo(e,` `))].join(`
|
|
17
|
+
`),data:{profile:{file:e.file,window:{fromMs:t.fromMs??null,toMs:t.toMs??null},by:t.by,activeSamples:r,busyMs:i,rows:a}}}}function Ho(e){return{startMs:e.startMs,endMs:e.endMs,spanMs:e.spanMs,busyMs:e.busyMs,samples:e.samples,topSelf:[],topStacks:[]}}function Uo(e){let t=Do(e);return{file:e.file,durationMs:e.durationMs,activeSamples:e.activeSamples.length,busyMs:e.busyMs,bursts:e.bursts.length,largestBurst:t?Ho(t):null}}function Wo(e,t,n){let r=Do(e),i=Do(t),a=r?.run??e.samples,o=i?.run??t.samples,s=new Map(To(a,{by:`self`,gapMs:e.gapMs}).rows.map(e=>[wo(e.node),e])),c=new Map(To(o,{by:`self`,gapMs:t.gapMs}).rows.map(e=>[wo(e.node),e])),l=[.../* @__PURE__ */ new Set([...s.keys(),...c.keys()])].map(e=>{let t=s.get(e),n=c.get(e),r=t?.node??n?.node;if(r)return{node:r,before:t?.count??0,after:n?.count??0,delta:(n?.count??0)-(t?.count??0)}}).filter(e=>e!==void 0&&e.delta!==0).sort((e,t)=>Math.abs(t.delta)-Math.abs(e.delta)||t.before-e.before).slice(0,n.limit).map(e=>({...ko(e.node,n.root),before:e.before,after:e.after,delta:e.delta})),u=!!(r&&i),d=Uo(e),f=Uo(t),p=[`before: ${e.file}`,`after: ${t.file}`,`duration: ${Q(e.durationMs)} -> ${Q(t.durationMs)} | active: ${e.activeSamples.length} -> ${t.activeSamples.length} | busy: ${Q(e.busyMs)} -> ${Q(t.busyMs)} | bursts: ${e.bursts.length} -> ${t.bursts.length}`];if(r||i){p.push(`largest burst:`);for(let[e,t]of[[`before`,r],[`after `,i]])p.push(t?` ${e}: ${Lo(Ho(t))}`:` ${e}: none`)}if(p.push(u?`largest-burst self samples (after - before):`:`active self samples (after - before):`),l.length===0)p.push(` no difference`);else for(let e of l){let t=e.delta>0?`+`:``;p.push(` ${t}${String(e.delta).padStart(4)} ${String(e.before).padStart(4)} -> ${String(e.after).padStart(4)} ${Ao(e)}`)}return{text:p.join(`
|
|
18
|
+
`),data:{before:d,after:f,compared:u?`burst`:`active`,changes:l}}}const Go=[`summary`,`bursts`,`top`,`diff`];function Ko(e,t=[]){throw new L(`CLI_ARGUMENT_INVALID`,e,{...t.length===0?{}:{suggestions:t}})}function qo(e,t,n,r){if(e===void 0)return n;let i=typeof e==`number`?e:Number(e);return(!Number.isFinite(i)||i<r.min)&&Ko(`--${t} must be a number >= ${r.min}, got ${JSON.stringify(e)}.`),r.integer&&!Number.isInteger(i)&&Ko(`--${t} must be an integer, got ${JSON.stringify(e)}.`),i}function Jo(e,t){if(e===void 0)return;let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)||Ko(`--${t} must be a number, got ${JSON.stringify(e)}.`),n}function Yo(e){if(e&&Go.includes(e))return e;Ko(`Unknown profile command: ${e??`(none)`}. Expected one of ${Go.join(`, `)}.`,["Run `bepack profile --help` to see available commands."])}async function Xo(e,t,n){let r=Yo(e),i=r===`diff`?2:1;t.length!==i&&Ko(`${r} expects ${i} profile file${i===1?``:`s`}, got ${t.length}.`,[r===`diff`?`Usage: bepack profile diff <before> <after>`:`Usage: bepack profile ${r} <profile>`]);let a=qo(n.gap,`gap`,5,{min:0}),o=qo(n.minSamples,`min-samples`,20,{min:1,integer:!0}),c=qo(n.limit??n.n,`limit`,15,{min:0,integer:!0}),l=qo(n.stacks,`stacks`,5,{min:0,integer:!0}),u=Jo(n.from,`from`),d=Jo(n.to,`to`),f=n.by??`self`;f!==`self`&&f!==`total`&&Ko(`--by must be self or total, got ${JSON.stringify(n.by)}.`);let p=s.resolve(typeof n.cwd==`string`?n.cwd:process.cwd()),m=s.resolve(p,typeof n.root==`string`?n.root:`.`),h=new z({silent:n.silent||n.json,verbose:n.verbose}),g=t.map(e=>s.resolve(p,e)),_=await Promise.all(g.map(e=>Co(e,{gapMs:a,minSamples:o}))),v={limit:c,root:m};if(r===`summary`){let e=zo(_,v);return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}if(r===`bursts`){let e=Bo(_,{...v,stacks:l});return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}let y=_[0];if(y||Ko(`top expects one profile file.`),r===`top`){let e=Vo(y,{...v,by:f,...u===void 0?{}:{fromMs:u},...d===void 0?{}:{toMs:d}});return n.json||h.info(e.text),{ok:!0,command:`profile`,mode:r,...e.data}}let b=_[1];b||Ko(`diff expects two profile files.`);let x=Wo(y,b,v);return n.json||h.info(x.text),{ok:!0,command:`profile`,mode:r,...x.data}}function Zo(e){return e instanceof L?{code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},...e.suggestions===void 0?{}:{suggestions:e.suggestions},...e.stack?{stack:e.stack}:{}}:e instanceof Error?{code:`UNKNOWN`,message:e.message,...e.stack?{stack:e.stack}:{}}:{code:`UNKNOWN`,message:String(e)}}function Qo(e){console.log(JSON.stringify(e,null,4))}const $o=Ee.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`),es=a(import.meta.url),ts=c(es),ns=l(ts,`../package.json`);let rs;try{let e=JSON.parse(r(ns,`utf-8`));(typeof e.version!=`string`||!e.version)&&(console.error(`ERROR: package.json missing valid 'version' field`),process.exit(1)),rs=e.version}catch(e){console.error(`ERROR: Failed to read package version: ${e.message}`),process.exit(1)}const $=ve(`bepack`);function is(e){return e.option(`--cwd <path>`,`Working directory`).option(`--config <path>`,`Config path`).option(`--json`,`JSON output`).option(`--dry-run`,`Do not write files`).option(`--silent`,`Silent output`).option(`--verbose`,`Verbose output`)}let as=!1;function os(e,t,n){let r=Zo(t);if(n)Qo({ok:!1,command:e,error:r});else if(t instanceof L){if(console.error(`${$o.red(r.code)}: ${r.message}`),r.suggestions?.length)for(let e of r.suggestions)console.error(` ${$o.dim(`→`)} ${e}`);as&&r.stack&&console.error(`${$o.dim(r.stack)}`)}else t instanceof Error?(console.error(`${$o.red(`ERROR`)}: ${t.message}`),as&&r.stack&&console.error(`${$o.dim(r.stack)}`)):console.error(`${$o.red(`ERROR`)}: ${String(t)}`);process.exitCode=1}async function ss(e,t,n){as=!!n.verbose;try{let e=await t(n);n.json&&Qo(e)}catch(t){os(e,t,!!n.json)}}is($.command(`init`,`Create BePack project`)).option(`--format <format>`,`ts/js/mjs`).option(`--yes`,`Use defaults`).option(`--force`,`Overwrite generated files`).option(`--from-bp <path>`,`Reverse-engineer config from existing BP manifest.json`).option(`--from-rp <path>`,`Reverse-engineer config from existing RP manifest.json`).action(e=>ss(`init`,bt,e)),is($.command(`install`,`Sync dependencies`)).option(`--target <target>`,`Target MC version`).option(`--registry <url>`,`npm registry`).option(`--pm <pm>`,`Package manager`).option(`--skip-pm`,`Do not run package manager`).option(`--skip-manifest`,`Do not patch manifest`).option(`--skip-package-json`,`Do not patch package.json`).option(`--save-to <field>`,`dependencies/devDependencies`).action(e=>ss(`install`,rr,e)),is($.command(`manifest`,`Patch manifest files`)).option(`--target <target>`,`Target MC version`).action(e=>ss(`manifest`,ir,e)),is($.command(`build`,`Build project`)).alias(`b`).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--target <target>`,`Target MC version`).option(`--install`,`Run install`).option(`--skip-install`,`Skip install`).option(`--copy`,`Copy after build`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--pack`,`Pack after build`).option(`--skip-pack`,`Skip pack`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--preserve-modules`,`Preserve module output`).option(`--use-npx`,`Use npx tsc for typecheck (deprecated: use --typecheck-command)`).option(`--minify`,`Minify output`).option(`--cache`,`Enable incremental compilation cache (--no-cache to disable)`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--timing`,`Show per-step timing`).action(e=>ss(`build`,to,e)),is($.command(`copy`,`Copy packs`)).option(`--target <target>`,`Copy target`).option(`--all`,`Copy to all targets`).option(`--optimize`,`Optimize the copied packs into __brarchive archives (--no-optimize to disable)`).action(e=>ss(`copy`,no,e)),is($.command(`pack`,`Build and pack mcpack/mcaddon`)).option(`--name <name>`,`Output name`).option(`--optimize`,`Bundle loose files into __brarchive archives (--no-optimize to disable)`).option(`--build`,`Build before packing (default; --no-build to skip)`).option(`--skip-build`,`Pack the current pack folders without building first`).option(`--typecheck`,`Run typecheck before packing`).option(`--skip-typecheck`,`Skip typecheck before packing`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).action(e=>ss(`pack`,$a,e)),is($.command(`dev`,`Watch project`)).option(`--mode <value>`,`Execution mode (passed to hooks)`).option(`--copy`,`Copy on change`).option(`--copy-target <target>`,`Copy target`).option(`--skip-copy`,`Skip copy`).option(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--typecheck-command <command>`,`Typecheck command line, e.g. "bun check"`).option(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).option(`--optimize`,`Optimize packed/copied output into __brarchive archives (--no-optimize to disable)`).option(`--timing`,`Show per-step timing`).action(e=>ss(`dev`,so,e)),is($.command(`config`,`Show resolved config`)).option(`--summary`,`Show brief summary instead of full config`).action(e=>ss(`config`,lo,e)),$.command(`profile <command> [...profiles]`,`Analyze Bedrock .cpuprofile captures (summary|bursts|top|diff)`).option(`--cwd <path>`,`Working directory for profile paths`).option(`--gap <ms>`,`Deltas above this are idle gaps (default: 5)`).option(`--min-samples <count>`,`Minimum active samples in a burst (default: 20)`).option(`--from <ms>`,`Restrict top to samples at or after this time`).option(`--to <ms>`,`Restrict top to samples at or before this time`).option(`--by <mode>`,`Count self or total samples (default: self)`).option(`-n, --limit <count>`,`Rows to print or return (default: 15)`).option(`--stacks <count>`,`Stacks per burst (default: 5)`).option(`--root <dir>`,`Make source paths relative to this directory`).option(`--json`,`JSON output`).option(`--silent`,`Silent output`).option(`--verbose`,`Verbose output`).example(`bepack profile summary bedrock.cpuprofile`).example(`bepack profile bursts bedrock.cpuprofile --stacks 10`).example(`bepack profile top bedrock.cpuprofile --from 2900 --to 2950 --by total`).example(`bepack profile diff before.cpuprofile after.cpuprofile`).action((e,t,n)=>ss(`profile`,n=>Xo(e,t??[],n),n)),$.help(),$.version(rs);async function cs(e){if($.unsetMatchedCommand(),$.parse(e,{run:!1}),!$.options.help&&!$.options.version){if(!$.matchedCommand){let e=$.args[0]??$.rawArgs.slice(2).find(e=>e!==`--`&&!e.startsWith(`-`));if(e){os(`cli`,new L(`UNKNOWN_COMMAND`,`Unknown command: ${e}`,{suggestions:["Run `bepack --help` to see available commands."]}),!!$.options.json);return}$.outputHelp();return}try{await $.runMatchedCommand()}catch(e){os(`cli`,e,!!$.options.json)}}}await cs(process.argv);export{};
|