-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdash-compiler.umd.js
More file actions
78 lines (78 loc) · 57.3 KB
/
dash-compiler.umd.js
File metadata and controls
78 lines (78 loc) · 57.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
(function(C,P){typeof exports=="object"&&typeof module!="undefined"?P(exports,require("@bridge-editor/mc-project-core"),require("pathe"),require("@bridge-editor/molang"),require("@bridge-editor/common-utils"),require("json5"),require("@swc/wasm-web"),require("@bridge-editor/js-runtime"),require("is-glob")):typeof define=="function"&&define.amd?define(["exports","@bridge-editor/mc-project-core","pathe","@bridge-editor/molang","@bridge-editor/common-utils","json5","@swc/wasm-web","@bridge-editor/js-runtime","is-glob"],P):(C=typeof globalThis!="undefined"?globalThis:C||self,P(C.DashCompiler={},C.mcProjectCore,C.pathe,C.molang,C.commonUtils,C.json5,C.initSwc,C.jsRuntime,C.isGlob))})(this,function(C,P,$,E,A,re,J,x,ne){"use strict";function N(n){return n&&typeof n=="object"&&"default"in n?n:{default:n}}var O=N(re),oe=N(J),ae=N(ne);class le extends P.ProjectConfig{constructor(e,t){super($.dirname(t)),this.fileSystem=e,this.configPath=t}readConfig(){return this.fileSystem.readJson(this.configPath)}writeConfig(e){return this.fileSystem.writeJson(this.configPath,e)}}class ce{constructor(e,t,s){this.dash=e,this.pluginId=t,this.plugin=s}implementsHook(e){return typeof this.plugin[e]=="function"}async runBuildStartHook(){var e,t;try{return await((t=(e=this.plugin).buildStart)==null?void 0:t.call(e))}catch(s){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "buildStart" hook:`,s)}}async runIncludeHook(){var e,t;try{return await((t=(e=this.plugin).include)==null?void 0:t.call(e))}catch(s){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "include" hook:`,s)}}async runIgnoreHook(e){var t,s;try{return await((s=(t=this.plugin).ignore)==null?void 0:s.call(t,e))}catch(i){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "ignore" hook for "${e}":`,i)}}async runTransformPathHook(e){var t,s;try{return await((s=(t=this.plugin).transformPath)==null?void 0:s.call(t,e))}catch(i){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "transformPath" hook for "${e}":`,i)}}async runReadHook(e,t){var s,i;try{return await((i=(s=this.plugin).read)==null?void 0:i.call(s,e,t))}catch(r){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "read" hook for "${e}":`,r)}}async runLoadHook(e,t){var s,i;try{return await((i=(s=this.plugin).load)==null?void 0:i.call(s,e,t))}catch(r){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "load" hook for "${e}":`,r)}}async runRegisterAliasesHook(e,t){var s,i;try{return await((i=(s=this.plugin).registerAliases)==null?void 0:i.call(s,e,t))}catch(r){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "registerAliases" hook for "${e}":`,r)}}async runRequireHook(e,t){var s,i;try{return await((i=(s=this.plugin).require)==null?void 0:i.call(s,e,t))}catch(r){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "require" hook for "${e}":`,r)}}async runTransformHook(e,t,s){var i,r;try{return await((r=(i=this.plugin).transform)==null?void 0:r.call(i,e,t,s))}catch(o){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "transform" hook for "${e}":`,o)}}async runFinalizeBuildHook(e,t){var s,i;try{return await((i=(s=this.plugin).finalizeBuild)==null?void 0:i.call(s,e,t))}catch(r){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "finalizeBuild" hook for "${e}":`,r)}}async runBuildEndHook(){var e,t;try{return await((t=(e=this.plugin).buildEnd)==null?void 0:t.call(e))}catch(s){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "buildEnd" hook:`,s)}}async runBeforeFileUnlinked(e){var t,s;try{return await((s=(t=this.plugin).beforeFileUnlinked)==null?void 0:s.call(t,e))}catch(i){this.dash.console.error(`The plugin "${this.pluginId}" threw an error while running the "beforeFileUnlinked" hook for "${e}":`,i)}}}const ue=({options:n,outputFileSystem:e,hasComMojangDirectory:t,projectConfig:s,projectRoot:i,packType:r})=>{var l;n.buildName||(n.buildName=n.mode==="development"?"dev":"dist"),n.packName||(n.packName="Bridge"),(l=n.rewriteToComMojang)==null||l||(t=!1);const o={behaviorPack:"development_behavior_packs",resourcePack:"development_resource_packs",skinPack:"skin_packs",worldTemplate:"minecraftWorlds"},a=d=>t&&n.mode==="development"?`${o[d]}`:`${i}/builds/${n.buildName}`,c=(d,f)=>`${a(d)}/${n.packName} ${f}`;return{async buildStart(){if(n.mode==="production"||n.buildType==="fullBuild")if(t)for(const d in o){const f=r.getFromId(d);!f||await e.unlink(c(d,f.defaultPackPath)).catch(()=>{})}else await e.unlink(a("BP")).catch(()=>{})},transformPath(d){var _,g;if(!d||d.includes("BP/scripts/gametests/")&&n.mode==="production")return;const f=r==null?void 0:r.get(d);if(!f)return;const u=s.getAbsolutePackRoot(f.id),w=$.relative(u,d);if(["behaviorPack","resourcePack","skinPack","worldTemplate"].includes(f.id))return $.join(c(f.id,(g=(_=n.packNameSuffix)==null?void 0:_[f.id])!=null?g:f.defaultPackPath),w)}}},z=async({fileType:n,projectConfig:e,requestJsonData:t,options:s,console:i,jsRuntime:r})=>{const o=(g,v)=>e.resolvePackPath(g,v),a=new E.CustomMolang({}),c=[e.resolvePackPath("behaviorPack","molang"),e.resolvePackPath("resourcePack","molang")],l=g=>g&&c.some(v=>g.startsWith(`${v}/`))&&g.endsWith(".molang"),d=e.resolvePackPath("behaviorPack","scripts/molang"),f=g=>g==null?void 0:g.startsWith(`${d}/`),u=new Map,w=g=>{if(u.has(g))return u.get(g);const v=s.include[n.getId(g)];return u.set(g,v),v};let _=[];return{async buildStart(){s.include=Object.assign(await t("data/packages/minecraftBedrock/location/validMolang.json"),s.include),u.clear()},ignore(g){return!l(g)&&!f(g)&&!w(g)},transformPath(g){if(l(g)||f(g))return null},async read(g,v){if((l(g)||f(g))&&v){const k=await v.getFile();return await(k==null?void 0:k.text())}else if(w(g)&&g.endsWith(".json")&&v){const k=await v.getFile();if(!k)return;try{return O.default.parse(await k.text())}catch(b){return s.buildType!=="fileRequest"&&i.error(`Error within file "${g}": ${b}`),{__error__:`Failed to load original file: ${b}`}}}},async load(g,v){if(l(g)&&v)a.parse(v);else if(f(g)){const k=await r.run(g,{console:i},v).catch(b=>(i.error(`Failed to execute Molang AST script "${g}": ${b}`),null));if(!k)return null;typeof k.__default__=="function"&&_.push(k.__default__)}},async require(g){if(w(g))return[o("behaviorPack","scripts/molang/**/*.[jt]s"),o("behaviorPack","molang/**/*.molang"),o("resourcePack","molang/**/*.molang")]},async transform(g,v){const k=w(g);k&&k.length>0&&k.forEach(b=>A.setObjectAt(b,v,S=>{if(typeof S!="string"||S[0]==="/"||S[0]==="@")return S;if(_.length>0){let p=null;try{p=a.parse(S)}catch(F){s.buildType!=="fileRequest"&&i.error(`Error within file "${g}"; script "${S}": ${F}`)}if(p){for(const F of _)p=p.walk(F);S=p.toString()}}try{return a.transform(S)}catch(p){return s.buildType!=="fileRequest"&&i.error(`Error within file "${g}"; script "${S}": ${p}`),S}}))},buildEnd(){_=[]}}},de=({fileType:n})=>({ignore(e){return(n==null?void 0:n.getId(e))!=="entity"},registerAliases(e,t){var s,i,r,o;if((n==null?void 0:n.getId(e))==="entity"&&((i=(s=t==null?void 0:t["minecraft:entity"])==null?void 0:s.description)==null?void 0:i.identifier))return[(o=(r=t==null?void 0:t["minecraft:entity"])==null?void 0:r.description)==null?void 0:o.identifier]}});function he(n,e){const t=U(n),s=U(e),i=t.pop(),r=s.pop(),o=L(t,s);return o!==0?o:i&&r?L(i.split("."),r.split(".")):i||r?i?-1:1:0}const me=(n,e,t)=>{ye(t);const s=he(n,e);return K[t].includes(s)},pe=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,U=n=>{if(typeof n!="string")throw new TypeError("Invalid argument expected string");const e=n.match(pe);if(!e)throw new Error(`Invalid argument not valid semver ('${n}' received)`);return e.shift(),e},V=n=>n==="*"||n==="x"||n==="X",G=n=>{const e=parseInt(n,10);return isNaN(e)?n:e},fe=(n,e)=>typeof n!=typeof e?[String(n),String(e)]:[n,e],ge=(n,e)=>{if(V(n)||V(e))return 0;const[t,s]=fe(G(n),G(e));return t>s?1:t<s?-1:0},L=(n,e)=>{for(let t=0;t<Math.max(n.length,e.length);t++){const s=ge(n[t]||0,e[t]||0);if(s!==0)return s}return 0},K={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1]},X=Object.keys(K),ye=n=>{if(typeof n!="string")throw new TypeError(`Invalid operator type, expected string but got ${typeof n}`);if(X.indexOf(n)===-1)throw new Error(`Invalid operator, expected one of ${X.join("|")}`)},we=(n,e)=>({register:t=>{var s;((s=t.type)!=null?s:"entity")===e&&(n.component=({name:i,schema:r,template:o})=>{const a=new t;i(t.component_name),r(R(Object.values(a.onPropose())[0])),o((c,{create:l})=>{l(a.onApply(c,"components")[`minecraft:${e}`])})})}});function R(n){const e={},t=Object.keys(n);if(t.length===1&&t[0].startsWith("$dynamic.list."))return{type:"array",items:R(Object.values(n)[0])};for(const[s,i]of Object.entries(n))s.startsWith("$")||(typeof i=="string"?e[s]=Fe(i):Array.isArray(i)?e[s]={enum:i}:i==="object"&&(e[s]=R(i)));return{type:"object",properties:e}}function Fe(n){switch(n){case"$general.boolean":return{type:"boolean"};case"$general.number":return{type:"integer"};case"$general.decimal":return{type:"number"};default:return{type:["number","integer","string","boolean","object","array"]}}}class Q{constructor(e,t,s,i,r,o){this.console=e,this.fileType=t,this.componentSrc=s,this.mode=i,this.v1Compat=r,this.targetVersion=o,this.animations=[],this.animationControllers=[],this.createOnPlayer=[],this.dialogueScenes={},this.serverFiles=[],this.clientFiles={},this.lifecycleHookCount={activated:0,deactivated:0}}setProjectConfig(e){this.projectConfig=e}get name(){return this._name}async load(e,t,s){let i={component:null};const r=await e.run(t,{defineComponent:l=>l,console:this.console,Bridge:this.v1Compat?we(i,this.fileType):void 0}).catch(l=>(this.console.error(`Failed to execute component "${t}": ${l}`),null));if(!r)return!1;if(typeof r.__default__!="function")if(i.component)r.__default__=i.component;else return this.console.error(`Component ${t} is not a valid component. Expected a function as the default export.`),!1;const o=l=>this._name=l;let a=l=>this.schema=l,c=()=>{};return(!s||s==="server")&&(a=()=>{},c=l=>{this.template=(d,f)=>{try{l(d,f)}catch(u){this.console.log(l.toString()),this.console.error(u)}}}),await r.__default__({name:o,schema:a,template:c}),!0}reset(){this.fileType!=="item"&&(this.animations=[],this.animationControllers=[]),this.clientFiles={},this.serverFiles=[]}getSchema(){return this.schema}toString(){return this.componentSrc}create(e,t,s=`minecraft:${this.fileType}`,i){var c;const r=s.split("/"),o=r.pop(),a=this.getObjAtLocation(e,[...r]);a[o]=(i?(l,d)=>i(A.deepMerge,l,d):A.deepMerge)((c=a[o])!=null?c:{},t!=null?t:{})}getObjAtLocation(e,t){let s=e;for(;t.length>0;){const i=t.shift();s[i]===void 0?s[Number(i)]!==void 0?s=s[Number(i)]:(s[i]={},s=s[i]):s=s[i]}return s}async processTemplates(e,t,s){var k,b,S,p,F,h;if(typeof this.template!="function")return;const i=(S=(b=(k=e[`minecraft:${this.fileType}`])==null?void 0:k.description)==null?void 0:b.identifier)!=null?S:"bridge:no_identifier",r=await A.hashString(`${this.name}/${i}`),o=(h=(F=(p=this.projectConfig)==null?void 0:p.get())==null?void 0:F.namespace)!=null?h:"bridge";let a;if(o.includes("_")){const m=o.split("_")[0],y=o.split("_").slice(1).join("_");a=`${m}/${y}`}else a="bridge";const c=(m,y)=>(this.animations.push([m,y]),this.getShortAnimName("a",r,this.animations.length-1)),l=(m,y)=>(this.animationControllers.push([m,y]),this.getShortAnimName("ac",r,this.animationControllers.length-1)),d=m=>{const y=`loot_tables/${a}/${this.getShortAnimName("lt",r,this.serverFiles.length)}.json`;return this.serverFiles.push([y,m]),y},f=m=>{const y=`trading/${a}/${this.getShortAnimName("tt",r,this.serverFiles.length)}.json`;return this.serverFiles.push([y,m]),y},u=m=>{this.serverFiles.push([`recipes/${a}/${this.getShortAnimName("recipe",r,this.serverFiles.length)}.json`,m])},w=m=>{this.serverFiles.push([`spawn_rules/${a}/${this.getShortAnimName("sr",r,this.serverFiles.length)}.json`,m])},_=(await A.hashString(`${this.name}/${s}`)).slice(0,16),g=m=>this.registerLifecycleHook(e,s,m,_,"activated"),v=m=>this.registerLifecycleHook(e,s,m,_,"deactivated");this.fileType==="entity"?this.template(t!=null?t:{},{mode:this.mode,compilerMode:this.mode,sourceEntity:()=>JSON.parse(JSON.stringify(e)),create:(m,y,j)=>this.create(e,m,y,j),location:s,identifier:i,projectNamespace:o,animationController:l,animation:c,lootTable:d,tradeTable:f,spawnRule:w,dialogueScene:!this.targetVersion||me(this.targetVersion,"1.17.10",">=")?(m,y=!0)=>{this.dialogueScenes[r]||(this.dialogueScenes[r]=[]),this.dialogueScenes[r].push(m),m.scene_tag&&y&&g({run_command:{command:[`/dialogue open @s @p ${m.scene_tag}`]}})}:void 0,onActivated:g,onDeactivated:v,client:{create:(m,y="1.10.0")=>{this.clientFiles[`entity/${a}/${r}.json`]={format_version:y,"minecraft:client_entity":Object.assign({description:{identifier:i}},m)}}}}):this.fileType==="item"?this.template(t!=null?t:{},{mode:this.mode,compilerMode:this.mode,sourceItem:()=>JSON.parse(JSON.stringify(e)),create:(m,y,j)=>this.create(e,m,y,j),location:s,identifier:i,projectNamespace:o,lootTable:d,recipe:u,player:{animationController:l,animation:c,create:(m,y,j)=>{this.createOnPlayer.push([y!=null?y:"minecraft:entity",m,j])}}}):this.fileType==="block"&&this.template(t!=null?t:{},{mode:this.mode,compilerMode:this.mode,sourceBlock:()=>JSON.parse(JSON.stringify(e)),create:(m,y,j)=>this.create(e,m,y,j),lootTable:d,recipe:u,location:s,identifier:i,projectNamespace:o})}async processAdditionalFiles(e,t,s=!1){var w,_,g,v,k,b,S,p,F;const i=(_=(w=this.projectConfig)==null?void 0:w.getRelativePackRoot("behaviorPack"))!=null?_:"BP",r=(g=this.projectConfig)==null?void 0:g.getRelativePackRoot("resourcePack"),o=s?"minecraft:player":(b=(k=(v=t[`minecraft:${this.fileType}`])==null?void 0:v.description)==null?void 0:k.identifier)!=null?b:"bridge:no_identifier",a=(F=(p=(S=this.projectConfig)==null?void 0:S.get())==null?void 0:p.namespace)!=null?F:"bridge";let c;if(a.includes("_")){const h=a.split("_")[0],m=a.split("_").slice(1).join("_");c=`${h}/${m}`}else c="bridge";const l=(await A.hashString(`${this.name}/${o}`)).slice(0,25),d=`${i}/animations/${c}/${l}.json`,f=`${i}/animation_controllers/${c}/${l}.json`;o==="minecraft:player"&&this.createOnPlayer.forEach(([h,m,y])=>{this.create(t,m,h,y)}),r||(this.clientFiles={},this.console.error(`[${this.name}] Dash was unable to load the root of your resource pack and therefore cannot generate client files for this component.`));let u={};return(this.fileType!=="item"||o==="minecraft:player")&&(u={[d]:{baseFile:e,fileContent:this.createAnimations(l,t)},[f]:{baseFile:e,fileContent:this.createAnimationControllers(l,t)}}),{...u,[$.join(i,`dialogue/${c}/${l}.json`)]:this.dialogueScenes[l]&&this.dialogueScenes[l].length>0?{baseFile:e,fileContent:JSON.stringify({format_version:this.targetVersion,"minecraft:npc_dialogue":{scenes:this.dialogueScenes[l]}},null," ")}:void 0,...Object.fromEntries(this.serverFiles.map(([h,m])=>[$.join(i,h),{baseFile:e,fileContent:JSON.stringify(m,null," ")}])),...Object.fromEntries(Object.entries(this.clientFiles).map(([h,m])=>[$.join(r,h),{baseFile:e,fileContent:JSON.stringify(m,null," ")}]))}}createAnimations(e,t){var o,a,c;if(this.animations.length===0)return;const s=(c=(a=(o=this.projectConfig)==null?void 0:o.get())==null?void 0:a.namespace)!=null?c:"bridge";let i=0;const r={format_version:"1.10.0",animations:{}};for(const[l,d]of this.animations){if(!l){i++;continue}const f=this.getAnimName("animation",s,e,i),u=this.getShortAnimName("a",e,i);r.animations[f]=l,this.create(t,{animations:{[u]:f}},"minecraft:entity/description"),d!==!1&&this.create(t,{scripts:{animate:[d?{[u]:d}:u]}},"minecraft:entity/description"),i++}return JSON.stringify(r,null," ")}createAnimationControllers(e,t){var o,a,c;if(this.animationControllers.length===0)return;const s=(c=(a=(o=this.projectConfig)==null?void 0:o.get())==null?void 0:a.namespace)!=null?c:"bridge";let i=0;const r={format_version:"1.10.0",animation_controllers:{}};for(const[l,d]of this.animationControllers){if(!l){i++;continue}const f=this.getAnimName("controller.animation",s,e,i),u=this.getShortAnimName("ac",e,i);r.animation_controllers[f]=l,this.create(t,{animations:{[u]:f}},"minecraft:entity/description"),d!==!1&&this.create(t,{scripts:{animate:[d?{[u]:d}:u]}},"minecraft:entity/description"),i++}return JSON.stringify(r,null," ")}getAnimName(e,t,s,i){return`${e}.${t}.${s}_${i}`}getShortAnimName(e,t,s){var i;return`${(i=t.slice(0,16))!=null?i:"bridge_auto"}_${e}_${s}`}registerLifecycleHook(e,t,s,i,r){e[`minecraft:${this.fileType}`].events||(e[`minecraft:${this.fileType}`].events={});const o=e[`minecraft:${this.fileType}`].events;if(r==="activated"&&t===`minecraft:${this.fileType}/components`)o["minecraft:entity_spawned"]||(o["minecraft:entity_spawned"]={}),this.addEventReponse(o["minecraft:entity_spawned"],s);else if(this.fileType==="entity"&&t.startsWith(`minecraft:${this.fileType}/component_groups/`)){const a=t.split("/").pop();this.findComponentGroupReferences(o,r==="activated"?"add":"remove",a).forEach(l=>this.addEventReponse(l,s))}else if(t.startsWith(`minecraft:${this.fileType}/permutations/`)){const a=t.split("/");if(a.pop()!=="components")throw new Error("Invalid component location inside of permutation");const c=this.getObjAtLocation(e,[...a]),l=`bridge:${i}_${r}_${r==="activated"?this.lifecycleHookCount.activated++:this.lifecycleHookCount.deactivated++}`;c.condition&&this.animationControllers.push([{states:{default:{on_entry:[`@s ${l}`]}}},r==="activated"?c.condition:`!(${c.condition})`]),o[l]=s}}addEventReponse(e,t){if(Array.isArray(e.sequence))e.sequence.push(t);else if(Object.keys(e).length===0)Object.assign(e,t);else{let s=Object.assign({},e,{filters:void 0});for(const i in e)i!=="filters"&&(e[i]=void 0);e.sequence=[s,t]}}findComponentGroupReferences(e,t,s){var r,o;let i=[];for(const a in e){const c=e[a];Array.isArray(c.sequence)?i.push(...this.findComponentGroupReferences(c.sequence,t,s)):Array.isArray(c.randomize)?i.push(...this.findComponentGroupReferences(c.randomize,t,s)):((o=(r=c[t])==null?void 0:r.component_groups)!=null?o:[]).includes(s)&&i.push(c)}return i}}function ke(n){const e=[];for(const[t,s]of n)e.push(...ve(s,t));return e}function ve(n,e){const t=[];for(const s in n)s.startsWith("minecraft:")||s.startsWith("tag:")||t.push([s,e]);return t}function B({fileType:n,getComponentObjects:e}){const t=new Map;let s={};return({console:i,projectConfig:r,projectRoot:o,compileFiles:a,getAliases:c,getAliasesWhere:l,options:d,jsRuntime:f,targetVersion:u,fileType:w,fileSystem:_})=>{let g=null;const v=(h,m)=>{if(!h)return!1;if(g&&h===g)return!0;const y=n==="item"&&(w==null?void 0:w.getId(h))==="entity"&&m(h).includes("minecraft:player");return y&&(g=h),y},k=new Map,b=h=>{if(!h)return!1;if(k.has(h))return k.get(h);const m=d.v1CompatMode?h.includes("/components/"):(w==null?void 0:w.getId(h))==="customComponent"&&h.includes(`/${n}/`);return k.set(h,m),m},S=new Map,p=h=>{if(!h)return!1;if(S.has(h))return S.get(h);const m=(w==null?void 0:w.getId(h))===n;return S.set(h,m),m};let F=!1;return{async buildStart(){var h,m;t.clear(),k.clear(),S.clear(),g=null,s={},F=(await _.allFiles(`${o}${(m=(h=r.get().packs)==null?void 0:h.behaviorPack)==null?void 0:m.substring(1)}/components`).catch(()=>[])).length>0},ignore(h){return!s[h]&&!b(h)&&!p(h)&&!(n==="item"&&w.getId(h)==="entity")},transformPath(h){if(b(h)&&d.buildType!=="fileRequest")return null},async read(h,m){if(!m)return s[h]?O.default.parse(s[h].fileContent):void 0;if(b(h)){F=!0;const y=await m.getFile();return await(y==null?void 0:y.text())}else if(p(h)||v(h,c)){const y=await m.getFile();if(!y)return;try{return O.default.parse(await y.text())}catch(j){return d.buildType!=="fileRequest"&&i.error(`Error within file "${h}": ${j}`),{__error__:`Failed to load original file: ${j}`}}}},async load(h,m){if(!!F&&b(h)&&typeof m=="string"){const y=new Q(i,n,m,d.mode,!!d.v1CompatMode,u);return y.setProjectConfig(r),await y.load(f,h)?y:m}},async registerAliases(h,m){if(!!F&&b(h))return[`${n}Component#${m.name}`]},async require(h,m){if(!!F){if(v(h,c))return l(y=>y.startsWith("itemComponent#"));if(p(h)){const y=ke(e(m));return t.set(h,y),y.map(j=>`${n}Component#${j[0]}`)}else if(s[h])return[s[h].baseFile]}},async transform(h,m,y={}){var j;if(!!F){if(v(h,c)){const M=Object.entries(y).filter(([I])=>I.startsWith("itemComponent#")).map(([I,H])=>H);for(const I of M){if(!I)return;s=A.deepMerge(s,await I.processAdditionalFiles(h,m,!0))}}else if(p(h)){const M=new Set;for(const[I,H]of(j=t.get(h))!=null?j:[]){const T=y[`${n}Component#${I}`];if(!T)continue;const ie=A.get(m,H.split("/"),{}),Ge=ie[I];delete ie[I],await T.processTemplates(m,Ge,H),M.add(T)}for(const I of M)s=A.deepMerge(s,await I.processAdditionalFiles(h,m));for(const I of M)I.reset()}}},finalizeBuild(h,m){if(!!F){if(b(h)&&m)return m.toString();if(p(h)||s[h])return JSON.stringify(m,null," ")}},async buildEnd(){if(!F||d.buildType==="fileRequest")return;s=Object.fromEntries(Object.entries(s).filter(([m,y])=>(y==null?void 0:y.fileContent)!==void 0).map(([m,y])=>[$.join(o,m),y]));const h=Object.keys(s);h.length>0&&await a(h),s={}}}}}const _e=B({fileType:"entity",getComponentObjects:n=>{var e,t,s,i,r,o;return[["minecraft:entity/components",(t=(e=n==null?void 0:n["minecraft:entity"])==null?void 0:e.components)!=null?t:{}],...Object.entries((i=(s=n==null?void 0:n["minecraft:entity"])==null?void 0:s.component_groups)!=null?i:{}).map(([a,c])=>[`minecraft:entity/component_groups/${a}`,c]),...((o=(r=n==null?void 0:n["minecraft:entity"])==null?void 0:r.permutations)!=null?o:[]).map((a,c)=>{var l;return[`minecraft:entity/permutations/${c}/components`,(l=a==null?void 0:a.components)!=null?l:{}]})]}}),be=B({fileType:"item",getComponentObjects:n=>{var e,t;return[["minecraft:item/components",(t=(e=n==null?void 0:n["minecraft:item"])==null?void 0:e.components)!=null?t:{}]]}}),$e=B({fileType:"block",getComponentObjects:n=>{var e,t,s,i;return[["minecraft:block/components",(t=(e=n==null?void 0:n["minecraft:block"])==null?void 0:e.components)!=null?t:{}],...((i=(s=n==null?void 0:n["minecraft:block"])==null?void 0:s.permutations)!=null?i:[]).map((r,o)=>{var a;return[`minecraft:block/permutations/${o}/components`,(a=r.components)!=null?a:{}]})]}});function W(n,e,t,s=0){const i=[];for(const r of n){if(!r.startsWith("/")){i.push(r);continue}const[o,...a]=A.tokenizeCommand(r.slice(1)).tokens.map(({word:l})=>l),c=e[`command#${o}`];if(o==="execute"){let l=4;if(a[l]==="detect"&&(l+=6),a[l]===void 0){i.push(r);continue}const[d,...f]=a.slice(l),u=e[`command#${d}`];if(!(u instanceof q)){i.push(r);continue}i.push(...u.process(`${d} ${f.join(" ")}`,e,s+1).map(w=>w.startsWith("/")?`/execute ${a.slice(0,l).join(" ")} ${w.slice(1)}`:w));continue}else if(!(c instanceof q)){i.push(r);continue}i.push(...c.process(r,e,s))}return i.filter(r=>t||!r.startsWith("#")).map(r=>r.trim())}const Se=n=>({register:e=>{n.command=({name:t,schema:s,template:i})=>{t(e.command_name),s([]),i(r=>new e().onApply(r))}}});class q{constructor(e,t,s,i){this.console=e,this.commandSrc=t,this.mode=s,this.v1Compat=i}get name(){var e;return(e=this._name)!=null?e:"unknown"}async load(e,t,s){const i={command:null},r=await e.run(t,{console:this.console,defineCommand:l=>l,Bridge:this.v1Compat?Se(i):void 0}).catch(l=>(this.console.error(`Failed to execute command ${this.name}: ${l}`),null));if(!r)return null;if(typeof r.__default__!="function")if(i.command)r.__default__=i.command;else return this.console.error(`Component ${t} is not a valid component. Expected a function as the default export.`),!1;const o=l=>this._name=l;let a=l=>this.schema=l,c=()=>{};(!s||s==="server")&&(a=()=>{},c=l=>{this.template=(d,f)=>{try{return l(d,f)}catch(u){return this.console.error(u),[]}}}),await r.__default__({name:o,schema:a,template:c})}process(e,t,s){var c;e.startsWith("/")&&(e=e.slice(1));const[i,...r]=A.tokenizeCommand(e).tokens.map(({word:l})=>l),o=(c=this.template)==null?void 0:c.call(this,r.map(l=>A.castType(l)),{compilerMode:this.mode,commandNestingDepth:s,compileCommands:l=>W(l.map(d=>d.startsWith("/")?d:`/${d}`),t,!1,s+1).map(d=>d.startsWith("/")?d.slice(1):d)});let a=[];if(typeof o=="string")a=o.split(`
`);else if(Array.isArray(o))a=o.filter(l=>typeof l=="string");else{const l=`Failed to process command ${this._name}; Invalid command template return type: Expected string[] or string, received ${typeof o}`;this.console.error(l),a.push(`# ${l}`)}return a.map(l=>l.startsWith("/")||l.startsWith("#")?l:`/${l}`)}getSchema(){if(this.schema){if(Array.isArray(this.schema))return this.schema.length===0?[{commandName:this.name}]:this.schema.map(e=>({commandName:this.name,...e}))}else return[{commandName:this.name}];return this.schema.commandName||(this.schema.commandName=this.name),[this.schema]}toString(){return this.commandSrc}}const je=({projectConfig:n,jsRuntime:e,console:t,fileType:s,requestJsonData:i,options:r})=>{const o=(u,w)=>n.resolvePackPath(u,w),a=u=>u&&s.getId(u)==="customCommand",c=u=>u&&s.getId(u)==="function",l=new Map,d=u=>{if(l.has(u))return l.get(u);const w=r.include[s.getId(u)];return l.set(u,w),w},f=u=>{var w,_,g;return(g=(_=(w=s.get(u))==null?void 0:w.meta)==null?void 0:_.commandsUseSlash)!=null?g:!1};return{async buildStart(){r.include=Object.assign(await i("data/packages/minecraftBedrock/location/validCommand.json"),r.include),l.clear()},ignore(u){return!a(u)&&!c(u)&&!d(u)},transformPath(u){if(a(u)&&r.buildType!=="fileRequest")return null},async read(u,w){if(!!w){if(a(u)&&u.endsWith(".js")){const _=await w.getFile();return await(_==null?void 0:_.text())}else if(c(u)){const _=await w.getFile();return await(_==null?void 0:_.text())}else if(d(u)&&w){const _=await w.getFile();if(!_)return;try{return O.default.parse(await _.text())}catch(g){t.error(g)}}}},async load(u,w){var _;if(a(u)){const g=new q(t,w,r.mode,(_=r.v1CompatMode)!=null?_:!1);return await g.load(e,u),g}},async registerAliases(u,w){if(a(u))return[`command#${w.name}`]},async require(u){if(d(u)||c(u))return[o("behaviorPack","commands/**/*.[jt]s"),o("behaviorPack","commands/*.[jt]s")]},async transform(u,w,_={}){const g=d(u);if(g&&g.length>0){const v=f(u);g.forEach(k=>A.setObjectAt(k,w,b=>{if(!b)return b;b=Array.isArray(b)?b:[b];const S=[];for(const p of b){if(typeof p=="string"){S.push(p);continue}t.error(`The file "${u}" contains invalid commands. Expected type "string" within array but got type "${typeof p}"`)}return W(S.map(p=>!v&&!p.startsWith("/")?`/${p}`:p),_,!1).map(p=>v?p:p.slice(1))}))}else if(c(u)){const v=w.split(`
`).map(k=>k.trim()).filter(k=>k!==""&&!k.startsWith("#")).map(k=>`/${k}`);return W(v,_,!0).map(k=>k.startsWith("/")?k.slice(1):k).join(`
`)}},finalizeBuild(u,w){if(a(u)&&w)return w.toString()}}},Ce=({options:n})=>({ignore(e){return!e.endsWith(".ts")},async transformPath(e){if(!!(e!=null&&e.endsWith(".ts")))return e!=null&&e.endsWith(".d.ts")?null:`${e.slice(0,-3)}.js`},async read(e,t){if(!e.endsWith(".ts")||!t)return;const s=await t.getFile();return await(s==null?void 0:s.text())},async load(e,t){if(!(!e.endsWith(".ts")||t===null||typeof t!="string"))return await x.loadedWasm,J.transformSync(t,{filename:$.basename(e),sourceMaps:n!=null&&n.inlineSourceMap?"inline":void 0,jsc:{parser:{syntax:"typescript"},preserveAllComments:!1,target:"es2020",transform:{useDefineForClassFields:!1}}}).code},finalizeBuild(e,t){if(e.endsWith(".ts")&&typeof t=="string")return t}}),Ae=({options:n,outputFileSystem:e,projectRoot:t,packType:s,fileType:i,console:r})=>{n.packName||(n.packName="bridge project");const o=d=>d.split(/\\|\//g).filter(f=>f!==".."&&f!==".").slice(1).join("/"),a=d=>{const f=s.getId(d),u=$.relative(t,d);if(f==="behaviorPack"||f==="resourcePack"||f==="skinPack")return $.join(t,"builds/dist",f,o(u))},c=d=>{const f=s.getId(d),u=$.relative(t,d);if(f==="worldTemplate")return $.join(t,"builds/dist",o(u));if(f==="behaviorPack"||f==="resourcePack")return $.join(t,"builds/dist",f==="behaviorPack"?"behavior_packs":"resource_packs",n.packName,o(u))},l=d=>i.getId(d)==="worldManifest"?null:c(d);return{async buildStart(){await e.unlink(`${t}/builds/dist`).catch(()=>{})},transformPath(d){if(!!d)switch(n.format){case"mcaddon":return a(d);case"mcworld":return l(d);case"mctemplate":return c(d);default:r.error(`Unknown packaging format: ${n.format}`)}}}},Ie=({projectConfig:n,packType:e,options:t})=>{const s=Object.keys(n.getAvailablePacks()),i=Object.fromEntries(s.map(o=>[o,[]])),r=o=>{const a=e.getId(o);if(a!=="unknown")return[a,n.resolvePackPath(a,"contents.json")]};return t.buildType!=="fullBuild"?{}:{include(){return s.map(o=>[n.resolvePackPath(o,"contents.json"),{isVirtual:!0}])},read(o){const a=r(o);if(!a)return;const[c,l]=a;if(o!==l)return i[c]},transformPath(o){if(!o)return;const a=e.getId(o);a!=="unknown"&&i[a].push(o)},finalizeBuild(o){const a=r(o);if(!a)return;const[c,l]=a;if(o!==l)return JSON.stringify(i[c])}}},Te=({fileType:n})=>{const e=new Set;for(const i of n.all)i.formatVersionMap&&e.add(i.id);const t=new Map,s=i=>{if(!i)return;let r=t.get(i);return r||(r=e.has(n.getId(i)),t.set(i,r),r)};return{ignore(i){return!s(i)},async read(i,r){if(!!r&&s(i)){const o=await r.getFile();if(!o)return;try{return O.default.parse(await o.text())}catch(a){console.error(a)}}},load(i,r){if(s(i))return r},transform(i,r){if(s(i)){const o=n.get(i),a=o==null?void 0:o.formatVersionMap;if(!a)return;const c=r==null?void 0:r.format_version;return c&&a[c]&&(r.format_version=a[c]),r}},finalizeBuild(i,r){if(s(i))return JSON.stringify(r)}}};class Me{constructor(e){this.console=e,this.__isCollection=!0,this.files=new Map}get hasFiles(){return this.files.size>0}getAll(){return[...this.files.entries()]}get(e){return this.files.get(e)}clear(){this.files.clear()}add(e,t){if(this.files.has(e)){this.console.warn(`Omitting file "${e}" from collection because it would overwrite a previously generated file!`);return}this.files.set(e,t)}has(e){return this.files.has(e)}addFrom(e,t){for(const[s,i]of e.getAll()){const r=t?$.join(t,s):s;this.add(r,i)}}}var He=`import { dirname, join } from 'pathe'\r
import type { FileSystem } from '../../../FileSystem/FileSystem'\r
import type { Console } from '../../../Common/Console'\r
// @ts-expect-error\r
import { Collection } from '@bridge-interal/collection'\r
\r
declare const __fileSystem: FileSystem\r
declare const console: Console\r
declare const __omitUsedTemplates: Set<string>\r
declare const __baseDirectory: string\r
\r
export interface IModuleOpts {\r
generatorPath: string\r
omitUsedTemplates: Set<string>\r
fileSystem: FileSystem\r
console: Console\r
}\r
\r
interface IUseTemplateOptions {\r
omitTemplate?: boolean\r
}\r
\r
export function useTemplate(filePath: string, { omitTemplate = true }: IUseTemplateOptions = {}) {\r
const templatePath = join(__baseDirectory, filePath)\r
if (omitTemplate) __omitUsedTemplates.add(templatePath)\r
\r
// TODO(@solvedDev): Pipe file through compileFile API\r
if (filePath.endsWith('.json')) return __fileSystem.readJson(templatePath)\r
else return __fileSystem.readFile(templatePath).then(file => file.text())\r
}\r
\r
export function createCollection() {\r
return new Collection(console)\r
}\r
`,Oe=`import { join } from 'pathe'\r
import { Console } from '../../../Common/Console'\r
\r
export class Collection {\r
public readonly __isCollection = true\r
protected files = new Map<string, any>()\r
constructor(protected console: Console) {}\r
\r
get hasFiles() {\r
return this.files.size > 0\r
}\r
\r
getAll() {\r
return [...this.files.entries()]\r
}\r
\r
get(filePath: string) {\r
return this.files.get(filePath)\r
}\r
\r
clear() {\r
this.files.clear()\r
}\r
add(filePath: string, fileContent: any) {\r
if (this.files.has(filePath)) {\r
this.console.warn(\`Omitting file "\${filePath}" from collection because it would overwrite a previously generated file!\`)\r
return\r
}\r
this.files.set(filePath, fileContent)\r
}\r
has(filePath: string) {\r
return this.files.has(filePath)\r
}\r
addFrom(collection: Collection, baseDir?: string) {\r
for (const [filePath, fileContent] of collection.getAll()) {\r
const resolvedPath = baseDir ? join(baseDir, filePath) : filePath\r
this.add(resolvedPath, fileContent)\r
}\r
}\r
}\r
`;const Pe=({options:n,fileType:e,console:t,jsRuntime:s,fileSystem:i,compileFiles:r,getFileMetadata:o,unlinkOutputFiles:a,addFileDependencies:c})=>{var S;const l=new Set(["gameTest","customCommand","customComponent","molangAstScript",...(S=n.ignoredFileTypes)!=null?S:[]]),d=p=>e.getId(p),f=p=>{var h;const F=e.get(p,void 0,!1);return F?(h=F.type)!=null?h:"json":"raw"},u=p=>!l.has(d(p))&&(p.endsWith(".js")||p.endsWith(".ts")),w=p=>{var h,m,y,j;return f(p)==="json"?".json":(j=(y=(m=(h=e.get(p,void 0,!1))==null?void 0:h.detect)==null?void 0:m.fileExtensions)==null?void 0:y[0])!=null?j:".txt"},_=p=>p.replace(/\.(js|ts)$/,w(p)),g=new Set,v=new Me(t),k=new Set,b=new Map;return{buildStart(){v.clear(),g.clear(),k.clear(),b.clear(),s.registerModule("@bridge-interal/collection",Oe),s.registerModule("@bridge/generate",He),s.registerModule("path-browserify",{dirname:$.dirname,join:$.join}),s.registerModule("pathe",{dirname:$.dirname,join:$.join})},ignore(p){return!u(p)&&!g.has(p)&&!v.has(p)},transformPath(p){if(p&&u(p))return _(p)},async read(p,F){if(u(p)&&F){const m=await F.getFile();return m?m.text():void 0}const h=v.get(p);if(h)return h},async load(p,F){var I,H;if(!u(p))return;if(!F)return null;const h=new Set,m=await s.run(p,{console:t,__baseDirectory:$.dirname(p),__omitUsedTemplates:g,__fileSystem:i},F).catch(T=>(t.error(`Failed to execute generator script "${p}": ${T}`),null));if(!m)return null;if(!m.__default__)return t.error(`Expected generator script "${p}" to provide file content as default export!`),null;const y=o(p);((I=y.get("unlinkedFiles"))!=null?I:[]).filter(T=>!h.has(T)).forEach(T=>k.add(T)),y.set("unlinkedFiles",[...h]);const M=(H=y.get("generatedFiles"))!=null?H:[];return await a([...M,...h]).catch(()=>{}),b.set(p,h),m.__default__},require(p){const F=b.get(p);if(F)return[...F]},finalizeBuild(p,F){if(v.get(p))return p.endsWith(".json")&&typeof F!="string"?JSON.stringify(F,null," "):F;if(g.has(p))return null;if(u(p)){if(F===null)return null;const h=o(p);return F.__isCollection?(v.addFrom(F,$.dirname(p)),h.set("generatedFiles",F.getAll().map(([m])=>m)),null):(h.set("generatedFiles",[_(p)]),typeof F=="object"?JSON.stringify(F):F)}},async buildEnd(){s.deleteModule("@bridge/generate"),s.deleteModule("@bridge-interal/collection"),s.deleteModule("path-browserify"),k.size>0&&await r([...k].filter(p=>!v.has(p)),!1),v.hasFiles&&await r(v.getAll().map(([p])=>p))},async beforeFileUnlinked(p){var F,h;if(u(p)){let m=null;try{m=o(p)}catch{}if(!m)return;const y=(F=m.get("unlinkedFiles"))!=null?F:[],j=(h=m.get("generatedFiles"))!=null?h:[];await a(j),await r(y)}}}};function Y(n,e,t=" "){let s=[],i=[];return JSON.stringify(n,function(r,o){if(r!==""&&(s.push(r),i.push(this)),typeof o!="object"){const a=s.join("/"),c=[...i];if(console.log(a),s.pop(),i.pop(),typeof o=="number"){for(const l of e)if(console.log(a,l.pathGlob,A.isMatch(a,l.pathGlob)),A.isMatch(a,l.pathGlob)&&(!l.apply||l.apply(a,c))){let d=o.toString();return`$___dash___floatPropertyTruncationFix___THIS IS AUTO GENERATED AND I HATE IT___${d.includes(".")?d:d+".0"}`}}return o}else return o},t).replaceAll(/"\$___dash___floatPropertyTruncationFix___THIS IS AUTO GENERATED AND I HATE IT___([0-9]|\.|-)+"/g,r=>r.substring(80,r.length-1))}const Ee=({fileType:n})=>({finalizeBuild(e,t){if((n==null?void 0:n.getId(e))==="entity")return!e.endsWith("player.json")||typeof t=="string"?t:Y(t,[{pathGlob:"minecraft:entity/description/properties/*/value",apply(s,i){return!(i.length===0||i[i.length-1].type!=="float")}},{pathGlob:"minecraft:entity/description/properties/*/range/*",apply(s,i){return!(i.length<2||i[i.length-2].type!=="float")}}])}});class Z extends x.Runtime{constructor(e,t){super(t),this.fs=e}readFile(e){return this.fs.readFile(e)}deleteModule(e){this.baseModules.delete(e)}}const ee={simpleRewrite:ue,rewriteForPackaging:Ae,moLang:z,molang:z,entityIdentifierAlias:de,customEntityComponents:_e,customItemComponents:be,customBlockComponents:$e,customCommands:je,typeScript:Ce,contentsFile:Ie,formatVersionCorrection:Te,generatorScripts:Pe,floatPropertyTruncationFix:Ee},qe=["buildStart","buildEnd","include","ignore","transformPath","read","load","registerAliases","require","transform","finalizeBuild","beforeFileUnlinked"];class De{constructor(e){this.dash=e,this.implementedHooks=new Map,this.pluginRuntime=new Z(this.dash.fileSystem)}pluginsFor(e,t){var s,i;return t?(s=t.myImplementedHooks.get(e))!=null?s:[]:(i=this.implementedHooks.get(e))!=null?i:[]}getImplementedHooks(){return this.implementedHooks}async loadPlugins(e={}){var c;this.implementedHooks.clear(),this.pluginRuntime.clearCache();const t=[...(await this.dash.fileSystem.readdir($.join(this.dash.projectRoot,".bridge/extensions")).catch(()=>[])).map(l=>l.kind==="directory"?$.join(this.dash.projectRoot,".bridge/extensions",l.name):void 0),...(await this.dash.fileSystem.readdir("extensions").catch(()=>[])).map(l=>l.kind==="directory"?$.join("extensions",l.name):void 0)],s={},i=[];for(const l of t)!l||i.push(this.dash.fileSystem.readJson($.join(l,"manifest.json")).then(d=>{var f;if(!!((f=d==null?void 0:d.compiler)!=null&&f.plugins))for(const u in d.compiler.plugins)s[u]=$.join(l,d.compiler.plugins[u])}).catch(()=>{}));await Promise.all(i);const r=(c=(await this.getCompilerOptions()).plugins)!=null?c:[],o=[],a=[];for(let l=0;l<r.length;l++){const d=r[l],f=typeof d=="string"?d:d[0];s[f]?a.push(this.pluginRuntime.run(s[f],{console:this.dash.console,...e}).catch(u=>(this.dash.console.error(`Failed to execute plugin ${f}: ${u}`),null)).then(u=>{!u||(typeof u.__default__=="function"?o[l]=u.__default__:(o[l]=null,this.dash.console.error(`Plugin ${f} is invalid: It does not provide a function as a default export.`)))})):ee[f]?o[l]=ee[f]:(o[l]=null,this.dash.console.error(`Unknown compiler plugin: ${f}`))}await Promise.all(a);for(let l=0;l<r.length;l++){const d=o[l];if(!d)continue;const f=r[l],u=typeof f=="string"?{}:f[1],w=typeof f=="string"?f:f[0];this.addPlugin(w,d,u)}}async addPlugin(e,t,s){const i=new ce(this.dash,e,await t(this.getPluginContext(e,s)));for(const r of qe)if(i.implementsHook(r)){let o=this.implementedHooks.get(r);o||(o=[],this.implementedHooks.set(r,o)),o.push(i)}}async getCompilerOptions(){var t;const e=await this.dash.getCompilerConfigPath();return e?await this.dash.fileSystem.readJson(e):(t=this.dash.projectConfig.get().compiler)!=null?t:{}}getPluginContext(e,t={}){const s=this.dash;return{options:{get mode(){return s.getMode()},get buildType(){return s.buildType},...t},jsRuntime:this.dash.jsRuntime,console:this.dash.console,fileSystem:this.dash.fileSystem,outputFileSystem:this.dash.outputFileSystem,projectConfig:this.dash.projectConfig,projectRoot:this.dash.projectRoot,packType:this.dash.packType,fileType:this.dash.fileType,targetVersion:this.dash.projectConfig.get().targetVersion,requestJsonData:this.dash.requestJsonData,getAliases:i=>{var r,o;return[...(o=(r=this.dash.includedFiles.get(i))==null?void 0:r.aliases)!=null?o:[]]},getAliasesWhere:i=>this.dash.includedFiles.getAliasesWhere(i),getFileMetadata:i=>{const r=this.dash.includedFiles.get(i);if(!r)throw new Error(`File ${i} to get metadata from not found`);return{get(o){return r.getMetadata(o)},set(o,a){r.addMetadata(o,a)},delete(o){r.deleteMetadata(o)}}},addFileDependencies:(i,r,o=!1)=>{const a=this.dash.includedFiles.get(i);if(!a)throw new Error(`File ${i} to add dependency to not found`);o?a.setRequiredFiles(new Set(r)):r.forEach(c=>a.addRequiredFile(c))},getOutputPath:i=>this.dash.getCompilerOutputPath(i),unlinkOutputFiles:i=>this.dash.unlinkMultiple(i,!1,!0),hasComMojangDirectory:this.dash.fileSystem!==this.dash.outputFileSystem,compileFiles:(i,r=!0)=>this.dash.compileAdditionalFiles(i,r),jsonStringifyWithFloatFix:Y}}async runBuildStartHooks(){await Promise.all(this.pluginsFor("buildStart").map(e=>e.runBuildStartHook()))}async runIncludeHooks(){let e=[];for(const t of this.pluginsFor("include")){const s=await t.runIncludeHook();Array.isArray(s)&&e.push(...s)}return e}async runIgnoreHooks(e){for(const t of this.pluginsFor("ignore"))await t.runIgnoreHook(e.filePath)&&e.addIgnoredPlugin(t.pluginId);e.createImplementedHooksMap()}async runTransformPathHooks(e){let t=e.filePath;for(const s of this.pluginsFor("transformPath")){const i=await s.runTransformPathHook(t);if(i===null)return null;i!==void 0&&(t=i)}return t}async runReadHooks(e){for(const t of this.pluginsFor("read",e)){const s=await t.runReadHook(e.filePath,e.fileHandle);if(s!=null)return s}}async runLoadHooks(e){let t=e.data;for(const s of this.pluginsFor("load",e)){const i=await s.runLoadHook(e.filePath,t);i!==void 0&&(t=i)}return t}async runRegisterAliasesHooks(e){const t=new Set;for(const s of this.pluginsFor("registerAliases",e)){const i=await s.runRegisterAliasesHook(e.filePath,e.data);i!=null&&(Array.isArray(i)?i.forEach(r=>t.add(r)):t.add(i))}return t}async runRequireHooks(e){const t=new Set;for(const s of this.pluginsFor("require",e)){const i=await s.runRequireHook(e.filePath,e.data);i!=null&&(Array.isArray(i)?i.forEach(r=>t.add(r)):t.add(i))}return t}async runTransformHooks(e){const t=Object.fromEntries([...e.requiredFiles].map(i=>this.dash.includedFiles.query(i)).flat().map(i=>[[i.filePath,i.data],...[...i.aliases].map(r=>[r,i.data])]).flat());let s=e.data;for(const i of this.pluginsFor("transform",e)){const r=await i.runTransformHook(e.filePath,s,t);r!==void 0&&(s=r)}return s}async runFinalizeBuildHooks(e){for(const t of this.pluginsFor("finalizeBuild",e)){const s=await t.runFinalizeBuildHook(e.filePath,e.data);if(s!==void 0)return s}}async runBuildEndHooks(){await Promise.allSettled(this.pluginsFor("buildEnd").map(e=>e.runBuildEndHook()))}async runBeforeFileUnlinked(e){for(const t of this.pluginsFor("beforeFileUnlinked"))await t.runBeforeFileUnlinked(e)}}class D{constructor(e,t,s=!1){this.dash=e,this.filePath=t,this.isVirtual=s,this.isDone=!1,this.requiredFiles=new Set,this.aliases=new Set,this.updateFiles=new Set,this.metadata=new Map,this.ignoredByPlugins=new Set,this._myImplementedHooks=null,this._cachedFile=null,this.outputPath=t,this.isVirtual||this.setDefaultFileHandle()}isIgnoredBy(e){return this.ignoredByPlugins.has(e)}addIgnoredPlugin(e){this.ignoredByPlugins.add(e)}createImplementedHooksMap(){var s;this._myImplementedHooks=new Map;for(const[i,r]of this.dash.plugins.getImplementedHooks()){const o=r.filter(a=>!this.isIgnoredBy(a.pluginId));this._myImplementedHooks.set(i,o)}((s=this.myImplementedHooks.get("read"))!=null?s:[]).length>0&&(this._cachedFile=this.dash.fileSystem.readFile(this.filePath).catch(()=>null))}get myImplementedHooks(){if(this._myImplementedHooks)return this._myImplementedHooks;throw new Error("Tried to access implemented hooks before they were created")}setFileHandle(e){this.fileHandle=e}setDefaultFileHandle(){this.setFileHandle({getFile:()=>this._cachedFile})}setOutputPath(e){this.outputPath=e}setReadData(e){this.data=e}setAliases(e){for(const t of e)this.dash.includedFiles.addAlias(t,this);this.aliases=e}setRequiredFiles(e){this.requiredFiles=e}addRequiredFile(e){this.requiredFiles.add(e)}setUpdateFiles(e){this.updateFiles=new Set(e.map(t=>this.dash.includedFiles.get(t)).filter(t=>t!==void 0))}addUpdateFile(e){this.updateFiles.add(e)}removeUpdateFile(e){this.updateFiles.delete(e)}setMetadata(e){typeof e=="object"&&(this.metadata=new Map(Object.entries(e)))}addMetadata(e,t){this.metadata.set(e,t)}deleteMetadata(e){this.metadata.delete(e)}getMetadata(e){return this.metadata.get(e)}getAllMetadata(){return Object.fromEntries(this.metadata.entries())}getHotUpdateChain(){const e=new Set([this]);for(const t of this.updateFiles)t.getHotUpdateChain().forEach(s=>{e.add(s)});return e}filesToLoadForHotUpdate(e=new Set,t=!0){const s=new Set;if(e.has(this))return s;e.add(this);for(const i of this.requiredFiles){const r=this.dash.includedFiles.query(i);for(const o of r)o.filesToLoadForHotUpdate(e,!1).forEach(a=>{s.add(a)})}if(s.add(this),t)for(const i of this.updateFiles)i.filesToLoadForHotUpdate(e,!0).forEach(r=>{s.add(r)});return s}processAfterLoad(e,t){(this.data===null||this.data===void 0)&&(this.isDone=!0,this.filePath!==this.outputPath&&this.outputPath!==null&&!this.isVirtual&&e&&t.push(this.dash.fileSystem.copyFile(this.filePath,this.outputPath,this.dash.outputFileSystem)))}serialize(){return{isVirtual:this.isVirtual,filePath:this.filePath,aliases:[...this.aliases],requiredFiles:[...this.requiredFiles],updateFiles:[...this.updateFiles].map(e=>e.filePath),metadata:this.metadata.size>0?Object.fromEntries(this.metadata.entries()):void 0}}reset(){this.isDone=!1,this.data=null,this._myImplementedHooks=null,this._cachedFile=null,this.isVirtual||this.setDefaultFileHandle()}}class xe{constructor(e){this.dash=e,this.files=new Map,this.aliases=new Map,this.queryCache=new Map}all(){return[...this.files.values()]}filtered(e){return this.all().filter(t=>e(t))}get(e){var t;return(t=this.aliases.get(e))!=null?t:this.files.get(e)}getFromFilePath(e){return this.files.get(e)}query(e){const t=this.aliases.get(e);if(t)return[t];const s=this.files.get(e);return s?[s]:ae.default(e)?this.queryGlob(e):[]}addAlias(e,t){this.aliases.set(e,t)}getAliasesWhere(e){return[...this.aliases.keys()].filter(e)}queryGlob(e){if(this.queryCache.has(e))return this.queryCache.get(e);const t=this.filtered(s=>A.isMatch(s.filePath,e));return this.queryCache.set(e,t),t}async loadAll(){this.dash.console.time("Load all files"),this.queryCache=new Map;const e=new Set,t=this.dash.projectConfig.getAvailablePackPaths(),s=[];for(const r of t)s.push(this.dash.fileSystem.allFiles(r).catch(o=>(this.dash.console.warn(o),[])).then(o=>{for(const a of o)e.add(a)}));await Promise.all(s);const i=await this.dash.plugins.runIncludeHooks();for(const r of i)typeof r=="string"?e.add(r):this.addOne(r[0],r[1].isVirtual);this.add([...e]),this.dash.console.timeEnd("Load all files")}addOne(e,t=!1){const s=new D(this.dash,e,t);return this.files.set(e,s),s}add(e,t=!1){let s=[];for(const i of e){const r=this.files.get(i);if(r){s.push(r);continue}s.push(new D(this.dash,i,t)),this.files.set(i,s[s.length-1])}return s}remove(e){const t=this.files.get(e);if(!!t){this.files.delete(e);for(const s of t.aliases)this.aliases.delete(s)}}async save(e){await this.dash.fileSystem.writeJson(e,this.all().map(t=>t.serialize()))}async load(e){this.removeAll();const t=await this.dash.fileSystem.readJson(e).catch(()=>null),s=[];if(!!t){for(const i of t){const r=new D(this.dash,i.filePath,i.isVirtual);r.setAliases(new Set(i.aliases)),r.setRequiredFiles(new Set(i.requiredFiles)),r.setMetadata(i.metadata),r.createImplementedHooksMap(),s.push(r);for(const o of i.aliases)this.aliases.set(o,r)}this.files=new Map(s.map(i=>[i.filePath,i]));for(let i=0;i<s.length;i++)s[i].setUpdateFiles(t[i].updateFiles)}}resetAll(){for(const e of this.all())e.reset()}removeAll(){this.files=new Map,this.aliases=new Map,this.queryCache=new Map}}class Ne{constructor(e){this.dash=e,this.copyFilePromises=[]}async run(e,t=!0){this.copyFilePromises=[];let s=[];for(const i of e)i.isDone||s.push(this.loadFile(i,t));await Promise.allSettled(s),await Promise.allSettled(e.map(async i=>{const r=await this.dash.plugins.runRequireHooks(i);i.setRequiredFiles(r)}))}async loadFile(e,t=!0){var a;const[s,i]=await Promise.all([this.dash.plugins.runIgnoreHooks(e),this.dash.plugins.runTransformPathHooks(e)]),r=await this.dash.plugins.runReadHooks(e);if(e.setOutputPath(i),e.setReadData(r),e.processAfterLoad(t,this.copyFilePromises),e.isDone)return;e.setReadData((a=await this.dash.plugins.runLoadHooks(e))!=null?a:e.data);const o=await this.dash.plugins.runRegisterAliasesHooks(e);e.setAliases(o)}async awaitAllFilesCopied(){this.copyFilePromises.length!==0&&(await Promise.allSettled(this.copyFilePromises),this.copyFilePromises=[])}}class Re{constructor(e){this.dash=e}run(e){const t=new Set;for(const s of e)s.isDone||t.has(s)||this.resolveSingle(s,t);return t}resolveSingle(e,t,s=new Set){const i=this.dash.includedFiles;s.add(e);for(const r of e.requiredFiles){const o=i.query(r);for(const a of o){if(!a){this.dash.console.error(`Undefined file dependency: "${e.filePath}" requires "${r}"`);continue}if(a.addUpdateFile(e),!t.has(a)){if(s.has(a)){this.dash.console.error(`Circular dependency detected: ${a.filePath} is required by ${e.filePath} but also depends on this file.`);continue}this.resolveSingle(a,t,s)}}}t.add(e),s.delete(e)}}function Be(n){return typeof n=="string"||n instanceof Blob||n instanceof File||n instanceof ArrayBuffer||(n==null?void 0:n.buffer)instanceof ArrayBuffer}class We{constructor(e){this.dash=e}async run(e,t=!1){const s=[];for(const i of e){if(i.isDone)continue;let r=await this.transformFile(i,!0,t);r!=null&&i.outputPath!==null&&i.filePath!==i.outputPath&&s.push(this.dash.outputFileSystem.writeFile(i.outputPath,r))}await Promise.allSettled(s)}async transformFile(e,t=!1,s=!1){var r;if(s||(e.data=(r=await this.dash.plugins.runTransformHooks(e))!=null?r:e.data),!t)return e.data;let i=await this.dash.plugins.runFinalizeBuildHooks(e);return i===void 0&&(i=e.data),i!=null&&(Be(i)||(i=JSON.stringify(i))),e.isDone=!0,i}}class Je{constructor(e=1){this.total=e,this.current=0,this.onChangeCbs=new Set}get percentage(){return this.current/this.total}onChange(e){return this.onChangeCbs.add(e),{dispose:()=>this.onChangeCbs.delete(e)}}setTotal(e){this.total=e,this.current=0,this.onChangeCbs.forEach(t=>t(this))}updateCurrent(e){this.current=e,this.onChangeCbs.forEach(t=>t(this))}advance(){this.current++,this.onChangeCbs.forEach(e=>e(this))}addToTotal(e){this.total+=e,this.onChangeCbs.forEach(t=>t(this))}}class te{constructor(e=!1){this.verboseLogs=e,this._timers=new Map}time(e){if(!!this.verboseLogs)if(this._timers.has(e)){this.warn(`Timer "${e}" already exists.`);return}else this._timers.set(e,Date.now())}timeEnd(e){if(!this.verboseLogs)return;const t=this._timers.get(e);if(t)this._timers.delete(e),this.log(`${e}: ${Date.now()-t}ms`);else{this.warn(`Timer "${e}" does not exist.`);return}}}class se extends te{constructor(e){super(e)}log(...e){console.log(...e)}error(...e){console.error(...e)}warn(...e){console.warn(...e)}info(...e){console.info(...e)}}class ze{constructor(e,t,s){var i;this.fileSystem=e,this.options=s,this.progress=new Je,this.plugins=new De(this),this.includedFiles=new xe(this),this.loadFiles=new Ne(this),this.fileOrderResolver=new Re(this),this.fileTransformer=new We(this),this.buildType="fullBuild",this.outputFileSystem=t!=null?t:e,this.projectRoot=$.dirname(s.config),this.projectConfig=new le(e,s.config),this.console=(i=s.console)!=null?i:new se(s.verbose),this.jsRuntime=new Z(this.fileSystem,[["@molang/expressions",E.expressions],["@molang/core",{Molang:E.Molang}],["molang",{Molang:E.Molang,...E.expressions}],["@bridge/compiler",{mode:s.mode}]]),this.packType=s.packType,this.fileType=s.fileType}getMode(){var e;return(e=this.options.mode)!=null?e:"development"}getCompilerConfigPath(){return this.options.compilerConfig}get requestJsonData(){return this.options.requestJsonData}get dashFilePath(){return $.join(this.projectRoot,`.bridge/.dash.${this.getMode()}.json`)}async setup(e){var t,s,i,r;try{await this.projectConfig.setup()}catch(o){this.console.error("Failed to load project config: "+o)}(t=this.fileType)==null||t.setProjectConfig(this.projectConfig),(s=this.packType)==null||s.setProjectConfig(this.projectConfig),await((i=this.fileType)==null?void 0:i.setup(e)),await((r=this.packType)==null?void 0:r.setup(e)),await this.plugins.loadPlugins(this.options.pluginEnvironment)}async reload(){try{await this.projectConfig.refreshConfig()}catch{}await this.plugins.loadPlugins(this.options.pluginEnvironment)}get isCompilerActivated(){const e=this.projectConfig.get();return e.compiler!==void 0&&Array.isArray(e.compiler.plugins)}async build(){if(this.console.log("Starting compilation..."),!this.isCompilerActivated)return;this.jsRuntime.clearCache(),this.buildType="fullBuild",this.includedFiles.removeAll();const e=Date.now();this.progress.setTotal(7),this.console.time("[HOOK] Build start"),await this.plugins.runBuildStartHooks(),this.console.timeEnd("[HOOK] Build start"),this.progress.advance(),await this.includedFiles.loadAll(),this.progress.advance(),await this.compileIncludedFiles(),this.console.time("[HOOK] Build end"),await this.plugins.runBuildEndHooks(),this.console.timeEnd("[HOOK] Build end"),this.progress.advance(),this.getMode()==="development"&&await this.saveDashFile(),this.includedFiles.resetAll(),this.progress.advance(),this.console.log(`Dash compiled ${this.includedFiles.all().length} files in ${Date.now()-e}ms!`)}async updateFiles(e,t=!0){var a;if(!this.isCompilerActivated||e.length===0)return;this.buildType="hotUpdate",this.jsRuntime.clearCache(),this.progress.setTotal(8),this.console.log(`Dash is starting to update ${e.length} files...`),await this.includedFiles.load(this.dashFilePath),await this.plugins.runBuildStartHooks();const s=[];for(const c of e){let l=this.includedFiles.get(c);l||([l]=await this.includedFiles.add([c])),s.push(l)}this.progress.advance();const i=[];for(const c of s)i.push(new Set([...c.requiredFiles]));this.progress.advance(),await this.loadFiles.run(s),this.progress.advance();for(let c=0;c<s.length;c++){const l=s[c];[...l.requiredFiles].filter(u=>!i[c].has(u)).forEach(u=>this.includedFiles.query(u).forEach(w=>w.addUpdateFile(l))),[...i[c]].filter(u=>!l.requiredFiles.has(u)).forEach(u=>this.includedFiles.query(u).forEach(w=>w.removeUpdateFile(l)))}this.progress.advance();const r=new Set(s.map(c=>[...c.filesToLoadForHotUpdate()]).flat());this.console.log(`Dash is loading ${r.size} files...`),await this.loadFiles.run([...r.values()].filter(c=>!s.includes(c))),this.progress.advance();const o=new Set(s.map(c=>[...c.getHotUpdateChain()]).flat());for(const c of r)c.isDone||(c.data=(a=await this.plugins.runTransformHooks(c))!=null?a:c.data,o.has(c)||(c.isDone=!0));this.progress.advance(),this.console.log(`Dash is compiling ${o.size} files...`),await this.fileTransformer.run(o,!0),await this.loadFiles.awaitAllFilesCopied(),this.progress.advance(),await this.plugins.runBuildEndHooks(),t&&await this.saveDashFile(),this.includedFiles.resetAll(),this.console.log(`Dash finished updating ${o.size} files!`),this.progress.advance()}async compileFile(e,t){var o;if(!this.isCompilerActivated)return[[],t];this.buildType="fileRequest",this.jsRuntime.clearCache(),this.progress.setTotal(7),await this.plugins.runBuildStartHooks(),await this.includedFiles.load(this.dashFilePath);let s=this.includedFiles.get(e);s||([s]=await this.includedFiles.add([e])),s.setFileHandle({getFile:async()=>new File([t],$.basename(e))}),await this.loadFiles.loadFile(s,!1),this.progress.advance();const i=s.filesToLoadForHotUpdate();await this.loadFiles.run([...i.values()].filter(a=>s!==a),!1),this.progress.advance();for(const a of i)a.isDone||(a.data=(o=await this.plugins.runTransformHooks(a))!=null?o:a.data);this.progress.advance();const r=await this.fileTransformer.transformFile(s,!0,!0);return this.progress.advance(),await this.includedFiles.load(this.dashFilePath),this.progress.advance(),await this.plugins.runBuildEndHooks(),[[...i].map(a=>a.filePath),r]}async unlinkMultiple(e,t=!0,s=!1){if(!this.isCompilerActivated||e.length===0)return;const i=[];for(const r of e)await this.unlink(r,!1,s).catch(o=>i.push(o));if(i.length>0)throw i[0];t&&await this.saveDashFile()}async unlink(e,t=!0,s=!1){if(!this.isCompilerActivated)return;const i=await this.getCompilerOutputPath(e);!i||i===e||(s||(await this.plugins.runBeforeFileUnlinked(e),this.includedFiles.remove(e)),await this.outputFileSystem.unlink(i),t&&await this.saveDashFile())}async rename(e,t){!this.isCompilerActivated||(await this.unlink(e,!1),await this.updateFiles([t],!1),await this.saveDashFile())}async getCompilerOutputPath(e){var i,r;if(!this.isCompilerActivated)return;const t=(i=this.includedFiles.get(e))!=null?i:new D(this,e);if(t&&t.outputPath!==e)return(r=t.outputPath)!=null?r:void 0;const s=await this.plugins.runTransformPathHooks(t);if(!!s)return s}async getFileMetadata(e){if(!this.isCompilerActivated)return;const t=this.includedFiles.get(e);return t?t.getAllMetadata():null}async getFileDependencies(e){if(!this.isCompilerActivated)return[];await this.includedFiles.load(this.dashFilePath);const t=this.includedFiles.get(e);return t?[...t.filesToLoadForHotUpdate()].filter(s=>!s.isVirtual).map(s=>s.filePath).filter(s=>s!==null&&s!==e):[]}async saveDashFile(){await this.includedFiles.save(this.dashFilePath)}async compileIncludedFiles(e=this.includedFiles.all()){this.console.time("Loading files..."),await this.loadFiles.run(e),this.console.timeEnd("Loading files..."),this.progress.advance(),this.console.time("Resolving file order...");const t=this.fileOrderResolver.run(e);this.console.timeEnd("Resolving file order..."),this.progress.advance(),this.console.time("Transforming files..."),await this.fileTransformer.run(t),this.console.timeEnd("Transforming files..."),this.progress.advance(),await this.loadFiles.awaitAllFilesCopied()}async compileAdditionalFiles(e,t=!0){const s=await this.includedFiles.add(e,t);this.progress.addToTotal(3),s.forEach(i=>i.reset()),await this.compileIncludedFiles(s)}}function Ue(n){x.initRuntimes(n),oe.default(n)}class Ve{async allFiles(e){const t=[],s=await this.readdir(e);for(const{name:i,kind:r}of s)r==="directory"?t.push(...await this.allFiles($.join(e,i))):r==="file"&&t.push($.join(e,i));return t}async directoryHasAnyFile(e){return(await this.readdir(e).catch(()=>[])).length>0}async copyFile(e,t,s=this){const i=await this.readFile(e);await s.writeFile(t,new Uint8Array(await i.arrayBuffer()))}async writeJson(e,t,s=!0){await this.writeFile(e,JSON.stringify(t,null,s?" ":0))}async readJson(e){const t=await this.readFile(e);try{return await O.default.parse(await t.text())}catch{throw new Error(`Invalid JSON: ${e}`)}}watchDirectory(e,t){console.warn("Watching a directory for changes is not supported on this platform!")}}C.Command=q,C.Component=Q,C.Console=te,C.Dash=ze,C.DefaultConsole=se,C.FileSystem=Ve,C.initRuntimes=Ue,Object.defineProperty(C,"__esModule",{value:!0}),C[Symbol.toStringTag]="Module"});