@bepack/cli 0.1.0-beta.1 → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import{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{exec as p,spawn as m}from"node:child_process";import h,{mkdir as g}from"node:fs/promises";import{rolldown as _}from"rolldown";import{createRequire as v}from"module";import y from"chokidar";var b=Object.create,x=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=Object.getOwnPropertyNames,w=Object.getPrototypeOf,T=Object.prototype.hasOwnProperty,E=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},ee=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),D=(e,t)=>{let n={};for(var r in e)x(n,r,{get:e[r],enumerable:!0});return t||x(n,Symbol.toStringTag,{value:`Module`}),n},te=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=C(t),a=0,o=i.length,s;a<o;a++)s=i[a],!T.call(e,s)&&s!==n&&x(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=S(t,s))||r.enumerable});return e},O=(e,t,n)=>(n=e==null?{}:b(w(e)),te(t||!e||!e.__esModule?x(n,`default`,{value:e,enumerable:!0}):n,e));function k(e){return e==null?[]:Array.isArray(e)?e:[e]}function A(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 j(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=k(t.string),t.boolean=k(t.boolean),f)for(n in t.alias)for(r=t.alias[n]=k(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);A(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 M(e){return e.replace(/[<[].+/,``).trim()}function ne(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 re(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 N(e){return e.sort((e,t)=>e.length>t.length?-1:1)[0]}function ie(e,t){return e.length>=t?e:`${e}${` `.repeat(t-e.length)}`}function ae(e){return e.replaceAll(/([a-z])-([a-z])/g,(e,t,n)=>t+n.toUpperCase())}function oe(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 P(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 se(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:``}function ce(e){return e.split(`.`).map((e,t)=>t===0?ae(e):e).join(`.`)}var le=class extends Error{constructor(e){super(e),this.name=`CACError`,typeof Error.captureStackTrace!=`function`&&(this.stack=Error(e).stack)}},ue=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=M(e).split(`,`).map(e=>{let t=e.trim().replace(/^-{1,2}/,``);return t.startsWith(`no-`)&&(this.negated=!0,t=t.replace(/^no-/,``)),ce(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 de,fe;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`,fe=`${process.platform}-${process.arch} ${e}-${process.version}`,de=process.argv}else fe=typeof navigator>`u`?`unknown`:`${navigator.platform} ${navigator.userAgent}`;var pe=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=M(e),this.args=ne(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 ue(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 me}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=N(t.map(e=>e.rawName));a.push({title:`Commands`,body:t.map(e=>` ${ie(e.rawName,n.length)} ${e.description}`).join(`
2
+ import{lstatSync as e,promises as t,readFileSync as n,statSync as r}from"node:fs";import{fileURLToPath as i,pathToFileURL as a}from"node:url";import o,{dirname as s,join as c}from"node:path";import{randomUUID as l}from"node:crypto";import u,{platform as d}from"node:os";import{replacePlugin as f}from"rolldown/plugins";import{exec as p,spawn as m}from"node:child_process";import h,{mkdir as g}from"node:fs/promises";import{rolldown as _}from"rolldown";import{loadConfig as v}from"rolldown/config";import{createRequire as y}from"module";import b from"chokidar";var x=Object.create,S=Object.defineProperty,C=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyNames,T=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,D=(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),ee=(e,t)=>{let n={};for(var r in e)S(n,r,{get:e[r],enumerable:!0});return t||S(n,Symbol.toStringTag,{value:`Module`}),n},k=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=w(t),a=0,o=i.length,s;a<o;a++)s=i[a],!E.call(e,s)&&s!==n&&S(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=C(t,s))||r.enumerable});return e},A=(e,t,n)=>(n=e==null?{}:x(T(e)),k(t||!e||!e.__esModule||!E.call(e,`default`)?S(n,`default`,{value:e,enumerable:!0}):n,e));function j(e){return e==null?[]:Array.isArray(e)?e:[e]}function M(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 N(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=j(t.string),t.boolean=j(t.boolean),f)for(n in t.alias)for(r=t.alias[n]=j(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);M(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 te(e){return e.replace(/[<[].+/,``).trim()}function ne(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 P(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 re(e){return e.sort((e,t)=>e.length>t.length?-1:1)[0]}function ie(e,t){return e.length>=t?e:`${e}${` `.repeat(t-e.length)}`}function ae(e){return e.replaceAll(/([a-z])-([a-z])/g,(e,t,n)=>t+n.toUpperCase())}function F(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 oe(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 se(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:``}function ce(e){return e.split(`.`).map((e,t)=>t===0?ae(e):e).join(`.`)}var le=class extends Error{constructor(e){super(e),this.name=`CACError`,typeof Error.captureStackTrace!=`function`&&(this.stack=Error(e).stack)}},ue=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=te(e).split(`,`).map(e=>{let t=e.trim().replace(/^-{1,2}/,``);return t.startsWith(`no-`)&&(this.negated=!0,t=t.replace(/^no-/,``)),ce(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 de,fe;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`,fe=`${process.platform}-${process.arch} ${e}-${process.version}`,de=process.argv}else fe=typeof navigator>`u`?`unknown`:`${navigator.platform} ${navigator.userAgent}`;var pe=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=te(e),this.args=ne(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 ue(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 me}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=re(t.map(e=>e.rawName));a.push({title:`Commands`,body:t.map(e=>` ${ie(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=N(o.map(e=>e.rawName));a.push({title:`Options`,body:o.map(t=>` ${ie(t.rawName,e.length)} ${t.description} ${t.config.default===void 0?``:`(default: ${t.config.default})`}`).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=re(o.map(e=>e.rawName));a.push({title:`Options`,body:o.map(t=>` ${ie(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} ${fe}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new le(`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 le(`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 le(`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 le(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},me=class extends pe{constructor(e){super(`@@global@@`,``,{},e)}},he=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 me(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new pe(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(!de)throw Error(`No argv provided and runtime process argv is not available.`);e=de}this.rawArgs=e,this.name||=e[1]?se(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=re(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=j(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[ce(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!==`_`&&(oe(c,e.split(`.`),o[e]),P(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 ge=(e=``)=>new he(e);function _e(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function ve(e){return`${JSON.stringify(e,null,4)}\n`}var ye=E((()=>{}));async function F(e){try{return await n.access(e),!0}catch{return!1}}async function be(e){await n.mkdir(e,{recursive:!0})}async function xe(e){await n.rm(e,{recursive:!0,force:!0}),await n.mkdir(e,{recursive:!0})}async function Se(e){return _e(await n.readFile(e,`utf8`),e)}async function Ce(e,t){await be(s.dirname(e)),await n.writeFile(e,ve(t),`utf8`)}async function we(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 Te=E((()=>{ye()})),I,L=E((()=>{I=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=ee(((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}));Te(),L();var De=O(Ee(),1);const R=De.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var Oe=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 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)`}function Ne(e,t){let n=[];for(let r of Pe){let i=r(e,t);i!==null&&(Array.isArray(i)?n.push(...i):n.push(i))}if(n.length>0)throw new I(`MANIFEST_INVALID`,`Manifest validation failed: ${n.join(`; `)}`)}var Pe,Fe=E((()=>{Pe=[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 Ie(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Le(e){return Array.isArray(e)?e:[]}function Re(e){if(!(e&&Object.keys(e).length===0))return e}var ze,Be=E((()=>{L(),Fe(),ze=class{static async read(e){if(!await F(e))return;let t=await n.readFile(e,`utf8`);try{return Ie(JSON.parse(t))}catch{throw new I(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){Ne(t,n),await Ce(e,t)}}}));function Ve(e){let t=/^(\d+)\.(\d+)\.(\d+)$/.exec(e);if(!t)throw new I(`VERSION_INVALID`,`Manifest version requires x.y.z.`,{details:{version:e}});return[Number(t[1]),Number(t[2]),Number(t[3])]}function He(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function z(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 Ue(e){return e===`latest`?!0:z(e,`1.21.120`)>=0}function We(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 Ge(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function Ke(e,t){let n=We(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?We(t[1]):void 0;return!r||n.major!==r.major||Ge(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?z(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}var qe=E((()=>{L()}));function Je(e){if(e===`stable`||e===`beta`||e===`preview`)throw new I(`DEPENDENCY_VERSION_INVALID`,`${e} must be resolved from npm registry before writing package.json.`,{details:{specifier:e}});if(He(e))return e;throw new I(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function Ye(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(z)}function Xe(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(z)}var Ze,Qe=E((()=>{qe(),L(),Ze=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=Ye(this.npm.versions(t)).at(-1);if(!r)throw new I(`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=Xe(this.npm.versions(t)).at(-1);if(!r)throw new I(`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(z).at(-1);if(!a)throw new I(`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 I(`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 I(`SAPI_VERSION_NOT_FOUND`,`Cannot confirm inferred stable version ${s} for ${e}.`,{details:{package:e,target:t,beta:n,inferredStable:s}});return s}}}));function $e(e,t){return t===`latest`||Ue(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function et(e,t,n){let r=Xe(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 I(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest beta version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@beta -> ${r}`),r}function tt(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(z)}function nt(e,t,n){let r=tt(t).at(-1);if(!r)throw new I(`SAPI_VERSION_NOT_FOUND`,`Cannot resolve latest preview version for ${e}.`,{details:{package:e}});return n?.verbose(`Resolved ${e}@preview -> ${r}`),r}function rt(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(z).at(-1);if(!o)throw new I(`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}var it,at=E((()=>{qe(),Qe(),L(),it={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 Ze(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`?et(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:$e(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?nt(e.packageName,e.npm.versions(t),e.logger):rt(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}}})),B,ot=E((()=>{Qe(),at(),B={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 Ze(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?et(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:$e(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?nt(e.packageName,e.npm.versions(t),e.logger):rt(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}}}));function st(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&&lt.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>lt.test(e)).sort(z).at(-1);if(!r)throw new I(`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 I(`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 ct(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=>ut.test(e)).sort(z).at(-1);if(!n)throw new I(`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(z).at(-1);if(!i)throw new I(`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}}var lt,ut,dt,ft=E((()=>{L(),qe(),lt=/^\d+\.\d+\.\d+$/,ut=/^\d+\.\d+\.\d+-preview\.\d+$/,dt={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`?st(e,t):ct(e,t)}}})),pt,mt=E((()=>{at(),ot(),ft(),pt={"@minecraft/common":{resolver:it,manifest:!0},"@minecraft/server":{resolver:it,manifest:!0},"@minecraft/server-ui":{resolver:it,manifest:!0},"@minecraft/server-net":{resolver:B,manifest:!0},"@minecraft/server-admin":{resolver:B,manifest:!0},"@minecraft/server-gametest":{resolver:B,manifest:!0},"@minecraft/debug-utilities":{resolver:B,manifest:!0},"@minecraft/diagnostics":{resolver:B,manifest:!0},"@minecraft/server-graphics":{resolver:B,manifest:!0},"@minecraft/server-editor":{resolver:B,manifest:!0},"@minecraft/vanilla-data":{resolver:dt,manifest:!1}}}));Be(),L(),mt();var ht=class e{static validateHeader(e,t){if(!e.header?.name||!e.header?.uuid)throw new I(`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;pt[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`}};Te(),L();function gt(e,t){if(typeof e!=`string`||!e)throw new I(`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 I(`MANIFEST_INVALID`,`${t} script module entry must be a relative path, got absolute: "${e}".`);if(!n.endsWith(`.js`))throw new I(`MANIFEST_INVALID`,`${t} script module entry must end with .js, got: "${e}".`);let r=n.split(`/`);if(r.includes(`..`))throw new I(`MANIFEST_INVALID`,`${t} script module entry must not contain "..": "${e}".`);if(r.includes(``))throw new I(`MANIFEST_INVALID`,`${t} script module entry must not contain empty segments: "${e}".`);return n}function _t(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 I(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function vt(e,t){if(!t&&await F(e))throw new I(`CONFIG_INVALID`,`Config file already exists: ${e}. Use --force to overwrite.`,{suggestions:[`Pass --force to overwrite the existing file.`]});await be(s.dirname(e))}async function yt(e,t,r){return await vt(e,r),await n.writeFile(e,t,`utf8`),!0}function bt(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
9
- $1$2: `)}\n`}function xt(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function St(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function Ct(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 wt(e,t){let n=t.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new I(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);let r=s.join(e,`bepack.config.${n}`),i=!!t.force,a=new Oe({silent:t.silent,verbose:t.verbose}),o=!!t.fromBp,c=!!t.fromRp,l,u,d,f=!1,p,m,h,g,_,v,y=[];if(o){let n=s.resolve(e,t.fromBp),r=await ze.read(n);if(!r)throw new I(`CONFIG_NOT_FOUND`,`BP manifest not found: ${t.fromBp}`);d??=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`)&&(f=!0);let i=ht.validateHeader(r,`BP`),a=ht.findScriptModuleUuid(r),o=ht.findScriptModuleEntry(r),c=xt(r.header?.version);c&&y.push(c),l={root:_t(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:ht.matchDependencies(r),...o?{scriptEntry:o}:{}},p=i.name,m=i.description,h=i.name,g=i.description}if(c){let n=s.resolve(e,t.fromRp),r=await ze.read(n);if(!r)throw new I(`CONFIG_NOT_FOUND`,`RP manifest not found: ${t.fromRp}`);d??=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`)&&(f=!0);let i=ht.validateHeader(r,`RP`),a=ht.findResourcesModuleUuid(r);if(!a)throw new I(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let c=xt(r.header?.version);c&&y.push(c),u={root:_t(e,n),uuid:i.uuid,moduleUuid:a,...c?{version:c}:{}},o||(p=i.name,m=i.description),_=i.name,v=i.description}let b;if(y.length===1)b=y[0];else if(y.length===2){let e=y[0],t=y[1];if(e===t)b=e;else{let n=Ct(e),r=Ct(t);b=n&&r?St(n,r)>=0?e:t:e,a.warn(`BP version (${e}) and RP version (${t}) differ. Using ${b}.`)}}f&&(a.warn(`Detected format_version ${d} doesn't match the actual version format used in manifest. Falling back to format_version 2.`),d=2);let x={root:`.`,target:`latest`,pack:{outDir:`dist`}};d!==void 0&&(x.manifestFormat=d),b&&(x.version=b),p&&(x.name=p),m&&(x.description=m);let S={};if(l){let e={root:l.root,uuid:l.uuid};if(l.moduleUuid)if(e.moduleUuid=l.moduleUuid,l.scriptEntry){let t=gt(l.scriptEntry,`BP`),n=s.posix.dirname(t),r=s.posix.basename(t,`.js`);if(n===`.`)throw new I(`MANIFEST_INVALID`,`BP manifest script entry "${l.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.`);e.compile={entry:`src/${r}.ts`,scriptOutputDir:n}}else e.compile={entry:`src/main.ts`};h&&(e.name=h),g&&(e.description=g),Object.keys(l.deps).length>0&&(e.dependencies={...l.deps}),S.bp=e}if(u){let e={root:u.root,uuid:u.uuid,moduleUuid:u.moduleUuid};_&&(e.name=_),v&&(e.description=v),S.rp=e}return x.packs=S,process.platform===`win32`&&(x.copy={defaultTarget:`win`}),{ok:!0,command:`init`,filesCreated:[await yt(r,bt(x),i)].filter(Boolean).length}}function Tt(){return bt({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 Et(e){let t=s.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await wt(t,e);let n=e.format??`ts`;if(![`ts`,`js`,`mjs`].includes(n))throw new I(`CONFIG_INVALID`,`init --format must be ts, js, or mjs.`);return{ok:!0,command:`init`,filesCreated:[await yt(s.join(t,`bepack.config.${n}`),Tt(),!!e.force)].filter(Boolean).length}}const Dt=[`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:{}},Ot={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},kt={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:Ot,scriptOutputDir:`scripts`},At=[`world`,`global`,`any`];function jt(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}var Mt,Nt,Pt=E((()=>{Mt=[`scripts`,`manifest.json`,`animation_controllers`,`animations`,`biomes`,`blocks`,`entities`,`functions`,`items`,`loot_tables`,`pack_icon.png`,`recipes`,`spawn_rules`,`structures`,`texts`,`trading`,`feature_rules`,`features`,`worldgen`],Nt=[]}));function Ft(e,t){return s.isAbsolute(t)?t:s.join(e,t)}function H(e){return e.replace(/\\/g,`/`)}function U(e,t){return Ft(e,t.root)}function W(e,t,n){return n===`bp`?t.packs.bp?Ft(e,t.packs.bp.root):void 0:t.packs.rp?Ft(e,t.packs.rp.root):void 0}function It(e,t){let n=W(U(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function Lt(e,t){let n=W(U(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function Rt(e){return!!e.packs.bp?.compile}function zt(e,t){if(t.packs.bp?.compile)return Ft(U(e,t),t.packs.bp.compile.entry)}function Bt(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return s.join(It(e,t),n)}function Vt(e,t){let n=Bt(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 Ht(e,t){let n=s.relative(e,t);return n===``||!n.startsWith(`..${s.sep}`)&&n!==`..`&&!s.isAbsolute(n)}function Ut(e,t,n){if(!t||t===`.`)throw new I(`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 I(`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 I(`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 I(`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&&Ht(a,n))throw new I(`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 Wt(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(Ht(a,t))throw new I(`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 I(`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 I(`BUILD_FAILED`,`Safety check failed: ${n} "${e}" is not inside the BP root "${t}". Refusing to empty this directory.`)}function Gt(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...Mt.filter(e=>e!==`scripts`)],n=e.packs.bp?.include??[],r=[...t,...n],i=new Set;return r.filter(e=>i.has(e)?!1:(i.add(e),!0))}function Kt(e,t){if(t.packs.bp)return s.join(It(e,t),`manifest.json`)}function qt(e,t){if(t.packs.rp)return s.join(Lt(e,t),`manifest.json`)}function Jt(e,t){return Ft(U(e,t),t.pack.outDir)}function Yt(e){let t=new Set;return e.filter(e=>{let n=H(s.resolve(e)),r=Xt?n:n.toLowerCase();return t.has(r)?!1:(t.add(r),!0)})}var Xt,Zt=E((()=>{L(),Pt(),Xt=f()!==`win32`}));Zt();var Qt=Object.create,$t=Object.defineProperty,en=Object.getOwnPropertyDescriptor,tn=Object.getOwnPropertyNames,nn=Object.getPrototypeOf,rn=Object.prototype.hasOwnProperty,an=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),on=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=tn(t),a=0,o=i.length,s;a<o;a++)s=i[a],!rn.call(e,s)&&s!==n&&$t(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=en(t,s))||r.enumerable});return e},sn=(e,t,n)=>(n=e==null?{}:Qt(nn(e)),on(t||!e||!e.__esModule?$t(n,`default`,{value:e,enumerable:!0}):n,e)),G=e(import.meta.url),cn=an(((e,t)=>{let n=G(`node:fs`),r=G(`node:child_process`),i=JSON.parse(n.readFileSync(G.resolve(`rolldown/package.json`),`utf-8`)).version,a=`/tmp/rolldown-${i}`,o=`${a}/node_modules/@rolldown/binding-wasm32-wasi/rolldown-binding.wasi.cjs`;if(!n.existsSync(o)){let e=`@rolldown/binding-wasm32-wasi@${i}`;n.rmSync(a,{recursive:!0,force:!0}),n.mkdirSync(a,{recursive:!0}),console.log(`[rolldown] Downloading ${e} on WebContainer...`),r.execFileSync(`pnpm`,[`i`,e],{cwd:a,stdio:`inherit`})}t.exports=G(o)})),ln=an(((e,t)=>{let{readFileSync:n}=G(`fs`),r=null,i=[],a=()=>{let e=!1;return process.platform===`linux`&&(e=s(),e===null&&(e=c()),e===null&&(e=l())),e},o=e=>e.includes(`libc.musl-`)||e.includes(`ld-musl-`),s=()=>{try{return n(`/usr/bin/ldd`,`utf-8`).includes(`musl`)}catch{return null}},c=()=>{let e=null;return process.report&&typeof process.report.getReport==`function`&&(process.report.excludeNetwork=!0,e=process.report.getReport()),e?e.header&&e.header.glibcVersionRuntime?!1:!!(Array.isArray(e.sharedObjects)&&e.sharedObjects.some(o)):null},l=()=>{try{return G(`child_process`).execSync(`ldd --version`,{encoding:`utf8`}).includes(`musl`)}catch{return!1}};function u(){if(process.env.NAPI_RS_NATIVE_LIBRARY_PATH)try{return G(process.env.NAPI_RS_NATIVE_LIBRARY_PATH)}catch(e){i.push(e)}else if(process.platform===`android`)if(process.arch===`arm64`){try{return G(`./rolldown-binding.android-arm64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-android-arm64`),t=G(`@rolldown/binding-android-arm64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm`){try{return G(`./rolldown-binding.android-arm-eabi.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-android-arm-eabi`),t=G(`@rolldown/binding-android-arm-eabi/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on Android ${process.arch}`));else if(process.platform===`win32`)if(process.arch===`x64`)if(process.config&&process.config.variables&&process.config.variables.shlib_suffix===`dll.a`||process.config&&process.config.variables&&process.config.variables.node_target_type===`shared_library`){try{return G(`./rolldown-binding.win32-x64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-win32-x64-gnu`),t=G(`@rolldown/binding-win32-x64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`./rolldown-binding.win32-x64-msvc.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-win32-x64-msvc`),t=G(`@rolldown/binding-win32-x64-msvc/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`ia32`){try{return G(`./rolldown-binding.win32-ia32-msvc.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-win32-ia32-msvc`),t=G(`@rolldown/binding-win32-ia32-msvc/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm64`){try{return G(`./rolldown-binding.win32-arm64-msvc.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-win32-arm64-msvc`),t=G(`@rolldown/binding-win32-arm64-msvc/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on Windows: ${process.arch}`));else if(process.platform===`darwin`){try{return G(`./rolldown-binding.darwin-universal.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-darwin-universal`),t=G(`@rolldown/binding-darwin-universal/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}if(process.arch===`x64`){try{return G(`./rolldown-binding.darwin-x64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-darwin-x64`),t=G(`@rolldown/binding-darwin-x64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm64`){try{return G(`./rolldown-binding.darwin-arm64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-darwin-arm64`),t=G(`@rolldown/binding-darwin-arm64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on macOS: ${process.arch}`))}else if(process.platform===`freebsd`)if(process.arch===`x64`){try{return G(`./rolldown-binding.freebsd-x64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-freebsd-x64`),t=G(`@rolldown/binding-freebsd-x64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm64`){try{return G(`./rolldown-binding.freebsd-arm64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-freebsd-arm64`),t=G(`@rolldown/binding-freebsd-arm64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on FreeBSD: ${process.arch}`));else if(process.platform===`linux`)if(process.arch===`x64`)if(a()){try{return G(`./rolldown-binding.linux-x64-musl.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-x64-musl`),t=G(`@rolldown/binding-linux-x64-musl/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`../rolldown-binding.linux-x64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-x64-gnu`),t=G(`@rolldown/binding-linux-x64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm64`)if(a()){try{return G(`./rolldown-binding.linux-arm64-musl.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-arm64-musl`),t=G(`@rolldown/binding-linux-arm64-musl/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`./rolldown-binding.linux-arm64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-arm64-gnu`),t=G(`@rolldown/binding-linux-arm64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm`)if(a()){try{return G(`./rolldown-binding.linux-arm-musleabihf.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-arm-musleabihf`),t=G(`@rolldown/binding-linux-arm-musleabihf/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`./rolldown-binding.linux-arm-gnueabihf.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-arm-gnueabihf`),t=G(`@rolldown/binding-linux-arm-gnueabihf/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`loong64`)if(a()){try{return G(`./rolldown-binding.linux-loong64-musl.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-loong64-musl`),t=G(`@rolldown/binding-linux-loong64-musl/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`./rolldown-binding.linux-loong64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-loong64-gnu`),t=G(`@rolldown/binding-linux-loong64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`riscv64`)if(a()){try{return G(`./rolldown-binding.linux-riscv64-musl.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-riscv64-musl`),t=G(`@rolldown/binding-linux-riscv64-musl/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else{try{return G(`./rolldown-binding.linux-riscv64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-riscv64-gnu`),t=G(`@rolldown/binding-linux-riscv64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`ppc64`){try{return G(`./rolldown-binding.linux-ppc64-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-ppc64-gnu`),t=G(`@rolldown/binding-linux-ppc64-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`s390x`){try{return G(`./rolldown-binding.linux-s390x-gnu.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-linux-s390x-gnu`),t=G(`@rolldown/binding-linux-s390x-gnu/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on Linux: ${process.arch}`));else if(process.platform===`openharmony`)if(process.arch===`arm64`){try{return G(`./rolldown-binding.openharmony-arm64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-openharmony-arm64`),t=G(`@rolldown/binding-openharmony-arm64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`x64`){try{return G(`./rolldown-binding.openharmony-x64.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-openharmony-x64`),t=G(`@rolldown/binding-openharmony-x64/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else if(process.arch===`arm`){try{return G(`./rolldown-binding.openharmony-arm.node`)}catch(e){i.push(e)}try{let e=G(`@rolldown/binding-openharmony-arm`),t=G(`@rolldown/binding-openharmony-arm/package.json`).version;if(t!==`1.1.4`&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK&&process.env.NAPI_RS_ENFORCE_VERSION_CHECK!==`0`)throw Error(`Native binding package version mismatch, expected 1.1.4 but got ${t}. You can reinstall dependencies to fix this issue.`);return e}catch(e){i.push(e)}}else i.push(Error(`Unsupported architecture on OpenHarmony: ${process.arch}`));else i.push(Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`))}r=u();let d=process.env.NAPI_RS_FORCE_WASI===`true`||process.env.NAPI_RS_FORCE_WASI===`error`;if(!r||d){let e=null,t=null;try{e=G(`../rolldown-binding.wasi.cjs`),r=e}catch(e){d&&(t=e)}if(!r||d)try{e=G(`@rolldown/binding-wasm32-wasi`),r=e}catch(e){d&&(t?t.cause=e:t=e,i.push(e))}if(process.env.NAPI_RS_FORCE_WASI===`error`&&!e){let e=Error(`WASI binding not found and NAPI_RS_FORCE_WASI is set to error`);throw e.cause=t,e}}if(!r&&globalThis.process?.versions?.webcontainer)try{r=cn()}catch(e){i.push(e)}if(!r){if(i.length>0){let e=Error("Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.");throw e.cause=i.reduce((e,t)=>(t.cause=e,t)),e}throw Error(`Failed to load native binding`)}t.exports=r,t.exports.LegalCommentsMode=r.LegalCommentsMode,t.exports.minify=r.minify,t.exports.minifySync=r.minifySync,t.exports.Severity=r.Severity,t.exports.ParseResult=r.ParseResult,t.exports.ExportExportNameKind=r.ExportExportNameKind,t.exports.ExportImportNameKind=r.ExportImportNameKind,t.exports.ExportLocalNameKind=r.ExportLocalNameKind,t.exports.ImportNameKind=r.ImportNameKind,t.exports.parse=r.parse,t.exports.parseSync=r.parseSync,t.exports.rawTransferSupported=r.rawTransferSupported,t.exports.ResolverFactory=r.ResolverFactory,t.exports.EnforceExtension=r.EnforceExtension,t.exports.ModuleType=r.ModuleType,t.exports.sync=r.sync,t.exports.HelperMode=r.HelperMode,t.exports.isolatedDeclaration=r.isolatedDeclaration,t.exports.isolatedDeclarationSync=r.isolatedDeclarationSync,t.exports.moduleRunnerTransform=r.moduleRunnerTransform,t.exports.moduleRunnerTransformSync=r.moduleRunnerTransformSync,t.exports.transform=r.transform,t.exports.transformSync=r.transformSync,t.exports.BindingBundleEndEventData=r.BindingBundleEndEventData,t.exports.BindingBundleErrorEventData=r.BindingBundleErrorEventData,t.exports.BindingBundler=r.BindingBundler,t.exports.BindingCallableBuiltinPlugin=r.BindingCallableBuiltinPlugin,t.exports.BindingChunkingContext=r.BindingChunkingContext,t.exports.BindingDecodedMap=r.BindingDecodedMap,t.exports.BindingDevEngine=r.BindingDevEngine,t.exports.BindingLoadPluginContext=r.BindingLoadPluginContext,t.exports.BindingMagicString=r.BindingMagicString,t.exports.BindingModuleInfo=r.BindingModuleInfo,t.exports.BindingNormalizedOptions=r.BindingNormalizedOptions,t.exports.BindingOutputAsset=r.BindingOutputAsset,t.exports.BindingOutputChunk=r.BindingOutputChunk,t.exports.BindingPluginContext=r.BindingPluginContext,t.exports.BindingRenderedChunk=r.BindingRenderedChunk,t.exports.BindingRenderedChunkMeta=r.BindingRenderedChunkMeta,t.exports.BindingRenderedModule=r.BindingRenderedModule,t.exports.BindingSourceMap=r.BindingSourceMap,t.exports.BindingTransformPluginContext=r.BindingTransformPluginContext,t.exports.BindingWatcher=r.BindingWatcher,t.exports.BindingWatcherBundler=r.BindingWatcherBundler,t.exports.BindingWatcherChangeData=r.BindingWatcherChangeData,t.exports.BindingWatcherEvent=r.BindingWatcherEvent,t.exports.ParallelJsPluginRegistry=r.ParallelJsPluginRegistry,t.exports.TraceSubscriberGuard=r.TraceSubscriberGuard,t.exports.TsconfigCache=r.TsconfigCache,t.exports.BindingAttachDebugInfo=r.BindingAttachDebugInfo,t.exports.BindingBuiltinPluginName=r.BindingBuiltinPluginName,t.exports.BindingChunkModuleOrderBy=r.BindingChunkModuleOrderBy,t.exports.BindingErrorStage=r.BindingErrorStage,t.exports.BindingLogLevel=r.BindingLogLevel,t.exports.BindingPluginOrder=r.BindingPluginOrder,t.exports.BindingPropertyReadSideEffects=r.BindingPropertyReadSideEffects,t.exports.BindingPropertyWriteSideEffects=r.BindingPropertyWriteSideEffects,t.exports.BindingRebuildStrategy=r.BindingRebuildStrategy,t.exports.collapseSourcemaps=r.collapseSourcemaps,t.exports.enhancedTransform=r.enhancedTransform,t.exports.enhancedTransformSync=r.enhancedTransformSync,t.exports.FilterTokenKind=r.FilterTokenKind,t.exports.initTraceSubscriber=r.initTraceSubscriber,t.exports.registerPlugins=r.registerPlugins,t.exports.resolveTsconfig=r.resolveTsconfig,t.exports.shutdownAsyncRuntime=r.shutdownAsyncRuntime,t.exports.startAsyncRuntime=r.startAsyncRuntime}));function un(e,t,{hook:n,id:r}={}){try{let i=e.code;!e.pluginCode&&i!=null&&(typeof i!=`string`||!i.startsWith(`PLUGIN_`))&&(e.pluginCode=i),e.code=`PLUGIN_ERROR`,e.plugin=t,n&&(e.hook=n),r&&(e.id=r)}catch{}finally{return e}}function dn(e){throw e instanceof Error||(e=Object.assign(Error(e.message),e),Object.defineProperty(e,"name",{value:`RolldownError`,writable:!0})),e}var fn=sn(ln(),1),pn=class{name;_options;enforce;constructor(e,t){this.name=e,this._options=t}};function mn(e){let t=new fn.BindingCallableBuiltinPlugin(hn(e)),n=e;for(let r in t){let i=async function(...i){try{return await t[r](...i)}catch(t){return t instanceof Error&&!t.stack?.includes(`at `)&&Error.captureStackTrace(t,n[r]),dn(un(t,e.name,{hook:r,id:r===`transform`?i[2]:void 0}))}},a=t.getOrder(r);a==null?n[r]=i:n[r]={handler:i,order:a}}return n}function hn(e){return{__name:e.name,options:e._options}}function gn(e={},t={}){return Object.keys(e).forEach(t=>{let n=e[t];typeof n!=`string`&&(e[t]=String(n))}),mn(new pn(`builtin:replace`,{...t,values:e}))}const _n={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function vn(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function yn(e){let t=vn(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,_n[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[gn(r,{delimiters:[``,``]})]}function bn(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}}}L();function xn(e){let t={...e??{}};for(let[e,n]of Object.entries(t))try{Function(`return (${n});`)}catch{throw new I(`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 Sn(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}qe(),Qe();const Cn={name:`exact-version`,match:e=>He(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Je(e.specifier),manifestVersion:e.specifier}}};L(),at(),ot(),ft();const wn=[it,B,dt,Cn];var Tn=class e{resolvers;pluginNames=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,...wn],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 I(`PLUGIN_FAILED`,`Plugin ${t} resolver ${n.name} match failed: ${e instanceof Error?e.message:String(e)}`):e}if(!t)throw new I(`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 I(`PLUGIN_FAILED`,`Plugin ${n} resolver ${t.name} failed: ${e instanceof Error?e.message:String(e)}`):e}}};mt(),L(),qe();const En=`sapi-pro`,Dn=[`@minecraft/server`,`@minecraft/server-ui`];function On(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function kn(e){return On(e)?`beta`:`stable`}function An(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function jn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function Mn(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...pt,...e.config.install.dependencyCatalog},o=Tn.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==Pn),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||Dn.includes(s)&&On(c)!==On(u.packageVersion)||!Ke(u.packageVersion,c))return!1}return!0}function Nn(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!An(e))return!1;let r=jn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>z(e,t)).reverse()}const Pn={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(En),n=new Map,r=new Set;for(let[i,a]of Nn(t.versions??{},e.specifier))if(await Mn(e,jn(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 I(`SAPI_VERSION_NOT_FOUND`,`Cannot find a compatible ${En}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:En,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 Fn(){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[En];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(kn(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[En]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[Pn]}}}const In={"sapi-pro":Fn};L();function K(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function Ln(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...K(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...K(t.packs?.rp)});let r={...e.copy?.targets??{},...K(t.copy?.targets)},i=K(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...K(t.install)},build:{...e.build,...K(t.build)},dev:{...e.dev,...K(t.dev)},copy:{...e.copy,...K(t.copy),targets:r},pack:{...e.pack,...K(t.pack)},hooks:{...e.hooks,...K(t.hooks)}}}function Rn(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=In[e];if(!t)throw new I(`CONFIG_INVALID`,`Unknown built-in plugin: ${e}.`);return t()}),n=new Set;for(let e of t){if(!e?.name||e.name.trim()===``)throw new I(`CONFIG_INVALID`,`Every plugin must have a non-empty name.`);if(n.has(e.name))throw new I(`CONFIG_INVALID`,`Plugin name is duplicated: ${e.name}.`);if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new I(`CONFIG_INVALID`,`Plugin ${e.name} requires unsupported BePack plugin API version ${e.apiVersion}.`);if(e.priority!==void 0&&!Number.isFinite(e.priority))throw new I(`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 zn(e,t){let n=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 I(`PLUGIN_FAILED`,`Plugin ${t.name} ${String(n)} hook failed: ${e instanceof Error?e.message:String(e)}`):e}return t}]}))}function Bn(e,t){let n={},r=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 Vn(e,t,n){let r=kt,i=e?.scriptOutputDir??r.scriptOutputDir,a=s.resolve(n,e?.entry??r.entry),o=Ut(t,i,s.dirname(a));return{entry:e?.entry??r.entry,define:xn(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:e?.typecheck??r.typecheck,preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:c(e?.cache),scriptOutputDir:o};function c(e){let t=Ot;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function Hn(e){let t=e?.merge??`preserve`;if(t!==`preserve`&&t!==`clean`)throw new I(`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 I(`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 Un(e,t={},n=process.cwd()){let r=Ln(e,t),i=Rn(r.plugins),a=r.target??V.target;if(a===`stable`||a===`beta`)throw new I(`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 I(`CONFIG_INVALID`,`At least one pack (packs.bp or packs.rp) is required.`);if(!r.name||r.name.trim()===``)throw new I(`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 I(`CONFIG_INVALID`,`packs.bp.uuid is required.`);if(m.compile&&!m.moduleUuid)throw new I(`CONFIG_INVALID`,`packs.bp.moduleUuid is required when packs.bp.compile is configured.`);if(m.root===void 0)throw new I(`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 I(`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 I(`CONFIG_INVALID`,`packs.rp.uuid and packs.rp.moduleUuid are required.`);if(h.root===void 0)throw new I(`CONFIG_INVALID`,`packs.rp.root is required when packs.rp is configured.`);if(h.packScope!==void 0&&!At.includes(h.packScope))throw new I(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${At.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=Bn(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]);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:bn(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:Vn(p,_,g)}:{},manifest:Hn(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:Hn(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??{}},pack:{name:r.pack?.name??V.pack.name,outDir:r.pack?.outDir??V.pack.outDir},hooks:zn(i,r.hooks)}}L(),Zt();async function Wn(e,t){if(t){let r=Ft(e,t);return await n.access(r).catch(()=>{throw new I(`CONFIG_NOT_FOUND`,`Config not found: ${t}`,{details:{configPath:t}})}),r}for(let t of Dt){let r=s.join(e,t);try{return await n.access(r),r}catch{}}throw new I(`CONFIG_NOT_FOUND`,`No bepack.config.ts, bepack.config.mjs, or bepack.config.js found.`,{details:{cwd:e}})}async function Gn(e){try{if(e.endsWith(`.ts`))try{return await import(`${o(e).href}?t=${Date.now()}`)}catch{let t=Kn(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 I(`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 Kn(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 qn(e,t){for(let n of e.plugins??[])if(n.configResolved)try{await n.configResolved({cwd:t,config:e})}catch(e){throw new I(`PLUGIN_FAILED`,`Plugin ${n.name} configResolved hook failed: ${e instanceof Error?e.message:String(e)}`)}}async function Jn(e){let t=s.resolve(e.cwd),n=await Wn(t,e.configPath),r=await Gn(n);if(r.default===void 0)throw new I(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=Un(r.default,e.overrides,t);return await qn(i,t),{config:i,path:n,cwd:t}}function Yn(e){return{...pt,...e.install.dependencyCatalog}}function Xn(e,t){let n=e[t];if(!n)throw new I(`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}var Zn=E((()=>{L(),mt()}));Zn(),L();function Qn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var $n=class{registry;logger;cache=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;Qn(this.logger,`fetching ${e} metadata from ${this.registry}`);let r=await fetch(t);if(!r.ok)throw new I(`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/,`@`)}`}};L(),Qe();function er(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var tr=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new $n(e.install.registry,t),this.catalog=Yn(e),this.pkgResolver=new Ze(this.npm,t),this.log=er(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=Xn(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 Tn.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 I(`PLUGIN_FAILED`,`Plugin ${n.name} ${e} hook failed: ${t instanceof Error?t.message:String(t)}`)}}}};L(),Te();async function nr(e,t,n,r=!1){let i=s.join(e,`package.json`);if(!await F(i))throw new I(`PACKAGE_JSON_NOT_FOUND`,`package.json not found.`,{details:{cwd:e}});let a=await Se(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 Ce(i,a),{updated:!0,path:`package.json`}}var rr,ir,ar=E((()=>{rr=[1,21,0],ir=[1,0,0]})),or,sr=E((()=>{L(),ar(),qe(),Be(),or=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=Ve(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Ie(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=Ie(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:this.cleanMinEngineVersion(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:this.cleanMinEngineVersion(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)}}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)}}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:!1}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[...Le(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Le(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=Re(t);n?e.metadata=n:delete e.metadata}}applyPbrCapability(e,t){if(t.pbr===!0){let t=Le(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Le(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`:ir}getWriteFormatVersion(e){return this.config.manifestFormat===void 0?e.format_version??2:this.config.manifestFormat}normalizeMinEngineVersion(e,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)}cleanMinEngineVersion(e,t){return e===void 0?this.defaultMinEngineVersion(t):t===3?e:this.stringToVersionTuple(e)??this.defaultMinEngineVersion(t)}defaultMinEngineVersion(e){return e===3?`1.21.0`:rr}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 I(`CONFIG_INVALID`,`packs.bp is required to build the BP manifest.`);return this.config.packs.bp}requireRp(){if(!this.config.packs.rp)throw new I(`CONFIG_INVALID`,`packs.rp is required to build the RP manifest.`);return this.config.packs.rp}}})),cr,lr=E((()=>{L(),qe(),Be(),cr=class e{config;catalog;resolvedDeps;version;versionStr;constructor(e,t,n){this.config=e,this.catalog=t,this.resolvedDeps=n??{},this.version=Ve(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(e){let{specifier:t,target:n,resolvedVersion:r}=e;if(t===`stable`){if(r)return r;throw new I(`DEPENDENCY_REQUIRES_INSTALL`,"Run `bepack install` to resolve stable manifest dependencies.",{details:{specifier:t,target:n}})}if(t===`beta`){if(Ue(n))return`beta`;if(r)return r;throw new I(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve manifest dependencies for target ${n}.`,{details:{target:n}})}if(t===`preview`){if(r)return r;throw new I(`DEPENDENCY_REQUIRES_INSTALL`,`Run \`bepack install\` to resolve preview manifest dependencies for target ${n}.`,{details:{specifier:t,target:n}})}return t}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 I(`UNSUPPORTED_DEPENDENCY`,`${t} is not a managed dependency.`,{details:{package:t},suggestions:n})}if(!e.isAllowedSpecifier(n))throw new I(`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 I(`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.config.packs.bp)return[];let t=[];for(let[n,r]of Object.entries(this.config.packs.bp.dependencies))this.catalog[n]?.manifest&&t.push({module_name:n,version:e.resolveVersion({specifier:r,target:this.config.target,resolvedVersion:this.resolvedDeps[n]})});return t}getFormatAwareVersion(e){return(e??this.config.manifestFormat??2)===3?this.versionStr:this.version}replaceBpDependencies(e,t,n){let r=Le(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=Le(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]}}})),ur=D({patchManifest:()=>dr});async function dr(e){let t=Yn(e.config),n=e.config.packs.bp?Kt(e.cwd,e.config):void 0,r=n?await ze.read(n):void 0,i=fr(r,t),a=new cr(e.config,t,e.resolvedDeps?{...i,...e.resolvedDeps}:i),o=new or(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 i=o.buildBp(r);e.dryRun||await ze.write(n,i,`bp`),c.bpManifest={path:H(s.relative(e.cwd,n)),updated:!0,existed:t}}if(e.config.packs.rp){let t=qt(e.cwd,e.config),n=await ze.read(t),r=n!==void 0,i=o.buildRp(n);e.dryRun||await ze.write(t,i,`rp`),c.rpManifest={path:H(s.relative(e.cwd,t)),updated:!0,existed:r}}return c}function fr(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}var pr=E((()=>{Zt(),Zn(),Be(),sr(),lr()}));pr(),L(),Te();var mr=class{cwd;registry;constructor(e,t){this.cwd=e,this.registry=t}async detect(e){if(e!==`auto`)return e;let t=s.join(this.cwd,`package.json`);if(await F(t)){let e=(await Se(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await F(s.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await F(s.join(this.cwd,`yarn.lock`))?`yarn`:await F(s.join(this.cwd,`bun.lock`))||await F(s.join(this.cwd,`bun.lockb`))?`bun`:`npm`}async install(e){let{command:t,args:n}=this.commandForPlatform(e,this.installArgs(e));return await new Promise((r,i)=>{let a;try{a=m(t,n,{cwd:this.cwd,stdio:`inherit`})}catch(t){i(new I(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t instanceof Error?t.message:String(t)}}));return}a.on(`error`,t=>i(new I(`PACKAGE_MANAGER_NOT_FOUND`,`${e} is not available.`,{details:{manager:e,cause:t.message}}))),a.on(`exit`,t=>{t&&t!==0?i(new I(`PACKAGE_MANAGER_FAILED`,`${e} install failed.`,{details:{manager:e,registry:this.registry,exitCode:t}})):r(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}};L(),Zt();function hr(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 gr(e,t){let n={dist:Jt(e,t)};if(t.packs.bp&&(n.bpRoot=It(e,t),n.bpManifest=Kt(e,t),Rt(t))){let r=zt(e,t);r&&(n.srcEntry=r);let i=Vt(e,t);i&&(n.scriptOutFile=i);let a=Bt(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=Lt(e,t),n.rpManifest=qt(e,t)),n}async function q(e,t,n,r,i,a){let o=r.hooks[e];if(o)try{let s=await o({command:t,cwd:n,...a===void 0?{}:{mode:a},target:r.target,config:r,paths:gr(n,r),logger:i});i.hook(String(e),hr(s))}catch(t){throw new I(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function _r(e){let t=new Oe({...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 Jn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await q(`beforeInstall`,`install`,r,i,t);let a=await new tr(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 nr(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await dr({cwd:r,config:i,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new mr(r,i.install.registry),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 q(`afterInstall`,`install`,r,i,t),t.success(`Install`,`done`),{ok:!0,command:`install`,target:i.target,packageManager:l,resolved:a,files:s,packageInstall:u}}pr();async function vr(e){let t=new Oe({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Jn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}});await q(`beforeManifest`,`manifest`,n,r,t);let i=await dr({cwd:n,config:r,dryRun:e.dryRun,logger:t});return await q(`afterManifest`,`manifest`,n,r,t),t.success(`Manifest`,e.dryRun?`dry-run complete`:`updated manifest.json`),{ok:!0,command:`manifest`,target:r.target,files:i}}L(),Te();function yr(e,t,n,r){let i=e?`npx tsc --noEmit`:`tsc --noEmit`;return i+=` --project "${t}"`,n&&r&&(i+=` --incremental --tsBuildInfoFile "${r}"`),i}async function br(e,t={}){let n=t.tsconfigPath??`tsconfig.json`,r=s.resolve(e,n);if(!await F(r))throw new I(`TYPECHECK_FAILED`,`TypeScript config not found: ${n}. Create it or run build with --skip-typecheck.`,{details:{path:n}});t.incremental&&t.tsBuildInfoFile&&await g(s.dirname(t.tsBuildInfoFile),{recursive:!0});let i=yr(!!t.useNpx,r,!!t.incremental,t.tsBuildInfoFile);await new Promise((n,r)=>{let a=``,o=``,s;try{s=p(i,{cwd:e,windowsHide:!0,maxBuffer:1024*1024*10},e=>{if(!e){n();return}let s=[a.trim(),o.trim()].filter(Boolean).join(`
10
- `),c=s.includes(`not recognized`)||s.includes(`not found`)||s.includes(`ENOENT`)||s.includes(`不是内部或外部命令`),l=c?t.useNpx?[`Install npm/npx or set packs.bp.compile.entry to skip typecheck.`]:["Install TypeScript globally so `tsc` is available.",`Set packs.bp.compile.useNpx: true to use the project local TypeScript.`]:void 0;r(new I(`TYPECHECK_FAILED`,c?`Cannot find ${t.useNpx?`npx`:`tsc`}.`:`${i} failed.`,{details:{command:i,exitCode:typeof e.code==`number`?e.code:null,...s?{diagnostics:s}:{}},...l?{suggestions:l}:{}}))})}catch(e){r(new I(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e instanceof Error?e.message:String(e)},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}));return}s.on(`error`,e=>{r(new I(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e.message},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}))}),s.stdout?.on(`data`,e=>{a+=String(e),t.quiet||process.stdout.write(e)}),s.stderr?.on(`data`,e=>{o+=String(e),t.quiet||process.stderr.write(e)})})}L(),Te(),Zt(),Zn();function xr(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(Yn(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function Sr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}function Cr(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 I(`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 I)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 I(`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 wr(e,t,n){let r=s.resolve(e),i=s.resolve(t);if(Ht(r,i)||Ht(i,r))throw new I(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function Tr(e,t,n,r){let i=U(e,t),a=It(e,t),o=s.join(a,`manifest.json`),c=[s.join(i,`.git`),s.join(a,`.git`)];for(let e of c)wr(r,e,`.git metadata`);if(t.packs.rp){let e=W(i,t,`rp`);s.resolve(e)!==s.resolve(a)&&wr(r,e,`RP root`)}wr(r,o,`BP manifest`);let l=s.dirname(n),u=s.relative(a,l);Wt(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!s.isAbsolute(u)?[l]:[]),Cr(a,r)}async function Er(e,t,n){if(!Rt(t))throw new I(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let r=zt(e,t),i=Bt(e,t),a=Vt(e,t);if(!r||!i||!a)throw new I(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);try{Tr(e,t,r,i),await xe(i);let o=t.packs.bp.compile.define,c=await _({input:r,external:xr(t),plugins:yn(t),...Sn(o)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:t.packs.bp.compile.preserveModules?`none`:`simple`}});t.packs.bp.compile.preserveModules?await c.write({dir:i,format:`esm`,preserveModules:!0,preserveModulesRoot:s.dirname(r),entryFileNames:`[name].js`,minify:t.packs.bp.compile.minify}):await c.write({file:a,format:`esm`,minify:t.packs.bp.compile.minify}),await c.close(),await Dr(i,n)}catch(e){throw new I(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function Dr(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} (${Sr(n[0].size)})`:`${n.length} files, total ${Sr(i)}`)}pr(),Zt();async function Or(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function kr(e){let t=Date.now(),n=e.config.build.timing,r=U(e.cwd,e.config),i=Rt(e.config);await Or(`manifest`,()=>dr({cwd:e.cwd,config:e.config,dryRun:!!e.dryRun,logger:e.logger,...e.resolvedDeps?{resolvedDeps:e.resolvedDeps}:{}}),e.logger,n);let a=[];e.config.packs.bp&&a.push(`bp`),e.config.packs.rp&&a.push(`rp`),e.logger.manifest(`manifest.json updated (${a.join(`, `)})`),await q(`beforeBuild`,`build`,e.cwd,e.config,e.logger,e.mode);let o=!1;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;await Or(`typecheck`,()=>br(r,{quiet:!!e.quiet,useNpx:t.useNpx,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{}}),e.logger,n),o=!0,e.logger.typescript(`typecheck complete`)}i&&!e.dryRun&&(await Or(`rolldown`,()=>Er(e.cwd,e.config,e.logger),e.logger,n),e.logger.rolldown(e.config.packs.bp.compile.preserveModules?`preserve modules build complete`:`bundle complete`)),await q(`afterBuild`,`build`,e.cwd,e.config,e.logger,e.mode);let c=Date.now()-t;return{script:i?H(Vt(e.cwd,e.config)):void 0,compiled:i,typecheck:o,durationMs:c}}L();const Ar={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 I(`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 jr(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 Mr(e,t){let n=t??e.copy.defaultTarget;if(!n)throw new I(`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]??Ar[n]?.();if(!r)throw new I(`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:jr(e,r),names:l}:{name:n,target:r,names:l}}L(),Te(),Zt(),Pt();const Nr=De.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Pr(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 Fr(e,t){let n=s.resolve(e),r=s.resolve(t);if(Ht(n,r)||Ht(r,n))throw new I(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function Ir(e,t){let n=s.resolve(e),r=s.resolve(n,t);if(r===n||!Ht(n,r))throw new I(`COPY_FAILED`,`Copy folder name "${t}" must resolve to a directory inside "${e}".`,{details:{targetDir:n,folderName:t,destination:r}});return r}async function Lr(e,t){if(!await F(e))throw new I(`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 Rr(e,t){if(t===`bp`)return Gt(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...Nt,...i]:[]}async function zr(e,t,n,r,i,a,o){let s=Rr(i,e),c=Ir(n,r);Fr(t,c),a||(e===`bp`||s.length>0?await Pr(t,c,s):await we(t,c));let l=s.length>0?s.length:void 0;return o?.copy(`${a?`would copy`:`copied`} ${e}${l?` (${l} items)`:``} -> ${Nr.gray(c)}`),c}async function Br(e,t,n,r=!1,i){let{name:a,target:o,names:s}=Mr(t,n),c=[],l=U(e,t),u=jt(t);for(let e of u){let n;if(n=e.type===`bp`?o.bp:o.rp,!n)continue;await Lr(n,e.type);let a=s[e.type]??e.name,u=W(l,t,e.type),d=await zr(e.type,u,n,a,t,r,i);c.push(d)}return{target:a,copied:c}}function Vr(e,t){return wi(e,t||{},0,0)}function Hr(e,t){if(t){for(var n=new J(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(Di)return Di.encode(e);for(var i=e.length,a=new J(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 J(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 li(a,0,o)}function Ur(e,t){t||={};var n={},r=[];Ei(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=Hr(o),f=d.length,p=l.comment,m=p&&Hr(p),h=m&&m.length,g=ki(l.extra);f>65535&&di(11);var _=u?Vr(c,l):c,v=_.length,y=Ci();y.p(c),r.push(Ti(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 J(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];Ai(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+ki(d.extra);b.set(d.c,d.o+w),Ai(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return ji(b,i,r.length,S,x),b}var Wr,Gr,J,Y,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,X,ni,ri,ii,ai,oi,si,ci,li,ui,di,Z,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Q,Ei,Di,Oi,ki,Ai,ji,Mi=E((()=>{Wr=v(`/`);try{Gr=Wr("worker_threads"),Gr.Worker,Gr.isMarkedAsUntransferable}catch{}for(J=Uint8Array,Y=Uint16Array,Kr=Int32Array,qr=new J([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]),Jr=new J([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]),Yr=new J([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xr=function(e,t){for(var n=new Y(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Kr(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}},Gr=Xr(qr,2),Zr=Gr.b,Qr=Gr.r,Zr[28]=258,Qr[258]=28,$r=Xr(Jr,0),$r.b,ei=$r.r,ti=new Y(32768),X=0;X<32768;++X)ni=(X&43690)>>1|(X&21845)<<1,ni=(ni&52428)>>2|(ni&13107)<<2,ni=(ni&61680)>>4|(ni&3855)<<4,ti[X]=((ni&65280)>>8|(ni&255)<<8)>>1;for(ri=(function(e,t,n){for(var r=e.length,i=0,a=new Y(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Y(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Y(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[ti[d]>>c]=l}else for(s=new Y(r),i=0;i<r;++i)e[i]&&(s[i]=ti[o[e[i]-1]++]>>15-e[i]);return s}),ii=new J(288),X=0;X<144;++X)ii[X]=8;for(X=144;X<256;++X)ii[X]=9;for(X=256;X<280;++X)ii[X]=7;for(X=280;X<288;++X)ii[X]=8;for(ai=new J(32),X=0;X<32;++X)ai[X]=5;oi=ri(ii,9,0),si=ri(ai,5,0),ci=function(e){return(e+7)/8|0},li=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new J(e.subarray(t,n))},ui=[`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`],di=function(e,t,n){var r=Error(t||ui[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,di),!n)throw r;return r},Z=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},fi=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},pi=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:bi,l:0};if(i==1){var o=new J(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 Y(f+1),m=mi(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 J(p),l:m}},mi=function(e,t,n){return e.s==-1?Math.max(mi(e.l,t,n+1),mi(e.r,t,n+1)):t[e.s]=n},hi=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Y(++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}},gi=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},_i=function(e,t,n){var r=n.length,i=ci(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},vi=function(e,t,n,r,i,a,o,s,c,l,u){Z(t,u++,n),++i[256];for(var d=pi(i,15),f=d.t,p=d.l,m=pi(a,15),h=m.t,g=m.l,_=hi(f),v=_.c,y=_.n,b=hi(h),x=b.c,S=b.n,C=new Y(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=pi(C,7),E=T.t,ee=T.l,D=19;D>4&&!E[Yr[D-1]];--D);var te=l+5<<3,O=gi(i,ii)+gi(a,ai)+o,k=gi(i,f)+gi(a,h)+o+14+3*D+gi(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&te<=O&&te<=k)return _i(t,u,e.subarray(c,c+l));var A,j,M,ne;if(Z(t,u,1+(k<O)),u+=2,k<O){A=ri(f,p,0),j=f,M=ri(h,g,0),ne=h;var re=ri(E,ee,0);Z(t,u,y-257),Z(t,u+5,S-1),Z(t,u+10,D-4),u+=14;for(var w=0;w<D;++w)Z(t,u+3*w,E[Yr[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 oe=ae[w]&31;Z(t,u,re[oe]),u+=E[oe],oe>15&&(Z(t,u,ae[w]>>5&127),u+=ae[w]>>12)}}else A=oi,j=ii,M=si,ne=ai;for(var w=0;w<s;++w){var P=r[w];if(P>255){var oe=P>>18&31;fi(t,u,A[oe+257]),u+=j[oe+257],oe>7&&(Z(t,u,P>>23&31),u+=qr[oe]);var se=P&31;fi(t,u,M[se]),u+=ne[se],se>3&&(fi(t,u,P>>5&8191),u+=Jr[se])}else fi(t,u,A[P]),u+=j[P]}return fi(t,u,A[256]),u+j[256]},yi=new Kr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bi=new J(0),xi=function(e,t,n,r,i,a){var o=a.z||e.length,s=new J(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=yi[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new Y(32768),g=a.h||new Y(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new Kr(25e3),x=new Y(288),S=new Y(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=vi(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),oe=Math.min(258,A);N<=ae&&--re&&O!=k;){if(e[T+M]==e[T+M-N]){for(var P=0;P<oe&&e[T+P]==e[T+P-N];++P);if(P>M){if(M=P,ne=N,P>ie)break;for(var se=Math.min(N,P-2),ce=0,j=0;j<se;++j){var le=T-N+j&32767,ue=le-h[le]&32767;ue>ce&&(ce=ue,k=le)}}}O=k,k=h[O],N+=O-k&32767}if(ne){b[E++]=268435456|Qr[M]<<18|ei[ne];var de=Qr[M]&31,fe=ei[ne]&31;w+=qr[de]+Jr[fe],++x[257+de],++S[fe],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=vi(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 pe=T+65535;pe>=o&&(c[u/8|0]=l,pe=o),u=_i(c,u+1,e.subarray(T,pe))}a.i=o}return li(s,0,r+ci(u)+i)},Si=(function(){for(var e=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})(),Ci=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=Si[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},wi=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new J(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return xi(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)},Ti=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},Q=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},Ei=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=Ti(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new J(0),s],Ei(a,o,n,r))}},Di=typeof TextEncoder<`u`&&new TextEncoder,Oi=typeof TextDecoder<`u`&&new TextDecoder;try{Oi.decode(bi,{stream:!0})}catch{}ki=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&di(9),t+=r+4}return t},Ai=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=ki(l);Q(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)&&di(10),Q(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(Q(e,t,n.crc),Q(e,t+4,a<0?-a-2:a),Q(e,t+8,n.size)),Q(e,t+12,c),Q(e,t+14,d),t+=16,o!=null&&(Q(e,t,u),Q(e,t+6,n.attrs),Q(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;Q(e,t,+m),Q(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},ji=function(e,t,n,r,i){Q(e,t,101010256),Q(e,t+8,n),Q(e,t+10,n),Q(e,t+12,r),Q(e,t+16,i)}}));async function Ni(e,t,r,i=``){let a=await n.readdir(t,{withFileTypes:!0});for(let o of a){let a=s.join(t,o.name),c=i?`${i}/${o.name}`:o.name;o.isDirectory()?await Ni(e,a,r,c):r[c]=new Uint8Array(await n.readFile(a))}}async function Pi(e,t,r){let i=s.join(e,t);try{(await n.stat(i)).isDirectory()?await Ni(e,i,r,t):r[t]=new Uint8Array(await n.readFile(i))}catch{}}async function Fi(e,t){let r={};await Ni(e,e,r),await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,Ur(r))}async function Ii(e,t,r){let i={};for(let n of t)await Pi(e,n,i);await n.mkdir(s.dirname(r),{recursive:!0}),await n.writeFile(r,Ur(i))}async function Li(e,t){let r={};for(let t of e){let e=s.basename(s.resolve(t.source));for(let i of t.items){let a=s.join(t.source,i);try{(await n.stat(a)).isDirectory()?await Ni(t.source,a,r,`${e}/${i}`):r[`${e}/${i}`]=new Uint8Array(await n.readFile(a))}catch{}}}await n.mkdir(s.dirname(t),{recursive:!0}),await n.writeFile(t,Ur(r))}async function Ri(e,t,r){let i={};for(let t of e){let e=s.basename(s.resolve(t.source));for(let r of t.items){let a=s.join(t.source,r);try{(await n.stat(a)).isDirectory()?await Ni(t.source,a,i,`${e}/${r}`):i[`${e}/${r}`]=new Uint8Array(await n.readFile(a))}catch{}}}for(let e of t)await Ni(e.dir,e.dir,i,s.basename(s.resolve(e.dir)));await n.mkdir(s.dirname(r),{recursive:!0}),await n.writeFile(r,Ur(i))}var zi=E((()=>{Mi()})),Bi=D({packMcpack:()=>Vi});async function Vi(e,t,n,r=!1){let i=s.join(t,`${n}.mcpack`);return r||await Fi(e,i),i}var Hi=E((()=>{zi()}));zi(),Zt(),Pt(),L();function Ui(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 I(`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 Wi(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 I(`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 Gi(e,t){let n=s.relative(s.resolve(t),s.resolve(e));if(n.startsWith(`..`)||s.isAbsolute(n))throw new I(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:s.resolve(e),dist:s.resolve(t)}})}function Ki(e,t){if(t===`bp`)return{items:Gt(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:[...Nt,...i],selective:!0}:{items:[],selective:!1}}async function qi(e,t,n={}){let r=U(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=Jt(e,t);if(jt(t).length===0)throw new I(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let o=t.packs.bp?{root:W(r,t,`bp`),config:t}:void 0,c=t.packs.rp?{root:W(r,t,`rp`),config:t}:void 0,l=o?Ki(t,`bp`):void 0;if(o&&c){if(!l)throw new I(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcaddon`);if(Gi(e,a),l?.selective&&Wi(e,o.root,l.items),Ui(e,c.root,`RP`),!n.dryRun){let n=Ki(t,`rp`);n.selective?await Li([{source:o.root,items:l.items},{source:c.root,items:n.items}],e):await Ri([{source:o.root,items:l.items}],[{dir:c.root}],e)}return e}if(o){if(!l)throw new I(`PACK_FAILED`,`BP pack configuration is missing.`);let e=s.join(a,`${i}.mcpack`);return Gi(e,a),l?.selective&&Wi(e,o.root,l.items),n.dryRun||await Ii(o.root,l.items,e),e}if(c){let e=s.join(a,`${i}.mcpack`);if(Gi(e,a),Ui(e,c.root,`RP`),!n.dryRun){let r=Ki(t,`rp`);if(r.selective)await Ii(c.root,r.items,e);else{let{packMcpack:e}=await Promise.resolve().then(()=>(Hi(),Bi));return await e(c.root,a,i,n.dryRun)}}return e}throw new I(`PACK_FAILED`,`No packs configured.`)}async function Ji(e,t,n,r={}){let i=Date.now();await q(`beforePack`,`pack`,e,t,n);let a=await qi(e,t,r);await q(`afterPack`,`pack`,e,t,n);let o=Date.now()-i;return n.done(`pack`,`packed ${a} in ${n.formatDuration(o)}`),{output:a,durationMs:o}}async function Yi(e){let t=new Oe({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Jn({cwd:e.cwd??process.cwd(),configPath:e.config}),{output:i,durationMs:a}=await Ji(n,r,t,{name:e.name,dryRun:e.dryRun});return{ok:!0,command:`pack`,durationMs:a,output:i}}L();function Xi(e){for(let t of[[`copy`,`skipCopy`],[`pack`,`skipPack`],[`typecheck`,`skipTypecheck`],[`install`,`skipInstall`]]){let[n,r]=t;if(e[n]&&e[r])throw new I(`CLI_ARGUMENT_CONFLICT`,`--${n} and --${r} cannot be used together.`)}}async function Zi(e){Xi(e);let t=new Oe({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Jn({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 _r({...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.cache===void 0?a?.cache.build??!1:e.cache,c=await kr({cwd:n,config:r,logger:t,mode:e.mode,typecheck:!!o,cache:!!s,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),l=null,u=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;u&&(l=await Br(n,r,e.copyTarget??(typeof u==`string`?u:void 0),e.dryRun,t));let d=null;return!e.skipPack&&e.pack&&(d=await Ji(n,r,t,{name:e.name,dryRun:e.dryRun})),t.done(`build`,`complete in ${t.formatDuration(c.durationMs)}`),{ok:!0,command:`build`,durationMs:c.durationMs,build:c,copy:l,pack:d}}async function Qi(e){let t=Date.now(),n=new Oe({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Jn({cwd:e.cwd??process.cwd(),configPath:e.config});await q(`beforeCopy`,`copy`,r,i,n);let a=e.all?[`win`,`winold`,...Object.keys(i.copy.targets)]:[e.target??i.copy.defaultTarget],o=[];for(let t of a)o.push(await Br(r,i,t,e.dryRun,n));await q(`afterCopy`,`copy`,r,i,n);let s=Date.now()-t;return n.done(`copy`,`${e.dryRun?`dry-run complete`:`complete`} in ${n.formatDuration(s)}`),{ok:!0,command:`copy`,durationMs:s,results:o}}Zt();function $i(e,t){return H(s.relative(e,t))}function ea(e,t,n,r){let i=U(e,t),a=Rt(t),o=[];if(a){let n=zt(e,t);n&&o.push($i(e,s.dirname(n)))}if(r.copy){for(let n of jt(t))if(W(i,t,n.type)){let r=ta(e,t,n.type,i);o.push(...r)}}let c=t.dev.watch?.include??[];o.push(...c);let l=Yt(o.map(t=>s.resolve(e,t))).map(t=>$i(e,t)),u=[`node_modules`,`.git`,$i(e,Jt(e,t))];for(let n of jt(t)){let r=W(i,t,n.type);if(r&&(u.push($i(e,s.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=W(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push($i(e,s.join(n,r)))}}let d=y.watch(l,{cwd:e,ignored:u,ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await Br(e,t,r.copyTarget,r.dryRun,n)},g=async()=>{let{patchManifest:i}=await Promise.resolve().then(()=>(pr(),ur));await i({cwd:e,config:t,dryRun:r.dryRun,logger:n}),await h()},_=async()=>{if(a)await kr({cwd:e,config:t,logger:n,typecheck:r.typecheck,cache:r.cache,dryRun:r.dryRun,quiet:!!r.quiet,...r.mode===void 0?{}:{mode:r.mode}});else{let{patchManifest:i}=await Promise.resolve().then(()=>(pr(),ur));await i({cwd:e,config:t,dryRun:r.dryRun,logger:n})}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?zt(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 b=t.packs.bp?H(s.relative(e,W(i,t,`bp`))):null,x=t.packs.rp?H(s.relative(e,W(i,t,`rp`))):null,S=a&&zt(e,t)?$i(e,s.dirname(zt(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)b&&(e===b||e.startsWith(b+`/`))?(T++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))?(E++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):S&&(e===S||e.startsWith(S+`/`))||w.push(e);return S&&!C&&w.unshift(S),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function ta(e,t,n,r){let i=W(r,t,n);if(!i)return[];if(n===`bp`)return Gt(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 na(e){let t=Date.now(),n=new Oe({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Jn({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.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),c=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),l=a?.cache.dev??!0,u=!!e.dryRun,d=!!(e.json||e.silent);return await kr({cwd:r,config:i,logger:n,mode:e.mode,typecheck:!!o,cache:l,dryRun:u,quiet:d}),s&&await Br(r,i,c,u,n),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),ea(r,i,n,{copy:s,mode:e.mode,...c?{copyTarget:c}:{},typecheck:!!o,cache:l,dryRun:u,quiet:d}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}Zn();function ra(e){let t=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 ia(e){let t=new Oe({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await Jn({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:ra(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.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(Yn(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=ra(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`}}L();function aa(e){return e instanceof I?{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 oa(e){console.log(JSON.stringify(e,null,4))}L();const sa=De.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`),ca=l(c(a(import.meta.url)),`../package.json`);let la;try{let e=JSON.parse(r(ca,`utf-8`));(typeof e.version!=`string`||!e.version)&&(console.error(`ERROR: package.json missing valid 'version' field`),process.exit(1)),la=e.version}catch(e){console.error(`ERROR: Failed to read package version: ${e.message}`),process.exit(1)}const $=ge(`bepack`);function ua(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 da=!1;function fa(e,t,n){let r=aa(t);if(n)oa({ok:!1,command:e,error:r});else if(t instanceof I){if(console.error(`${sa.red(r.code)}: ${r.message}`),r.suggestions?.length)for(let e of r.suggestions)console.error(` ${sa.dim(`→`)} ${e}`);da&&r.stack&&console.error(`${sa.dim(r.stack)}`)}else t instanceof Error?(console.error(`${sa.red(`ERROR`)}: ${t.message}`),da&&r.stack&&console.error(`${sa.dim(r.stack)}`)):console.error(`${sa.red(`ERROR`)}: ${String(t)}`);process.exitCode=1}async function pa(e,t,n){da=!!n.verbose;try{let e=await t(n);n.json&&oa(e)}catch(t){fa(e,t,!!n.json)}}ua($.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=>pa(`init`,Et,e)),ua($.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=>pa(`install`,_r,e)),ua($.command(`manifest`,`Patch manifest files`)).option(`--target <target>`,`Target MC version`).action(e=>pa(`manifest`,vr,e)),ua($.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(`--typecheck`,`Run typecheck`).option(`--skip-typecheck`,`Skip typecheck`).option(`--preserve-modules`,`Preserve module output`).option(`--use-npx`,`Use npx tsc for typecheck`).option(`--minify`,`Minify output`).option(`--cache`,`Enable incremental compilation cache (--no-cache to disable)`).option(`--timing`,`Show per-step timing`).action(e=>pa(`build`,Zi,e)),ua($.command(`copy`,`Copy packs`)).option(`--target <target>`,`Copy target`).option(`--all`,`Copy to all targets`).action(e=>pa(`copy`,Qi,e)),ua($.command(`pack`,`Pack mcpack/mcaddon`)).option(`--name <name>`,`Output name`).action(e=>pa(`pack`,Yi,e)),ua($.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(`--timing`,`Show per-step timing`).action(e=>pa(`dev`,na,e)),ua($.command(`config`,`Show resolved config`)).option(`--summary`,`Show brief summary instead of full config`).action(e=>pa(`config`,ia,e)),$.help(),$.version(la);async function ma(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){fa(`cli`,new I(`UNKNOWN_COMMAND`,`Unknown command: ${e}`,{suggestions:["Run `bepack --help` to see available commands."]}),!!$.options.json);return}$.outputHelp();return}try{await $.runMatchedCommand()}catch(e){fa(`cli`,e,!!$.options.json)}}}await ma(process.argv);export{};
8
+ `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;t&&console.info(`${e}/${t} ${fe}`)}checkRequiredArgs(){let e=this.args.filter(e=>e.required).length;if(this.cli.args.length<e)throw new le(`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 le(`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 le(`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 le(`Unused args: ${this.cli.args.slice(e).map(e=>`\`${e}\``).join(`, `)}`)}},me=class extends pe{constructor(e){super(`@@global@@`,``,{},e)}},he=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 me(this),this.globalCommand.usage(`<command> [options]`)}usage(e){return this.globalCommand.usage(e),this}command(e,t,n){let r=new pe(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(!de)throw Error(`No argv provided and runtime process argv is not available.`);e=de}this.rawArgs=e,this.name||=e[1]?se(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=P(n),i=[],a=e.indexOf(`--`);a!==-1&&(i=e.slice(a+1),e=e.slice(0,a));let o=N(e,r);o=Object.keys(o).reduce((e,t)=>({...e,[ce(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!==`_`&&(F(c,e.split(`.`),o[e]),oe(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 ge=(e=``)=>new he(e);function _e(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Invalid JSON in ${t}: ${e instanceof Error?e.message:String(e)}`)}}function ve(e){return`${JSON.stringify(e,null,4)}\n`}async function I(e){try{return await t.access(e),!0}catch{return!1}}async function ye(e){await t.mkdir(e,{recursive:!0})}async function be(e){await t.rm(e,{recursive:!0,force:!0}),await t.mkdir(e,{recursive:!0})}async function xe(e){return _e(await t.readFile(e,`utf8`),e)}async function Se(e,n){await ye(o.dirname(e)),await t.writeFile(e,ve(n),`utf8`)}async function Ce(e,n){await t.rm(n,{recursive:!0,force:!0}),await t.mkdir(o.dirname(n),{recursive:!0}),await t.cp(e,n,{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}},we=/* @__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 R=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);var Te=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 Ee(e){return Array.isArray(e)&&e.length===3&&typeof e[0]==`number`&&typeof e[1]==`number`&&typeof e[2]==`number`}function De(e){return typeof e==`string`&&/^\d+\.\d+\.\d+$/.test(e)}function Oe(e){return e===3?De:Ee}function ke(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 Ae=[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?Oe(e.format_version)(e.header.version)?null:ke(e.format_version,`header.version`):null,e=>e.header?Oe(e.format_version)(e.header.min_engine_version)?null:ke(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=Oe(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`}): ${ke(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=Oe(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}): ${ke(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 je(e,t){let n=[];for(let r of Ae){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 Me(e){return!e||typeof e!=`object`||Array.isArray(e)?{}:{...e}}function Ne(e){return Array.isArray(e)?e:[]}var Pe=class{static async read(e){if(!await I(e))return;let n=await t.readFile(e,`utf8`);try{return Me(JSON.parse(n))}catch{throw new L(`MANIFEST_INVALID`,`Invalid JSON in manifest: ${e}`)}}static async write(e,t,n){je(t,n),await Se(e,t)}};function Fe(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 Ie(e){return/^\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/.test(e)}function z(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 Le(e){return e===`latest`||z(e,`1.21.120`)>=0}function Re(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 ze(e,t){for(let n of[`major`,`minor`,`patch`])if(e[n]!==t[n])return e[n]-t[n];return 0}function Be(e,t){let n=Re(e);return n?t.split(`||`).some(e=>{let t=/(?:\^|~|>=|<=|>|<|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(e.trim()),r=t?Re(t[1]):void 0;return!r||n.major!==r.major||ze(n,r)<0?!1:r.minecraftTarget?n.minecraftTarget?z(n.minecraftTarget.join(`.`),r.minecraftTarget.join(`.`))>=0:!1:!0}):!1}function Ve(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(Ie(e))return e;throw new L(`DEPENDENCY_VERSION_INVALID`,`Unsupported dependency version: ${e}`,{details:{specifier:e}})}function He(e){return e.filter(e=>/^\d+\.\d+\.\d+$/.test(e)).sort(z)}function Ue(e){return e.filter(e=>/(?:^|[-.])beta(?:[-.]|$)/i.test(e)).sort(z)}var We=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=He(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=Ue(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(z).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 Ge(e,t){return t===`latest`||Le(t)?`beta`:/^(\d+\.\d+\.\d+-beta)/i.exec(e)?.[1]??e}function Ke(e,t,n){let r=Ue(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 qe(e){return e.filter(e=>/(?:rc|beta)\.\d+\.\d+\.\d+-preview\.\d+$/i.test(e)).sort(z)}function Je(e,t,n){let r=qe(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 Ye(e,t,n,r){let i=n.replace(/\./g,`\\.`),a=RegExp(`(?:rc|beta)\\.${i}-preview\\.\\d+$`),o=t.filter(e=>a.test(e)).sort(z).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 Xe={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 We(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`?Ke(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ge(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):Ye(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},Ze={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 We(e.npm,e.logger);if(e.specifier===`beta`){e.logger?.verbose(`Resolving ${e.packageName}@beta for target ${e.target}`);let r=e.target===`latest`?Ke(e.packageName,e.npm.versions(t),e.logger):n.betaForTarget(e.packageName,e.target,t);return{packageVersion:r,manifestVersion:Ge(r,e.target)}}e.logger?.verbose(`Resolving ${e.packageName}@preview for target ${e.target}`);let r=e.target===`latest`?Je(e.packageName,e.npm.versions(t),e.logger):Ye(e.packageName,e.npm.versions(t),e.target,e.logger);return{packageVersion:r,manifestVersion:r}}},Qe=/^\d+\.\d+\.\d+$/,$e=/^\d+\.\d+\.\d+-preview\.\d+$/,et={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`?tt(e,t):nt(e,t)}};function tt(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&&Qe.test(n))return e.logger?.verbose(`Resolved ${e.packageName}@stable -> ${n}`),{packageVersion:n};let r=e.npm.versions(t).filter(e=>Qe.test(e)).sort(z).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 nt(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=>$e.test(e)).sort(z).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(z).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 rt={"@minecraft/common":{resolver:Xe,manifest:!0},"@minecraft/server":{resolver:Xe,manifest:!0},"@minecraft/server-ui":{resolver:Xe,manifest:!0},"@minecraft/server-net":{resolver:Ze,manifest:!0},"@minecraft/server-admin":{resolver:Ze,manifest:!0},"@minecraft/server-gametest":{resolver:Ze,manifest:!0},"@minecraft/debug-utilities":{resolver:Ze,manifest:!0},"@minecraft/diagnostics":{resolver:Ze,manifest:!0},"@minecraft/server-graphics":{resolver:Ze,manifest:!0},"@minecraft/server-editor":{resolver:Ze,manifest:!0},"@minecraft/vanilla-data":{resolver:et,manifest:!1}};var it=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;rt[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 at(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(o.posix.isAbsolute(n)||o.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 ot(e,t){let n=o.resolve(e,t),r=o.dirname(n),i=o.relative(e,r);if(i.startsWith(`..`)||o.isAbsolute(i))throw new L(`CONFIG_INVALID`,`Manifest path is outside the project directory: ${t}`);return i||`.`}async function st(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 ct(e,n,r,i=!1){return await st(e,r),!i&&(await ye(o.dirname(e)),await t.writeFile(e,n,`utf8`),!0)}const lt=[`.ts`,`.mts`,`.js`,`.mjs`];async function ut(e,t){let n=(t===`main`?[`main`]:[t,`main`]).flatMap(e=>lt.map(t=>`src/${e}${t}`));for(let t of n)if(await I(o.join(e,t))){let e=o.extname(t);return{entry:t,typecheckable:e===`.ts`||e===`.mts`,searched:n}}}function dt(e){return(e===`main`?[`main`]:[e,`main`]).map(e=>`src/${e}.{${lt.join(`,`).replace(/\./g,``)}}`).join(` or `)}function ft(e){return`export default ${JSON.stringify(e,null,4).replace(/\n( +)"([a-zA-Z_$][a-zA-Z0-9_$]*)": /g,`
9
+ $1$2: `)}\n`}function pt(e){if(e){if(Array.isArray(e))return e.join(`.`);if(typeof e==`string`)return e}}function mt(e,t){return e[0]===t[0]?e[1]===t[1]?e[2]-t[2]:e[1]-t[1]:e[0]-t[0]}function ht(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 gt(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=o.join(e,`bepack.config.${n}`),i=!!t.force,a=!!t.dryRun,s=new Te({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=o.resolve(e,t.fromBp),r=await Pe.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=it.validateHeader(r,`BP`),a=it.findScriptModuleUuid(r),s=it.findScriptModuleEntry(r),c=pt(r.header?.version);c&&b.push(c),u={root:ot(e,n),uuid:i.uuid,...a?{moduleUuid:a}:{},...c?{version:c}:{},deps:it.matchDependencies(r),...s?{scriptEntry:s}:{}},m=i.name,h=i.description,g=i.name,_=i.description}if(l){let n=o.resolve(e,t.fromRp),r=await Pe.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=it.validateHeader(r,`RP`),a=it.findResourcesModuleUuid(r);if(!a)throw new L(`MANIFEST_INVALID`,`RP manifest is missing a resources module with uuid`);let s=pt(r.header?.version);s&&b.push(s),d={root:ot(e,n),uuid:i.uuid,moduleUuid:a,...s?{version:s}:{}},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=ht(e),r=ht(t);x=n&&r?mt(n,r)>=0?e:t:e,s.warn(`BP version (${e}) and RP version (${t}) differ. Using ${x}.`)}}p&&(s.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=at(u.scriptEntry,`BP`),r=o.posix.dirname(n),i=o.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 ut(e,i);if(a){let n=await I(o.join(e,`tsconfig.json`)),i=a.typecheckable&&n;t.compile={entry:a.entry,scriptOutputDir:r,...i?{}:{typecheck:!1}},i||s.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 s.warn(`BP manifest declares script entry "${u.scriptEntry}" but no matching source file exists (looked for ${dt(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 s.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 ct(r,ft(S),i,a);return a&&s.info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:a,filesCreated:+!!w,files:[r]}}function _t(){return ft({root:`.`,name:`example-addon`,version:`1.0.0`,target:`latest`,packs:{bp:{root:`bp`,uuid:l(),moduleUuid:l(),compile:{entry:`src/main.ts`},dependencies:{"@minecraft/server":`stable`}}},pack:{outDir:`dist`}})}async function vt(e){let t=o.resolve(e.cwd??process.cwd());if(e.fromBp||e.fromRp)return await gt(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=o.join(t,`bepack.config.${n}`),i=!!e.dryRun,a=await ct(r,_t(),!!e.force,i);return i&&new Te({silent:e.silent,verbose:e.verbose}).info(`init dry-run: would create ${r}`),{ok:!0,command:`init`,dryRun:i,filesCreated:+!!a,files:[r]}}const yt=[`bepack.config.ts`,`bepack.config.mjs`,`bepack.config.js`],B={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:{}},bt={dev:!0,build:!1,file:`node_modules/.cache/bepack/tsconfig.tsbuildinfo`},xt={keepLooseFiles:!1,keepLoose:[],exclude:[],minifyJson:!0,packOptimizationVersion:`0.1.0`,allowUnsupportedTarget:!1},St={entry:`src/main.ts`,define:{},tsconfig:`tsconfig.json`,typecheck:!0,preserveModules:!0,external:[/^@minecraft\/server.*/],useNpx:!1,minify:!1,cache:bt,scriptOutputDir:`scripts`},Ct=[`world`,`global`,`any`];function wt(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 Tt=[`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`],Et=[];function Dt(e,t){return o.isAbsolute(t)?t:o.join(e,t)}function V(e){return e.replace(/\\/g,`/`)}function H(e,t){return Dt(e,t.root)}function U(e,t,n){return n===`bp`?t.packs.bp?Dt(e,t.packs.bp.root):void 0:t.packs.rp?Dt(e,t.packs.rp.root):void 0}function Ot(e,t){let n=U(H(e,t),t,`bp`);if(!n)throw Error(`packs.bp is not configured`);return n}function kt(e,t){let n=U(H(e,t),t,`rp`);if(!n)throw Error(`packs.rp is not configured`);return n}function At(e){return!!e.packs.bp?.compile}function W(e,t){if(t.packs.bp?.compile)return Dt(H(e,t),t.packs.bp.compile.entry)}function jt(e,t){if(!t.packs.bp)return;let n=t.packs.bp.compile?.scriptOutputDir??`scripts`;return o.join(Ot(e,t),n)}function Mt(e,t){let n=jt(e,t);if(!n)return;if(!t.packs.bp?.compile)return o.join(n,`main.js`);let r=o.basename(t.packs.bp.compile.entry,o.extname(t.packs.bp.compile.entry));return o.join(n,`${r}.js`)}function Nt(e,t){let n=o.relative(e,t);return n===``||!n.startsWith(`..${o.sep}`)&&n!==`..`&&!o.isAbsolute(n)}function Pt(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(o.posix.isAbsolute(r)||o.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=o.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=o.resolve(e,i),s=o.relative(e,a);if(!s||s.startsWith(`..`)||o.isAbsolute(s))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&&Nt(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 V(s)}function Ft(e,t,n,i=[]){let a=o.resolve(e),s=o.resolve(t),c=[s,...i.map(e=>o.resolve(e))];for(let t of c)if(Nt(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(!r(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=o.relative(s,a);if(!l||l.startsWith(`..`)||o.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 It(e){let t=[e.packs.bp?.compile?.scriptOutputDir??`scripts`,...Tt.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 Lt(e,t){if(t.packs.bp)return o.join(Ot(e,t),`manifest.json`)}function Rt(e,t){if(t.packs.rp)return o.join(kt(e,t),`manifest.json`)}function zt(e,t){return Dt(H(e,t),t.pack.outDir)}const Bt=d()!==`win32`;function Vt(e){let t=/* @__PURE__ */ new Set;return e.filter(e=>{let n=V(o.resolve(e)),r=Bt?n:n.toLowerCase();return!t.has(r)&&(t.add(r),!0)})}const Ht={VERSION:e=>e.version,NAME:e=>e.name,UUID:e=>e.packs.bp?.uuid??``,DESCRIPTION:e=>e.packs.bp?.description??e.description??``};function Ut(e){return Object.fromEntries(Object.entries(e.replace.values).map(([t,n])=>[t,typeof n==`function`?n(e):n]))}function Wt(e){let t=Ut(e),n=Object.fromEntries(Object.entries(e.replace.builtins).filter(([,e])=>e).map(([t])=>[`**${t}**`,Ht[t](e)])),r={...t,...n};return Object.keys(r).length===0?[]:[f(r,{delimiters:[``,``]})]}function Gt(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 Kt(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 qt(e){return Object.keys(e).length>0?{transform:{define:e}}:void 0}const Jt=[Xe,Ze,et,{name:`exact-version`,match:e=>Ie(e.specifier),resolve(e){return e.logger?.verbose(`Using exact ${e.packageName}@${e.specifier}`),{packageVersion:Ve(e.specifier),manifestVersion:e.specifier}}}];var Yt=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,...Jt],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 Xt=`sapi-pro`,Zt=[`@minecraft/server`,`@minecraft/server-ui`];function Qt(e){return/(?:beta|preview|alpha|rc)/i.test(e)}function $t(e){return Qt(e)?`beta`:`stable`}function en(e){let t=/^(\d+)\.(\d+)\./.exec(e);return!!t&&(Number(t[1])>0||Number(t[2])>=4)}function tn(e){return{...e.dependencies??{},...e.peerDependencies??{}}}async function nn(e,t,n,r){let i=e.config.packs.bp?.dependencies??{},a={...rt,...e.config.install.dependencyCatalog},o=Yt.fromConfig(e.config.install.dependencyResolvers.filter(e=>e!==an),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||Zt.includes(s)&&Qt(c)!==Qt(u.packageVersion)||!Be(u.packageVersion,c))return!1}return!0}function rn(e,t){if(t!==`stable`&&t!==`beta`){let n=e[t];return n?[[t,n]]:[]}return Object.entries(e).filter(([e,n])=>{if(!en(e))return!1;let r=tn(n);return Object.keys(r).length===0?!1:t===`stable`?/-stable(?:\.\d+)?$/i.test(e):/^\d+\.\d+\.\d+$/.test(e)}).sort(([e],[t])=>z(e,t)).reverse()}const an={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(Xt),n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set;for(let[i,a]of rn(t.versions??{},e.specifier))if(await nn(e,tn(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 ${Xt}@${e.specifier} for target ${e.target}.${r.size>0?` Missing explicit dependencies: ${[...r].join(`, `)}.`:``}`,{details:{package:Xt,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 on(){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[Xt];if(!n)return;let r=Zt.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 Zt){let r=t[e];if($t(r)!==n)throw Error(`sapi-pro ${n} requires ${e} to use ${n}, received ${r}.`)}},install:{dependencyCatalog:{[Xt]:{resolver:`sapi-pro`,manifest:!1}},dependencyResolvers:[an]}}}const sn={"sapi-pro":on};function G(e){return e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{}}function cn(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 ln(e,t){let n={};(e.packs?.bp||t.packs?.bp)&&(n.bp={...e.packs?.bp??{},...G(t.packs?.bp)}),(e.packs?.rp||t.packs?.rp)&&(n.rp={...e.packs?.rp??{},...G(t.packs?.rp)});let r={...e.copy?.targets??{},...G(t.copy?.targets)},i=G(t);return{...e,...i,...t.plugins!==void 0||e.plugins!==void 0?{plugins:t.plugins??e.plugins}:{},packs:n,install:{...e.install,...G(t.install)},build:{...e.build,...G(t.build)},dev:{...e.dev,...G(t.dev)},copy:{...e.copy,...G(t.copy),targets:r},pack:{...e.pack,...G(t.pack)},hooks:{...e.hooks,...G(t.hooks)}}}function un(e){let t=(e??[]).map(e=>{if(typeof e!=`string`)return e;let t=sn[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 dn(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 fn(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 pn(e,t,n){let r=St,i=e?.scriptOutputDir??r.scriptOutputDir,a=o.resolve(n,e?.entry??r.entry),s=Pt(t,i,o.dirname(a));return{entry:e?.entry??r.entry,define:Kt(e?.define),tsconfig:e?.tsconfig??r.tsconfig,typecheck:e?.typecheck??r.typecheck,preserveModules:e?.preserveModules??r.preserveModules,external:e?.external??r.external,useNpx:e?.useNpx??r.useNpx,minify:e?.minify??r.minify,cache:u(e?.cache),scriptOutputDir:s,...e?.rolldown===void 0?{}:{rolldown:c(e.rolldown)},...e?.rolldownConfig===void 0?{}:{rolldownConfig:l(e.rolldownConfig)}};function c(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: ${cn(e)}.`)}function l(e){if(typeof e!=`string`||e.trim()===``)throw new L(`CONFIG_INVALID`,`packs.bp.compile.rolldownConfig must be a non-empty path string, got: ${cn(e)}.`);return e}function u(e){let t=bt;return{dev:e?.dev??t.dev,build:e?.build??t.build,file:e?.file??t.file}}}function mn(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: ${cn(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: ${cn(n)}.`);return{keepLooseFiles:t.keepLooseFiles??xt.keepLooseFiles,keepLoose:t.keepLoose!==!1&&(t.keepLoose??[]).map(hn),exclude:(t.exclude??[]).map(hn),minifyJson:t.minifyJson??xt.minifyJson,packOptimizationVersion:n??xt.packOptimizationVersion,allowUnsupportedTarget:t.allowUnsupportedTarget??xt.allowUnsupportedTarget}}function hn(e){let t=String(e).replace(/\\/g,`/`).replace(/^\.\//,``).replace(/\/+$/,``);if(!t||t.includes(`/`)||t.includes(`..`)||o.posix.isAbsolute(t))throw new L(`CONFIG_INVALID`,`pack.optimize.exclude entries must be top-level folder names (no path separators, no ".."), got: ${cn(e)}.`);return t}function gn(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 _n(e,t={},n=process.cwd()){let r=ln(e,t),i=un(r.plugins),a=r.target??B.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 s=!!r.packs?.bp,c=!!r.packs?.rp;if(!s&&!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??B.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=o.resolve(n,r.root??`.`),_=m?o.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&&!Ct.includes(h.packScope))throw new L(`CONFIG_INVALID`,`packs.rp.packScope must be one of ${Ct.map(e=>`"${e}"`).join(`, `)}.`,{details:{packScope:h.packScope}})}let v=m?.description??d,y=h?.description??d,{catalog:b,diagnostics:x}=fn(i,r.install?.dependencyCatalog??{}),S=i.flatMap(e=>e.install?.dependencyResolvers??[]),C=mn(r.pack?.optimize),w=mn(r.copy?.optimize);return{root:r.root??B.root,configured:{root:r.root!==void 0,packOutDir:r.pack?.outDir!==void 0},name:l,version:u,...d===void 0?{}:{description:d},replace:Gt(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:pn(p,_,g)}:{},manifest:gn(m.manifest),dependencies:m.dependencies??{},include:m.include??[]}}:{},...h?{rp:{root:h.root,uuid:h.uuid,moduleUuid:h.moduleUuid,name:h.name??l,...y===void 0?{}:{description:y},manifest:gn(h.manifest),...h.pbr===void 0?{}:{pbr:h.pbr},...h.packScope===void 0?{}:{packScope:h.packScope},include:h.include??[]}}:{}},install:{registry:r.install?.registry??B.install.registry,saveTo:r.install?.saveTo??B.install.saveTo,packageManager:r.install?.packageManager??B.install.packageManager,runPackageManager:r.install?.runPackageManager??B.install.runPackageManager,updatePackageJson:r.install?.updatePackageJson??B.install.updatePackageJson,updateManifest:r.install?.updateManifest??B.install.updateManifest,dependencyCatalog:b,dependencyResolvers:[...S,...r.install?.dependencyResolvers??[]]},build:{copy:r.build?.copy??B.build.copy,timing:r.build?.timing??B.build.timing},dev:{copy:r.dev?.copy??B.dev.copy,...r.dev?.watch?{watch:r.dev.watch}:{}},copy:{defaultTarget:r.copy?.defaultTarget??B.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??B.pack.name,outDir:r.pack?.outDir??B.pack.outDir,...C?{optimize:C}:{}},hooks:dn(i,r.hooks)}}async function vn(e,n){if(n){let r=Dt(e,n);return await t.access(r).catch(()=>{throw new L(`CONFIG_NOT_FOUND`,`Config not found: ${n}`,{details:{configPath:n}})}),r}for(let n of yt){let r=o.join(e,n);try{return await t.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 yn(e){try{if(e.endsWith(`.ts`))try{return await import(`${a(e).href}?t=${Date.now()}`)}catch{let n=bn(await t.readFile(e,`utf8`));return await import(`data:text/javascript;base64,${Buffer.from(n,`utf8`).toString(`base64`)}`)}return await import(`${a(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 bn(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 xn(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 Sn(e){let t=o.resolve(e.cwd),n=await vn(t,e.configPath),r=await yn(n);if(r.default===void 0)throw new L(`CONFIG_INVALID`,`Config must use default export.`,{details:{file:n}});let i=_n(r.default,e.overrides,t);return await xn(i,t),{config:i,path:n,cwd:t}}function Cn(e){return{...rt,...e.install.dependencyCatalog}}function wn(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 Tn(e,t){e?.install?e.install(t):e?.info(`[Install] ${t}`)}var En=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;Tn(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 Dn(e){return t=>{e?.install?e.install(t):e?.info(`[Install] ${t}`)}}var On=class{config;logger;npm;catalog;pkgResolver;log;constructor(e,t){this.config=e,this.logger=t,this.npm=new En(e.install.registry,t),this.catalog=Cn(e),this.pkgResolver=new We(this.npm,t),this.log=Dn(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=wn(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 Yt.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 kn(e,t,n,r=!1){let i=o.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 xe(i),s=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[s]=a[s]??{};for(let[e,t]of Object.entries(n))a[s][e]=t.packageVersion;return Object.keys(a.dependencies).length||delete a.dependencies,Object.keys(a.devDependencies).length||delete a.devDependencies,r||await Se(i,a),{updated:!0,path:`package.json`}}const An=[1,21,0],jn=[1,0,0];var Mn=class{config;version;versionStr;depManager;constructor(e,t){this.config=e,this.version=Fe(e.version),this.versionStr=e.version,this.depManager=t}buildBp(e){let t=this.requireBp(),n=Me(e);this.depManager.validateBpDependencies();let r=this.getWriteFormatVersion(n);return t.manifest.merge===`clean`?this.buildCleanBp(t,r):this.buildPreserveBp(n,t,r)}buildRp(e){let t=this.requireRp(),n=Me(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}/${o.basename(e.entry,o.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[...Ne(e).filter(e=>!this.isManagedBpModule(e,t)),this.createScriptModule(t,n)]}replaceManagedRpModules(e,t,n){return[...Ne(e).filter(e=>!this.isManagedRpModule(e,t)),this.createResourcesModule(t,n)]}applyPbrCapability(e,t){if(t.pbr===!0){let t=Ne(e.capabilities);e.capabilities=t.includes(`pbr`)?t:[...t,`pbr`]}else if(t.pbr===!1){let t=Ne(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`:jn}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`:An}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}},Nn=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=Fe(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(Le(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`}}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}})}}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=Ne(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=Ne(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 Pn=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function Fn(e){let t=Cn(e.config),n=e.config.packs.bp?Lt(e.cwd,e.config):void 0,r=n?await Pe.read(n):void 0,i=Ln(r,t),a=new Nn(e.config,t,{...e.resolvedDeps?{install:e.resolvedDeps}:{},manifest:i}),s=new Mn(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=s.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 Pe.write(n,l,`bp`),In(u,e.logger),c.bpManifest={path:V(o.relative(e.cwd,n)),updated:!0,existed:t,dependencies:u}}if(e.config.packs.rp){let t=Rt(e.cwd,e.config),n=await Pe.read(t),r=n!==void 0,i=s.buildRp(n);e.dryRun||await Pe.write(t,i,`rp`),c.rpManifest={path:V(o.relative(e.cwd,t)),updated:!0,existed:r}}return c}function In(e,t){if(t)for(let n of e){let e=Pn.cyan(n.module_name);n.previous!==void 0&&n.previous!==n.version?t.info(`manifest ${e}: ${n.previous} ${Pn.dim(`->`)} ${n.version} (specifier ${JSON.stringify(n.specifier)}, ${n.source})`):n.source===`manifest`?t.info(`manifest ${e} ${n.version} ${Pn.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 Ln(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 Rn(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 zn(e,t){let n={dist:zt(e,t)};if(t.packs.bp&&(n.bpRoot=Ot(e,t),n.bpManifest=Lt(e,t),At(t))){let r=W(e,t);r&&(n.srcEntry=r);let i=Mt(e,t);i&&(n.scriptOutFile=i);let a=jt(e,t);a&&(n.scriptOutDir=a)}return t.packs.rp&&(n.rpRoot=kt(e,t),n.rpManifest=Rt(e,t)),n}async function K(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:zn(n,r),logger:i});i.hook(String(e),Rn(s))}catch(t){throw new L(`HOOK_FAILED`,`${String(e)} hook failed: ${t instanceof Error?t.message:String(t)}`)}}async function Bn(e){let{command:t,logger:n,mode:r,...i}=e,a={...r===void 0?{}:{mode:r},dryRun:!!i.dryRun};await K(`beforeManifest`,t,i.cwd,i.config,n,a);let o=await Fn({...i,logger:n});return await K(`afterManifest`,t,i.cwd,i.config,n,a),o}function Vn(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 Hn=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=o.join(this.cwd,`package.json`);if(await I(t)){let e=(await xe(t)).packageManager?.split(`@`)[0];if(e===`npm`||e===`pnpm`||e===`yarn`||e===`bun`)return e}return await I(o.join(this.cwd,`pnpm-lock.yaml`))?`pnpm`:await I(o.join(this.cwd,`yarn.lock`))?`yarn`:await I(o.join(this.cwd,`bun.lock`))||await I(o.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}=Vn(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 Un(e){let t=new Te({...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 Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:n});await K(`beforeInstall`,`install`,r,i,t,{dryRun:!!e.dryRun});let a=await new On(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 kn(r,i,a,e.dryRun)),i.install.updateManifest&&Object.assign(s,await Bn({cwd:r,config:i,command:`install`,dryRun:e.dryRun,logger:t,resolvedDeps:o}));let c=new Hn(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 K(`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 Wn(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config,overrides:{target:e.target}}),i=await Bn({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}}function Gn(e,t,n,r){let i=e?`npx tsc --noEmit`:`tsc --noEmit`;return i+=` --project "${t}"`,n&&r&&(i+=` --incremental --tsBuildInfoFile "${r}"`),i}async function Kn(e,t={}){let n=t.tsconfigPath??`tsconfig.json`,r=o.resolve(e,n);if(!await I(r))throw new L(`TYPECHECK_FAILED`,`TypeScript config not found: ${n}. Create it or run build with --skip-typecheck.`,{details:{path:n}});t.incremental&&t.tsBuildInfoFile&&await g(o.dirname(t.tsBuildInfoFile),{recursive:!0});let i=Gn(!!t.useNpx,r,!!t.incremental,t.tsBuildInfoFile);await new Promise((n,r)=>{let a=``,o=``,s;try{s=p(i,{cwd:e,windowsHide:!0,maxBuffer:10485760},e=>{if(!e){n();return}let s=[a.trim(),o.trim()].filter(Boolean).join(`
10
+ `),c=s.includes(`not recognized`)||s.includes(`not found`)||s.includes(`ENOENT`)||s.includes(`不是内部或外部命令`),l=c?t.useNpx?[`Install npm/npx or set packs.bp.compile.entry to skip typecheck.`]:["Install TypeScript globally so `tsc` is available.",`Set packs.bp.compile.useNpx: true to use the project local TypeScript.`]:void 0;r(new L(`TYPECHECK_FAILED`,c?`Cannot find ${t.useNpx?`npx`:`tsc`}.`:`${i} failed.`,{details:{command:i,exitCode:typeof e.code==`number`?e.code:null,...s?{diagnostics:s}:{}},...l?{suggestions:l}:{}}))})}catch(e){r(new L(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e instanceof Error?e.message:String(e)},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}));return}s.on(`error`,e=>{r(new L(`TYPECHECK_FAILED`,`Cannot start ${i}.`,{details:{command:i,cause:e.message},suggestions:t.useNpx?[`Install npm/npx or set build.useNpx to false.`]:["Install TypeScript globally so `tsc` is available.",`Set build.useNpx: true to use the project local TypeScript.`]}))}),s.stdout?.on(`data`,e=>{a+=String(e),t.quiet||process.stdout.write(e)}),s.stderr?.on(`data`,e=>{o+=String(e),t.quiet||process.stderr.write(e)})})}const qn=/* @__PURE__ */ new Set([`plugins`]),Jn=/* @__PURE__ */ new Set([`external`]),Yn=/* @__PURE__ */ new Set([`output`,`resolve`,`transform`,`experimental`,`checks`,`optimization`,`watch`,`moduleTypes`]),Xn=[{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 q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zn(e){return e==null||e===!1?[]:Array.isArray(e)?e:[e]}function Qn(e,t){return process.platform===`win32`?e.toLowerCase()===t.toLowerCase():e===t}function $n(e,t,n){return typeof e!=`string`||typeof t!=`string`?!1:Qn(o.resolve(n,e),o.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 tr(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[...Zn(e),...Zn(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 nr(e,t){if(!q(t))return t;let n=q(e)?e:{},r={...n,...t},i=q(n.define)?n.define:{};return q(t.define)&&(r.define={...i,...t.define}),r}function rr(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]=qn.has(e)?[...Zn(t),...Zn(r)]:Jn.has(e)?tr(t,r):e===`transform`?nr(t,r):Yn.has(e)&&q(t)&&q(r)?{...t,...r}:r}return n}function ir(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(Cn(e)))i.manifest&&!n.has(r)&&(t.push(r),n.add(r));return t}function ar(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 or(e,t){let n=ar(t),r=W(e,t);if(!r)throw new L(`BUILD_FAILED`,`packs.bp.compile.entry could not be resolved.`);return{input:r,external:ir(t),plugins:Wt(t),...qt(n.define)??{},onwarn(e,t){e.code!==`CIRCULAR_DEPENDENCY`&&t(e)},experimental:{attachDebugInfo:n.preserveModules?`none`:`simple`}}}function sr(e,t){let n=ar(t),r=W(e,t),i=jt(e,t),a=Mt(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:o.dirname(r),entryFileNames:`[name].js`,minify:n.minify}:{file:a,format:`esm`,minify:n.minify}}function cr(e,t){if(typeof e==`string`)return[o.resolve(t,e)];if(Array.isArray(e))return e.every(e=>typeof e==`string`)?e.map(e=>o.resolve(t,e)).sort():void 0;if(q(e)){let n=Object.values(e);return n.every(e=>typeof e==`string`)?n.map(e=>o.resolve(t,e)).sort():void 0}}function lr(e,t,n){if(e.input===void 0)return;let r=cr(e.input,n),i=cr(t.input,n);if(!(r!==void 0&&i!==void 0&&r.length===i.length&&r.every((e,t)=>Qn(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 ur(e,t,n){for(let{key:r,suggestion:i}of Xn){let a=e[r];if(a===void 0)continue;let o=t[r];if(!(r===`file`||r===`dir`||r===`preserveModulesRoot`?$n(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 dr(e,t){if(q(e)&&e.__esModule===!0&&`default`in e)return dr(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(!q(e[0]))throw new L(`CONFIG_INVALID`,`rolldown config file must export an options object or function: ${t}`);return e[0]}if(q(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 fr(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 v(e)}catch(t){throw new L(`CONFIG_INVALID`,`Failed to load rolldown config file "${e}": ${er(t)}`)}return dr(t,e)}async function pr(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(!q(r))throw new L(`CONFIG_INVALID`,`compile.rolldown customization function must return a rolldown options object (or nothing).`);return rr(t,r)}async function mr(e){let{cwd:t,config:n}=e,r=ar(n),i=H(t,n),a=W(t,n),s=jt(t,n),c=Mt(t,n);if(!a||!s||!c)throw new L(`BUILD_FAILED`,`rolldown requires a valid compile entry and output directory.`);let l=or(t,n),u=sr(t,n),d={command:e.command??`build`,...e.mode===void 0?{}:{mode:e.mode},target:n.target,entry:a,outDir:s,outFile:c,preserveModules:r.preserveModules},f=r.rolldown,p=e.configPath??r.rolldownConfig,m=p?await fr(o.resolve(i,p)):void 0,h=rr(l,typeof f==`function`?void 0:f);h=rr(h,typeof m==`function`?void 0:m),typeof f==`function`&&(h=await pr(f,h,d)),typeof m==`function`&&(h=await pr(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&&!q(g))throw new L(`CONFIG_INVALID`,"packs.bp.compile.rolldown `output` must be an object.",{details:{output:g}});lr({input:_},l,i);let y=rr(u,g);return ur(y,u,i),{inputOptions:{...v,input:l.input},outputOptions:y}}function hr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(2)} MB`}function gr(t,n){let r=o.resolve(t),i=o.resolve(n),a=o.relative(r,i);if(!a||a.startsWith(`..`)||o.isAbsolute(a))return;try{if(e(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 s=r;for(let t of a.split(o.sep)){s=o.join(s,t);try{if(e(s).isSymbolicLink())throw new L(`BUILD_FAILED`,`Safety check failed: script output path contains a symbolic link: "${s}". Refusing to recursively delete through a symbolic link.`)}catch(e){if(e.code===`ENOENT`)break;throw e}}}function _r(e,t,n){let r=o.resolve(e),i=o.resolve(t);if(Nt(r,i)||Nt(i,r))throw new L(`BUILD_FAILED`,`Safety check failed: script output directory "${e}" overlaps ${n} "${t}". Refusing to empty this directory.`)}function vr(e,t,n,r){let i=H(e,t),a=Ot(e,t),s=o.join(a,`manifest.json`),c=[o.join(i,`.git`),o.join(a,`.git`)];for(let e of c)_r(r,e,`.git metadata`);if(t.packs.rp){let e=U(i,t,`rp`);o.resolve(e)!==o.resolve(a)&&_r(r,e,`RP root`)}_r(r,s,`BP manifest`);let l=o.dirname(n),u=o.relative(a,l);Ft(r,a,`script output directory`,u&&!u.startsWith(`..`)&&!o.isAbsolute(u)?[l]:[]),gr(a,r)}async function yr(e,t,n,r={}){if(!At(t))throw new L(`BUILD_FAILED`,`rolldown requires packs.bp.compile to be configured.`);let i=W(e,t),a=jt(e,t),o=Mt(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 mr({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}});vr(e,t,i,a),await be(a);let c=await _(o);try{await c.write(s)}finally{await c.close()}await br(a,n)}catch(e){throw e instanceof L?e:new L(`BUILD_FAILED`,`rolldown failed: ${e instanceof Error?e.message:String(e)}`)}}async function br(e,t){let n=[];async function r(t){let i=await h.readdir(t,{withFileTypes:!0});for(let a of i){let i=o.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:o.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} (${hr(n[0].size)})`:`${n.length} files, total ${hr(i)}`)}async function xr(e,t,n,r){let i=r?Date.now():0,a=await t();return r&&n.timing(e,Date.now()-i),a}async function Sr(e){let t=Date.now(),n=e.config.build.timing,r=H(e.cwd,e.config),i=At(e.config),a=e.command??`build`,s={...e.mode===void 0?{}:{mode:e.mode},dryRun:!!e.dryRun};await xr(`manifest`,()=>Bn({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 K(`beforeBuild`,a,e.cwd,e.config,e.logger,s);let l=!1;if(i&&!e.dryRun&&e.typecheck!==!1){let t=e.config.packs.bp.compile,i=e.cache?o.resolve(r,t.cache.file):void 0;await xr(`typecheck`,()=>Kn(r,{quiet:!!e.quiet,useNpx:t.useNpx,tsconfigPath:t.tsconfig,incremental:!!e.cache,...i?{tsBuildInfoFile:i}:{}}),e.logger,n),l=!0,e.logger.typescript(`typecheck complete`)}i&&!e.dryRun&&(await xr(`rolldown`,()=>yr(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 K(`afterBuild`,a,e.cwd,e.config,e.logger,s);let u=Date.now()-t;return{script:i?V(Mt(e.cwd,e.config)):void 0,compiled:i,typecheck:l,durationMs:u}}async function Cr(e,n=``){let r={},i=await t.readdir(e,{withFileTypes:!0});for(let a of i){let i=o.join(e,a.name),s=n?`${n}/${a.name}`:a.name;a.isDirectory()?Object.assign(r,await Cr(i,s)):r[s]=new Uint8Array(await t.readFile(i))}return r}async function wr(e,n){let r={};for(let i of n){let n=o.join(e,i);try{(await t.stat(n)).isDirectory()?Object.assign(r,await Cr(n,i)):r[i]=new Uint8Array(await t.readFile(n))}catch{}}return r}async function Tr(e,t){return t?await t(e):e}function Er(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}/${r}`]=i;return n}function Dr(e){let t={};for(let n of Object.keys(e).sort())t[n]=e[n];return t}async function Or(e,n){await t.rm(e,{recursive:!0,force:!0}),await t.mkdir(e,{recursive:!0});for(let[r,i]of Object.entries(n)){let n=o.join(e,r);await t.mkdir(o.dirname(n),{recursive:!0}),await t.writeFile(n,i)}}var kr=D((()=>{}));kr();const Ar=new TextEncoder;new TextDecoder;function jr(e){let t=16+e.length*256,n=0,r=[];for(let t of e){let e=Ar.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 Mr=[`functions`,`loot_tables`,`structures`,`texts`],Nr=[`font`,`materials`,`sounds`,`texts`,`textures`],Pr=[1,26,40],Fr=Pr.join(`.`),Ir=new TextEncoder,Lr=new TextDecoder,Rr=new TextDecoder(`utf-16le`),zr=new TextDecoder(`utf-16be`);function Br(e){if(e.length>=2){if(e[0]===255&&e[1]===254)return Rr.decode(e.subarray(2));if(e[0]===254&&e[1]===255)return zr.decode(e.subarray(2))}return Lr.decode(e)}function Vr(e){return e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255)}function Hr(e){return e.startsWith(``)?e.slice(1):e}function Ur(e){if(e&&typeof e==`object`&&!Array.isArray(e))return e}function Wr(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 Gr(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 Kr(e){if(e)try{return Ur(JSON.parse(Hr(Br(e))))}catch{return}}function qr(e){return Wr(Ur(e?.header)?.min_engine_version)}function Jr(e){let t=e?.modules;return Array.isArray(t)?t.some(e=>Ur(e)?.type===`resources`):!1}function Yr(e,t,n){if(t.allowUnsupportedTarget)return;let r=qr(e);if(r&&Gr(r,Pr)>=0)return;let i=r?r.join(`.`):`(not declared)`;n?.warn(`pack optimization: header.min_engine_version is ${i}, below ${Fr}. 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 Xr(e,t,n){if(!e.toLowerCase().endsWith(`.json`))return t;try{let e=JSON.parse(Hr(Br(t)));return Ir.encode(JSON.stringify(e))}catch(r){let i=r instanceof Error?r.message:String(r),a=Vr(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 Zr(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=Ur(JSON.parse(Hr(Br(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={...Ur(n.header)??{}};return r.pack_optimization_version=t,n.header=r,Ir.encode(JSON.stringify(n))}function Qr(e,t,n,r){let i=e[`manifest.json`]??r,a=Kr(i);Yr(a,t,n);let o=new Set(t.exclude),s=t.keepLoose===!1?/* @__PURE__ */ new Set:/* @__PURE__ */ new Set([...Jr(a)?Nr:Mr,...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?Xr(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`]=jr(c.get(e));p[`manifest.json`]=Zr(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)`),Dr(p)}function $r(e,t,n){return r=>Qr(r,e,t,n)}const ei={win:()=>({type:`gameRoot`,path:o.join(`C:/Users`,u.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:o.join(e,`Packages`,`Microsoft.MinecraftUWP_8wekyb3d8bbwe`,`LocalState`,`games`,`com.mojang`)}}};function ti(e,t){return{type:`custom`,bp:o.join(t.path,`development_behavior_packs`),...e.packs.rp?{rp:o.join(t.path,`development_resource_packs`)}:{}}}function ni(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:ti(e,r),names:l}:{name:n,target:r,names:l}}const ri=/* @__PURE__ */ new Set([`node_modules`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lock`,`bun.lockb`,`tsconfig.json`,...yt]);function ii(e,t,n){let r=U(H(e,t),t,n);if(!r)return[];let i=W(e,t),a=[zt(e,t),i?o.dirname(i):void 0],s=[];for(let e of a){if(!e)continue;let t=o.relative(r,e);if(!t||t.startsWith(`..`)||o.isAbsolute(t))continue;let n=t.split(o.sep)[0];n&&s.push(n)}return s}async function ai(e,n,r=[]){let i;try{i=await t.readdir(e,{withFileTypes:!0})}catch{return[]}let a=new Set(n);return i.map(e=>e.name).filter(e=>!a.has(e)).filter(e=>!e.startsWith(`.`)&&!ri.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 si(e){let{logger:t,packType:n,root:r,items:i,action:a}=e;if(!t)return;let o=await ai(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 "${ci(r,e.cwd)}" ${o.length===1?`is`:`are`} skipped: ${c}${l}. Add them to ${oi(n)} to include them.`)}function ci(e,t){if(!t)return e;let n=o.relative(t,e).replace(/\\/g,`/`);return n&&!n.startsWith(`..`)&&!o.isAbsolute(n)?n:e}kr();const li=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`);async function ui(e,n,r){await t.rm(n,{recursive:!0,force:!0}),await t.mkdir(n,{recursive:!0});for(let i of r){let r=o.join(e,i),a=o.join(n,i);try{await t.cp(r,a,{recursive:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}function di(e,t){let n=o.resolve(e),r=o.resolve(t);if(Nt(n,r)||Nt(r,n))throw new L(`COPY_FAILED`,`Copy target "${t}" overlaps source pack "${e}". Refusing to copy.`,{details:{source:n,target:r}})}function fi(e,t){let n=o.resolve(e),r=o.resolve(n,t);if(r===n||!Nt(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 pi(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 mi(e,t){if(t===`bp`)return It(e);let n=e.packs.rp?.include??[],r=e.copy.include?.rp??[],i=n.length>0?n:r;return i.length>0?[...Et,...i]:[]}async function hi(e){try{return new Uint8Array(await t.readFile(o.join(e,`manifest.json`)))}catch{return}}async function gi(e,t,n,r,i,a,o,s,c){let l=mi(i,e),u=fi(n,r);di(t,u);let d=e===`bp`||l.length>0;d&&await si({...s?{logger:s}:{},packType:e,root:t,items:l,action:`copy`,cwd:o,ignore:ii(o,i,e)});let f=c===void 0?i.copy.optimize:c?i.copy.optimize??xt:void 0;if(!a){if(f){let e=d?await wr(t,l):await Cr(t),n=$r(f,s,await hi(t));try{await Or(u,await Tr(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 ui(t,u,l):await Ce(t,u)}let p=l.length>0?l.length:void 0;return s?.copy(`${a?`would copy`:`copied`} ${e}${p?` (${p} items)`:``} -> ${li.gray(u)}`),u}async function _i(e,t,n,r=!1,i,a={}){let{name:o,target:s,names:c}=ni(t,n),l=[],u=H(e,t),d=wt(t);for(let n of d){let o;if(o=n.type===`bp`?s.bp:s.rp,!o)continue;await pi(o,n.type);let d=c[n.type]??n.name,f=U(u,t,n.type),p=await gi(n.type,f,o,d,t,r,e,i,a.optimize);l.push(p)}return{target:o,copied:l}}async function vi(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 K(`beforeCopy`,t,n,r,i,l);let u=await _i(n,r,a,c,i,s===void 0?{}:{optimize:s});return await K(`afterCopy`,t,n,r,i,l),u}function yi(e,t){return na(e,t||{},0,0)}function bi(e,t){if(t){for(var n=new J(e.length),r=0;r<e.length;++r)n[r]=e.charCodeAt(r);return n}if(aa)return aa.encode(e);for(var i=e.length,a=new J(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 J(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 Vi(a,0,o)}function xi(e,t){t||={};var n={},r=[];ia(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=bi(o),f=d.length,p=l.comment,m=p&&bi(p),h=m&&m.length,g=sa(l.extra);f>65535&&Ui(11);var _=u?yi(c,l):c,v=_.length,y=ta();y.p(c),r.push(ra(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 J(a+22),x=i,S=a-i,C=0;C<r.length;++C){var d=r[C];ca(b,d.o,d,d.f,d.u,d.c.length);var w=30+d.f.length+sa(d.extra);b.set(d.c,d.o+w),ca(b,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+w+(d.m?d.m.length:0)}return la(b,i,r.length,S,x),b}var Si,Ci,J,Y,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,X,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Z,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,Q,ia,aa,oa,sa,ca,la,ua=D((()=>{Si=y(`/`);try{Ci=Si("worker_threads"),Ci.Worker,Ci.isMarkedAsUntransferable}catch{}for(J=Uint8Array,Y=Uint16Array,wi=Int32Array,Ti=new J([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]),Ei=new J([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]),Di=new J([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Oi=function(e,t){for(var n=new Y(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new wi(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}},Ci=Oi(Ti,2),ki=Ci.b,Ai=Ci.r,ki[28]=258,Ai[258]=28,ji=Oi(Ei,0),ji.b,Mi=ji.r,Ni=new Y(32768),X=0;X<32768;++X)Pi=(X&43690)>>1|(X&21845)<<1,Pi=(Pi&52428)>>2|(Pi&13107)<<2,Pi=(Pi&61680)>>4|(Pi&3855)<<4,Ni[X]=((Pi&65280)>>8|(Pi&255)<<8)>>1;for(Fi=(function(e,t,n){for(var r=e.length,i=0,a=new Y(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Y(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Y(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[Ni[d]>>c]=l}else for(s=new Y(r),i=0;i<r;++i)e[i]&&(s[i]=Ni[o[e[i]-1]++]>>15-e[i]);return s}),Ii=new J(288),X=0;X<144;++X)Ii[X]=8;for(X=144;X<256;++X)Ii[X]=9;for(X=256;X<280;++X)Ii[X]=7;for(X=280;X<288;++X)Ii[X]=8;for(Li=new J(32),X=0;X<32;++X)Li[X]=5;Ri=/*#__PURE__*/ Fi(Ii,9,0),zi=/*#__PURE__*/ Fi(Li,5,0),Bi=function(e){return(e+7)/8|0},Vi=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new J(e.subarray(t,n))},Hi=[`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`],Ui=function(e,t,n){var r=Error(t||Hi[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Ui),!n)throw r;return r},Z=function(e,t,n){n<<=t&7;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},Wi=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},Gi=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:Qi,l:0};if(i==1){var o=new J(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 Y(f+1),m=Ki(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 J(p),l:m}},Ki=function(e,t,n){return e.s==-1?Math.max(Ki(e.l,t,n+1),Ki(e.r,t,n+1)):t[e.s]=n},qi=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Y(++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}},Ji=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Yi=function(e,t,n){var r=n.length,i=Bi(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},Xi=function(e,t,n,r,i,a,o,s,c,l,u){Z(t,u++,n),++i[256];for(var d=Gi(i,15),f=d.t,p=d.l,m=Gi(a,15),h=m.t,g=m.l,_=qi(f),v=_.c,y=_.n,b=qi(h),x=b.c,S=b.n,C=new Y(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=Gi(C,7),E=T.t,D=T.l,O=19;O>4&&!E[Di[O-1]];--O);var ee=l+5<<3,k=Ji(i,Ii)+Ji(a,Li)+o,A=Ji(i,f)+Ji(a,h)+o+14+3*O+Ji(C,E)+2*C[16]+3*C[17]+7*C[18];if(c>=0&&ee<=k&&ee<=A)return Yi(t,u,e.subarray(c,c+l));var j,M,N,te;if(Z(t,u,1+(A<k)),u+=2,A<k){j=Fi(f,p,0),M=f,N=Fi(h,g,0),te=h;var ne=Fi(E,D,0);Z(t,u,y-257),Z(t,u+5,S-1),Z(t,u+10,O-4),u+=14;for(var w=0;w<O;++w)Z(t,u+3*w,E[Di[w]]);u+=3*O;for(var P=[v,x],re=0;re<2;++re)for(var ie=P[re],w=0;w<ie.length;++w){var ae=ie[w]&31;Z(t,u,ne[ae]),u+=E[ae],ae>15&&(Z(t,u,ie[w]>>5&127),u+=ie[w]>>12)}}else j=Ri,M=Ii,N=zi,te=Li;for(var w=0;w<s;++w){var F=r[w];if(F>255){var ae=F>>18&31;Wi(t,u,j[ae+257]),u+=M[ae+257],ae>7&&(Z(t,u,F>>23&31),u+=Ti[ae]);var oe=F&31;Wi(t,u,N[oe]),u+=te[oe],oe>3&&(Wi(t,u,F>>5&8191),u+=Ei[oe])}else Wi(t,u,j[F]),u+=M[F]}return Wi(t,u,j[256]),u+M[256]},Zi=/*#__PURE__*/ new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Qi=/*#__PURE__*/ new J(0),$i=function(e,t,n,r,i,a){var o=a.z||e.length,s=new J(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=Zi[t-1],f=d>>13,p=d&8191,m=(1<<n)-1,h=a.p||new Y(32768),g=a.h||new Y(m+1),_=Math.ceil(n/3),v=2*_,y=function(t){return(e[t]^e[t+1]<<_^e[t+2]<<v)&m},b=new wi(25e3),x=new Y(288),S=new Y(32),C=0,w=0,T=a.i||0,E=0,D=a.w||0,O=0;T+2<o;++T){var ee=y(T),k=T&32767,A=g[ee];if(h[k]=A,g[ee]=k,D<=T){var j=o-T;if((C>7e3||E>24576)&&(j>423||!l)){u=Xi(e,c,0,b,x,S,w,E,O,T-O,u),E=C=w=0,O=T;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)S[M]=0}var N=2,te=0,ne=p,P=k-A&32767;if(j>2&&ee==y(T-P))for(var re=Math.min(f,j)-1,ie=Math.min(32767,T),ae=Math.min(258,j);P<=ie&&--ne&&k!=A;){if(e[T+N]==e[T+N-P]){for(var F=0;F<ae&&e[T+F]==e[T+F-P];++F);if(F>N){if(N=F,te=P,F>re)break;for(var oe=Math.min(P,F-2),se=0,M=0;M<oe;++M){var ce=T-P+M&32767,le=ce-h[ce]&32767;le>se&&(se=le,A=ce)}}}k=A,A=h[k],P+=k-A&32767}if(te){b[E++]=268435456|Ai[N]<<18|Mi[te];var ue=Ai[N]&31,de=Mi[te]&31;w+=Ti[ue]+Ei[de],++x[257+ue],++S[de],D=T+N,++C}else b[E++]=e[T],++x[e[T]]}}for(T=Math.max(T,D);T<o;++T)b[E++]=e[T],++x[e[T]];u=Xi(e,c,l,b,x,S,w,E,O,T-O,u),l||(a.r=u&7|c[u/8|0]<<3,u-=7,a.h=g,a.p=h,a.i=T,a.w=D)}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=Yi(c,u+1,e.subarray(T,fe))}a.i=o}return Vi(s,0,r+Bi(u)+i)},ea=/*#__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})(),ta=function(){var e=-1;return{p:function(t){for(var n=e,r=0;r<t.length;++r)n=ea[n&255^t[r]]^n>>>8;e=n},d:function(){return~e}}},na=function(e,t,n,r,i){if(!i&&(i={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),o=new J(a.length+e.length);o.set(a),o.set(e,a.length),e=o,i.w=a.length}return $i(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)},ra=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},Q=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},ia=function(e,t,n,r){for(var i in e){var a=e[i],o=t+i,s=r;Array.isArray(a)&&(s=ra(r,a[1]),a=a[0]),ArrayBuffer.isView(a)?n[o]=[a,s]:(n[o+=`/`]=[new J(0),s],ia(a,o,n,r))}},aa=typeof TextEncoder<`u`&&/*#__PURE__*/ new TextEncoder,oa=typeof TextDecoder<`u`&&/*#__PURE__*/ new TextDecoder;try{oa.decode(Qi,{stream:!0})}catch{}sa=function(e){var t=0;if(e)for(var n in e){var r=e[n].length;r>65535&&Ui(9),t+=r+4}return t},ca=function(e,t,n,r,i,a,o,s){var c=r.length,l=n.extra,u=s&&s.length,d=sa(l);Q(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)&&Ui(10),Q(e,t,p<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,a!=-1&&(Q(e,t,n.crc),Q(e,t+4,a<0?-a-2:a),Q(e,t+8,n.size)),Q(e,t+12,c),Q(e,t+14,d),t+=16,o!=null&&(Q(e,t,u),Q(e,t+6,n.attrs),Q(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;Q(e,t,+m),Q(e,t+2,g),e.set(h,t+4),t+=4+g}return u&&(e.set(s,t),t+=u),t},la=function(e,t,n,r,i){Q(e,t,101010256),Q(e,t+8,n),Q(e,t+10,n),Q(e,t+12,r),Q(e,t+16,i)}}));async function da(e,n){await t.mkdir(o.dirname(n),{recursive:!0}),await t.writeFile(n,xi(Dr(e)))}async function fa(e,t,n){await da(await Tr(await Cr(e),n),t)}async function pa(e,t,n,r){await da(await Tr(await wr(e,t),r),n)}async function ma(e,t){let n={};for(let t of e){let e=await Tr(await wr(t.source,t.items),t.transform);Object.assign(n,Er(e,o.basename(o.resolve(t.source))))}await da(n,t)}async function ha(e,t,n){let r={};for(let t of e){let e=await Tr(await wr(t.source,t.items),t.transform);Object.assign(r,Er(e,o.basename(o.resolve(t.source))))}for(let e of t){let t=await Tr(await Cr(e.dir),e.transform);Object.assign(r,Er(t,o.basename(o.resolve(e.dir))))}await da(r,n)}var ga=D((()=>{ua(),kr()})),_a=/* @__PURE__ */ ee({packMcpack:()=>va});async function va(e,t,n,r=!1,i){let a=o.join(t,`${n}.mcpack`);return r||await fa(e,a,i),a}var ya=D((()=>{ga()}));ga();function ba(e,t,n){let r=o.resolve(e),i=o.resolve(t),a=o.relative(i,r);if(a&&!a.startsWith(`..`)&&!o.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 xa(e,t,n){let r=o.resolve(e),i=o.resolve(t);for(let e of n){let t=o.resolve(i,e),n=o.relative(t,r);if(n===``||!n.startsWith(`..${o.sep}`)&&n!==`..`&&!o.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 Sa(e,t){let n=o.relative(o.resolve(t),o.resolve(e));if(n.startsWith(`..`)||o.isAbsolute(n))throw new L(`PACK_FAILED`,`pack output name must stay inside pack.outDir.`,{details:{output:o.resolve(e),dist:o.resolve(t)}})}function Ca(e,t){if(t===`bp`)return{items:It(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:[...Et,...i],selective:!0}:{items:[],selective:!1}}async function wa(e,t,n={}){let r=H(e,t),i=(n.name??t.pack.name).replaceAll(`{name}`,t.name).replaceAll(`{version}`,t.version),a=zt(e,t);if(wt(t).length===0)throw new L(`PACK_FAILED`,`No packs configured. At least one pack is required.`);let s=n.optimize===void 0?t.pack.optimize:n.optimize?t.pack.optimize??xt:void 0,c=s?$r(s,n.logger):void 0,l=t.packs.bp?{root:U(r,t,`bp`),config:t}:void 0,u=t.packs.rp?{root:U(r,t,`rp`),config:t}:void 0,d=l?Ca(t,`bp`):void 0;if(l&&d?.selective&&await si({...n.logger?{logger:n.logger}:{},packType:`bp`,root:l.root,items:d.items,action:`pack`,cwd:e,ignore:ii(e,t,`bp`)}),u){let r=Ca(t,`rp`);r.selective&&await si({...n.logger?{logger:n.logger}:{},packType:`rp`,root:u.root,items:r.items,action:`pack`,cwd:e,ignore:ii(e,t,`rp`)})}if(l&&u){if(!d)throw new L(`PACK_FAILED`,`BP pack configuration is missing.`);let e=o.join(a,`${i}.mcaddon`);if(Sa(e,a),d?.selective&&xa(e,l.root,d.items),ba(e,u.root,`RP`),!n.dryRun){let n=Ca(t,`rp`);n.selective?await ma([{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=o.join(a,`${i}.mcpack`);return Sa(e,a),d?.selective&&xa(e,l.root,d.items),n.dryRun||await pa(l.root,d.items,e,c),e}if(u){let e=o.join(a,`${i}.mcpack`);if(Sa(e,a),ba(e,u.root,`RP`),!n.dryRun){let r=Ca(t,`rp`);if(r.selective)await pa(u.root,r.items,e,c);else{let{packMcpack:e}=await Promise.resolve().then(()=>(ya(),_a));return await e(u.root,a,i,n.dryRun,c)}}return e}throw new L(`PACK_FAILED`,`No packs configured.`)}async function Ta(e,t,n,r={}){let i=Date.now();await K(`beforePack`,`pack`,e,t,n,{dryRun:!!r.dryRun});let a=await wa(e,t,{...r,logger:n});await K(`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 Ea(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({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;a=await Sr({cwd:n,config:r,logger:t,command:`build`,...i===void 0?{}:{typecheck:i},...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 Ta(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 Da(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 Oa(e){Da(e);let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r}=await Sn({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 Un({...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.cache===void 0?a?.cache.build??!1:e.cache,c=await Sr({cwd:n,config:r,logger:t,mode:e.mode,command:`build`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,cache:!!s,dryRun:!!e.dryRun,quiet:!!(e.json||e.silent),...i?{resolvedDeps:i}:{}}),l=null,u=e.skipCopy?!1:e.copy||e.copyTarget?!0:r.build.copy;u&&(l=await vi({command:`build`,cwd:n,config:r,logger:t,...e.mode===void 0?{}:{mode:e.mode},targetName:e.copyTarget??(typeof u==`string`?u:void 0),dryRun:!!e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}}));let d=null;return!e.skipPack&&e.pack&&(d=await Ta(n,r,t,{name:e.name,dryRun:e.dryRun,...e.optimize===void 0?{}:{optimize:!!e.optimize}})),t.done(`build`,`complete in ${t.formatDuration(c.durationMs)}`),{ok:!0,command:`build`,durationMs:c.durationMs,build:c,copy:l,pack:d}}async function ka(e){let t=Date.now(),n=new Te({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config});await K(`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 _i(r,i,t,e.dryRun,n,o));await K(`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 Aa=/[/\\]rolldown\.config\.[A-Za-z0-9_-]+\.js$/;function ja(e,t){return V(o.relative(e,t))}function Ma(e,t,n,r){let i=H(e,t),a=At(t),s=[];if(a){let n=W(e,t);n&&s.push(ja(e,o.dirname(n)))}if(r.copy){for(let n of wt(t))if(U(i,t,n.type)){let r=Na(e,t,n.type,i);s.push(...r)}}let c=t.dev.watch?.include??[];s.push(...c);let l=Vt(s.map(t=>o.resolve(e,t))).map(t=>ja(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`,ja(e,zt(e,t))];for(let n of wt(t)){let r=U(i,t,n.type);if(r&&(u.push(ja(e,o.join(r,`manifest.json`))),n.type===`bp`&&a)){let n=U(i,t,`bp`),r=t.packs.bp.compile.scriptOutputDir;u.push(ja(e,o.join(n,r)))}}let d=b.watch(l,{cwd:e,ignored:[...u,Aa],ignoreInitial:!0}),f=!1,p=!1,m=!1,h=async()=>{r.copy&&await vi({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 Bn({cwd:e,config:t,command:`dev`,dryRun:r.dryRun,logger:n,...r.mode===void 0?{}:{mode:r.mode}}),await h()},_=async()=>{a?await Sr({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.rolldownConfig===void 0?{}:{rolldownConfig:r.rolldownConfig}}):await Bn({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 s=V(i),c=a?W(e,t):void 0,l=c?o.dirname(c):void 0,u=o.resolve(e,s),d=l?u===l||u.startsWith(l+o.sep):!1;if(f){d?p=!0:m=!0;return}f=!0;let h=Date.now();try{n.clear(),n.bepack(`dev`,`changed ${o.normalize(i)}`),d&&a?await _():await g(),n.done(`dev`,`updated after ${o.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?V(o.relative(e,U(i,t,`bp`))):null,x=t.packs.rp?V(o.relative(e,U(i,t,`rp`))):null,S=a&&W(e,t)?ja(e,o.dirname(W(e,t))):null,C=!1,w=[],T=0,E=0;for(let e of l)y&&(e===y||e.startsWith(y+`/`))?(T++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):x&&(e===x||e.startsWith(x+`/`))?(E++,S&&(e===S||e.startsWith(S+`/`))&&(C=!0)):S&&(e===S||e.startsWith(S+`/`))||w.push(e);return S&&!C&&w.unshift(S),T>0&&w.push(`bp(${T})`),E>0&&w.push(`rp(${E})`),n.progress(`dev`,`watching ${w.join(`, `)}`),d}function Na(e,t,n,r){let i=U(r,t,n);if(!i)return[];if(n===`bp`)return It(t).filter(e=>e!==`manifest.json`).map(t=>V(o.relative(e,o.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=>V(o.relative(e,o.join(i,t)))):[V(o.relative(e,i))]:[]}async function Pa(e){let t=Date.now(),n=new Te({...e,silent:e.silent||e.json}),{cwd:r,config:i}=await Sn({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.skipCopy&&!!(e.copy||e.copyTarget||i.dev.copy),c=e.copyTarget??(typeof i.dev.copy==`string`?i.dev.copy:void 0),l=a?.cache.dev??!0,u=!!e.dryRun,d=!!(e.json||e.silent),f=e.optimize===void 0?{}:{optimize:!!e.optimize};return await Sr({cwd:r,config:i,logger:n,mode:e.mode,command:`dev`,...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},typecheck:!!o,cache:l,dryRun:u,quiet:d}),s&&await vi({command:`dev`,cwd:r,config:i,logger:n,targetName:c,dryRun:u,...e.mode===void 0?{}:{mode:e.mode},...f}),n.done(`dev`,`initial build complete in ${n.formatDuration(Date.now()-t)}`),Ma(r,i,n,{copy:s,mode:e.mode,...c?{copyTarget:c}:{},...e.rolldownConfig?{rolldownConfig:e.rolldownConfig}:{},...f,typecheck:!!o,cache:l,dryRun:u,quiet:d}),{ok:!0,command:`dev`,initialBuildDurationMs:Date.now()-t}}function Fa(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 Ia(e){let t=new Te({...e,silent:e.silent||e.json}),{cwd:n,config:r,path:i}=await Sn({cwd:e.cwd??process.cwd(),configPath:e.config});if(e.json)return{cwd:n,configFile:i,config:Fa(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.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(Cn(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=Fa(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 La(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 Ra(e){console.log(JSON.stringify(e,null,4))}const za=we.default.createColors(process.env.NO_COLOR===void 0&&process.env.FORCE_COLOR!==`0`),Ba=i(import.meta.url),Va=s(Ba),Ha=c(Va,`../package.json`);let Ua;try{let e=JSON.parse(n(Ha,`utf-8`));(typeof e.version!=`string`||!e.version)&&(console.error(`ERROR: package.json missing valid 'version' field`),process.exit(1)),Ua=e.version}catch(e){console.error(`ERROR: Failed to read package version: ${e.message}`),process.exit(1)}const $=ge(`bepack`);function Wa(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 Ga=!1;function Ka(e,t,n){let r=La(t);if(n)Ra({ok:!1,command:e,error:r});else if(t instanceof L){if(console.error(`${za.red(r.code)}: ${r.message}`),r.suggestions?.length)for(let e of r.suggestions)console.error(` ${za.dim(`→`)} ${e}`);Ga&&r.stack&&console.error(`${za.dim(r.stack)}`)}else t instanceof Error?(console.error(`${za.red(`ERROR`)}: ${t.message}`),Ga&&r.stack&&console.error(`${za.dim(r.stack)}`)):console.error(`${za.red(`ERROR`)}: ${String(t)}`);process.exitCode=1}async function qa(e,t,n){Ga=!!n.verbose;try{let e=await t(n);n.json&&Ra(e)}catch(t){Ka(e,t,!!n.json)}}Wa($.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=>qa(`init`,vt,e)),Wa($.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=>qa(`install`,Un,e)),Wa($.command(`manifest`,`Patch manifest files`)).option(`--target <target>`,`Target MC version`).action(e=>qa(`manifest`,Wn,e)),Wa($.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(`--preserve-modules`,`Preserve module output`).option(`--use-npx`,`Use npx tsc for typecheck`).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=>qa(`build`,Oa,e)),Wa($.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=>qa(`copy`,ka,e)),Wa($.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(`--rolldown-config <path>`,`Custom rolldown config file (overrides bepack.config)`).action(e=>qa(`pack`,Ea,e)),Wa($.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(`--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=>qa(`dev`,Pa,e)),Wa($.command(`config`,`Show resolved config`)).option(`--summary`,`Show brief summary instead of full config`).action(e=>qa(`config`,Ia,e)),$.help(),$.version(Ua);async function Ja(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){Ka(`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){Ka(`cli`,e,!!$.options.json)}}}await Ja(process.argv);export{};