mbler 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1312 @@
1
+ import * as mcxDef from '@mbler/mcx-core';
2
+ import _chalk from 'chalk';
3
+ import jsonPlugin from '@rollup/plugin-json';
4
+ import resolvePlugin from '@rollup/plugin-node-resolve';
5
+ import minifyPlugin from '@rollup/plugin-terser';
6
+ import { watch as watch$1 } from 'chokidar';
7
+ import * as fs from 'node:fs/promises';
8
+ import fs__default from 'node:fs/promises';
9
+ import * as path from 'node:path';
10
+ import path__default, { isAbsolute } from 'node:path';
11
+ import * as rollup from 'rollup';
12
+ import * as readline from 'readline';
13
+ import os, { tmpdir } from 'node:os';
14
+ import { json } from 'npm-registry-fetch';
15
+ import 'node:child_process';
16
+ import crypto from 'node:crypto';
17
+ import * as fs$1 from 'node:fs';
18
+ import { env } from 'node:process';
19
+ import AdmZip from 'adm-zip';
20
+ import commonjs from '@rollup/plugin-commonjs';
21
+ import { createMCXLanguagePlugin } from '@mbler/mcx-server';
22
+ import typescript from '@rollup/plugin-typescript';
23
+ import { runTsc } from '@volar/typescript/lib/quickstart/runTsc';
24
+
25
+ // 启用 raw mode 和键盘事件(仅在 TTY 环境中)
26
+ if (process.stdin.isTTY) {
27
+ process.stdin.setRawMode(true);
28
+ readline.emitKeypressEvents(process.stdin);
29
+ }
30
+ const promises = [];
31
+ const tasks = [];
32
+ process.on("exit", (code) => {
33
+ process.stdout.write("\x1b[?25h");
34
+ });
35
+ const endTasks = [];
36
+ function onEnd(task) {
37
+ endTasks.push(task);
38
+ }
39
+ click("c", {
40
+ ctrl: true,
41
+ }).then(() => {
42
+ endTasks.forEach((task) => task());
43
+ process.exit(0);
44
+ });
45
+ /**
46
+ * 监听键盘输入并触发对应的 Promise 或任务
47
+ */
48
+ function handler(name, { ctrl, alt, }, raw) {
49
+ // 查找是否有匹配的 Promise 等待触发
50
+ const find = promises.find((e) => e.name === name && e.ctrl === ctrl && e.alt === alt);
51
+ if (find) {
52
+ find.resolve();
53
+ promises.splice(promises.indexOf(find), 1);
54
+ }
55
+ // 通知所有注册的监听任务
56
+ tasks.forEach((item) => item(name, ctrl, alt, raw));
57
+ }
58
+ /**
59
+ * 模拟等待某个按键被按下,返回一个 Promise
60
+ */
61
+ function click(name, { ctrl = false, alt = false, }) {
62
+ return new Promise((resolve) => {
63
+ promises.push({
64
+ name,
65
+ ctrl: ctrl || false,
66
+ alt: alt || false,
67
+ resolve,
68
+ });
69
+ });
70
+ }
71
+ /**
72
+ * 工具类:提供控制台交互功能,比如高亮菜单渲染、交互式选择等
73
+ */
74
+ class Input {
75
+ /**
76
+ * 渲染一个字符串数组,高亮当前选中的项
77
+ * @param arr 菜单项数组
78
+ * @param index 当前选中索引
79
+ * @returns 格式化后的字符串
80
+ */
81
+ static render(arr, index) {
82
+ return arr
83
+ .map((item, pindex) => {
84
+ if (pindex === index)
85
+ return "\x1b[1m\x1b[32m" + item + "\x1b[0m"; // 亮绿,高亮
86
+ return "\x1b[1m\x1b[33m" + item + "\x1b[0m"; // 亮黄
87
+ })
88
+ .join(" ");
89
+ }
90
+ /**
91
+ * 提供一个交互式菜单选择器
92
+ * @param tip 提示文本
93
+ * @param arr 选项数组
94
+ * @returns 用户选中的选项内容(Promise<string>)
95
+ */
96
+ static select(tip, arr) {
97
+ let index = 0;
98
+ let win = false;
99
+ console.log(`\x1b[2K\x1b[47m\x1b[1m\x1b[30m${tip} (按 b 确认,n 键选择下一个) \x1b[0m\x1b[?25l`);
100
+ console.log(Input.render(arr, index) + "\n\x1b[1A");
101
+ const handlerNext = () => {
102
+ if (win)
103
+ return;
104
+ index++;
105
+ if (index >= arr.length)
106
+ index = 0;
107
+ console.log(`\x1b[1A${Input.render(arr, index)}\n\x1b[1A`);
108
+ click("n", {
109
+ ctrl: false,
110
+ alt: false,
111
+ }).then(handlerNext);
112
+ };
113
+ return new Promise((resolve) => {
114
+ // 监听 n 按键来切换选项
115
+ click("n", {
116
+ ctrl: false,
117
+ alt: false,
118
+ }).then(handlerNext);
119
+ // 监听 b 按键来确认选择
120
+ click("b", {
121
+ ctrl: false,
122
+ alt: false,
123
+ }).then(() => {
124
+ win = true;
125
+ process.stdout.write("\x1b[?25h");
126
+ resolve(arr[index]);
127
+ });
128
+ });
129
+ }
130
+ /**
131
+ * 注册一个全局任务,每次按键都会被调用
132
+ * @param task 回调函数
133
+ */
134
+ static use(task) {
135
+ tasks.push(task);
136
+ }
137
+ }
138
+ // 监听键盘输入事件
139
+ process.stdin.on("keypress", (str, key) => {
140
+ const rawKeyName = key?.name || "";
141
+ const ctrl = Boolean(key?.ctrl);
142
+ const alt = Boolean(key?.alt);
143
+ handler(rawKeyName, {
144
+ ctrl,
145
+ alt,
146
+ }, str);
147
+ });
148
+
149
+ const templateMblerConfig = {
150
+ name: 'demo',
151
+ description: 'demo',
152
+ version: '0.0.0',
153
+ mcVersion: '1.21.100',
154
+ script: {
155
+ main: '',
156
+ },
157
+ minify: false,
158
+ outdir: {
159
+ behavior: '',
160
+ resources: '',
161
+ dist: '',
162
+ },
163
+ };
164
+
165
+ const BuildConfig = {
166
+ ConfigFile: "mbler.config.js",
167
+ salt: {
168
+ header: "d61e721d-a2c9-4535-8054-0183bce24767",
169
+ sapi: "33e2c698-908f-45ab-8a9f-66018f8486ed",
170
+ module: "cbbacfa4-8b1e-4a9c-9cbd-7a0d2e5f0b3c",
171
+ },
172
+ behavior: "behavior",
173
+ resources: "resources",
174
+ includes: {
175
+ public: {
176
+ "pack_icon.png": "file",
177
+ "manifest.json": "file",
178
+ },
179
+ resources: {
180
+ "biomes_client.json": "file",
181
+ "blocks.json": "file",
182
+ "bug_pack_icon.png": "file",
183
+ "contents.json": "file",
184
+ "loading_messages.json": "file",
185
+ "manifest_publish.json": "file",
186
+ "signatures.json": "file",
187
+ "sounds.json": "file",
188
+ "splashes.json": "file",
189
+ animation_controllers: "directory",
190
+ animations: "directory",
191
+ attachables: "directory",
192
+ biomes: "directory",
193
+ cameras: "directory",
194
+ entity: "directory",
195
+ fogs: "directory",
196
+ font: "directory",
197
+ items: "directory",
198
+ library: "directory",
199
+ materials: "directory",
200
+ models: "directory",
201
+ particles: "directory",
202
+ render_controllers: "directory",
203
+ sounds: "directory",
204
+ texts: "directory",
205
+ textures: "directory",
206
+ },
207
+ behavior: {
208
+ aim_assist: "directory",
209
+ animation_controllers: "directory",
210
+ animations: "directory",
211
+ behavior_trees: "directory",
212
+ biomes: "directory",
213
+ blocks: "directory",
214
+ cameras: "directory",
215
+ dimensions: "directory",
216
+ entities: "directory",
217
+ feature_rules: "directory",
218
+ features: "directory",
219
+ functions: "directory",
220
+ item_catalog: "directory",
221
+ items: "directory",
222
+ loot_tables: "directory",
223
+ recipes: "directory",
224
+ scripts: "skip", // special handling
225
+ spawn_rules: "directory",
226
+ structures: "directory",
227
+ texts: "directory",
228
+ trading: "directory",
229
+ worldgen: "directory",
230
+ "contents.json": "file",
231
+ "manifest_publish.json": "file",
232
+ "signatures.json": "file",
233
+ },
234
+ },
235
+ };
236
+
237
+ async function FileExsit(file) {
238
+ try {
239
+ const f = await fs.stat(file);
240
+ if (f)
241
+ return true;
242
+ }
243
+ catch {
244
+ return false;
245
+ }
246
+ return false;
247
+ }
248
+ function join(baseDir, inputPath) {
249
+ return path.isAbsolute(inputPath) ? inputPath : path.join(baseDir, inputPath);
250
+ }
251
+ async function ReadProjectMblerConfig(project) {
252
+ const fileExport = await import(path.join(project, BuildConfig.ConfigFile));
253
+ const file = fileExport.default || {};
254
+ for (const key in file) {
255
+ if (!(key in templateMblerConfig)) {
256
+ throw new Error(`[read config]: read config from '${project}' error: Unexpected '${key}'`);
257
+ }
258
+ }
259
+ return file;
260
+ }
261
+ /**
262
+ * Print a single-line message to stdout with a trailing newline.
263
+ * Exported here so other modules (for example `build`) do not need
264
+ * to import from `cli`, avoiding a circular dependency.
265
+ */
266
+ // IO缓冲队列,避免多线程写入冲突
267
+ let outputQueue = [];
268
+ let isFlushing = false;
269
+ async function flushOutputQueue() {
270
+ if (isFlushing || outputQueue.length === 0)
271
+ return;
272
+ isFlushing = true;
273
+ try {
274
+ while (outputQueue.length > 0) {
275
+ const chunk = outputQueue.shift();
276
+ if (chunk) {
277
+ process.stdout.write(chunk);
278
+ }
279
+ }
280
+ }
281
+ finally {
282
+ isFlushing = false;
283
+ }
284
+ }
285
+ process.on("exit", flushOutputQueue);
286
+ function showText(text, needNextLine = true) {
287
+ outputQueue.push(text + (needNextLine ? '\n' : ""));
288
+ if (!isFlushing) {
289
+ Promise.resolve().then(() => flushOutputQueue()).catch(() => {
290
+ outputQueue = [];
291
+ isFlushing = false;
292
+ });
293
+ }
294
+ }
295
+ function stringToNumberArray(str) {
296
+ return str
297
+ .split('.')
298
+ .map((s) => parseInt(s, 10))
299
+ .slice(0, 3);
300
+ }
301
+ async function writeJSON(filePath, data) {
302
+ const content = JSON.stringify(data, null, 2);
303
+ if (!(await FileExsit(path.dirname(filePath)))) {
304
+ await fs
305
+ .mkdir(path.dirname(filePath), { recursive: true })
306
+ .catch(() => void 0);
307
+ }
308
+ return await fs.writeFile(filePath, content, 'utf-8');
309
+ }
310
+ function compareVersion(a, b) {
311
+ const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
312
+ const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
313
+ for (let i = 0; i < 3; i++) {
314
+ const na = pa[i] || 0;
315
+ const nb = pb[i] || 0;
316
+ if (na !== nb)
317
+ return na - nb;
318
+ }
319
+ return 0;
320
+ }
321
+ ((function () {
322
+ let curr;
323
+ let currstr = '';
324
+ let tip = '';
325
+ let show = true;
326
+ // 在输入时使用输入中间件
327
+ Input.use(function (raw, ctrl, alt, name) {
328
+ if (typeof curr !== 'function')
329
+ return;
330
+ if (ctrl || alt)
331
+ return;
332
+ if (raw) {
333
+ if (raw === 'return' || raw === 'enter') {
334
+ curr(currstr);
335
+ curr = null;
336
+ currstr = '';
337
+ console.log('');
338
+ return;
339
+ }
340
+ if (raw === 'backspace') {
341
+ currstr = currstr.slice(0, -1);
342
+ refreshInput();
343
+ return;
344
+ }
345
+ }
346
+ if (name && typeof name === 'string') {
347
+ currstr += name;
348
+ refreshInput();
349
+ }
350
+ });
351
+ function refreshInput() {
352
+ const out = `\x1b[2K\r${tip}${show ? currstr : ''}`;
353
+ process.stdout.write(out);
354
+ }
355
+ /**
356
+ * 输入文本
357
+ * @param{string} tip 提示
358
+ * @param{boolean} show 是否显示输入
359
+ */
360
+ return async function (t = '', g = true) {
361
+ return new Promise((resolve) => {
362
+ show = g;
363
+ tip = t;
364
+ refreshInput();
365
+ curr = resolve;
366
+ });
367
+ };
368
+ }))();
369
+
370
+ const logFile = path__default.join(os.homedir(), ".cache/mbler/latest.log");
371
+ function _clean(promise) {
372
+ return () => {
373
+ Logger.run = Logger.run.filter((item) => {
374
+ return item !== promise;
375
+ });
376
+ };
377
+ }
378
+ function writeLog(logContent) {
379
+ async function write() {
380
+ try {
381
+ const dir = path__default.dirname(logFile);
382
+ if (!(await FileExsit(dir))) {
383
+ // ensure the directory exists, root-to-leaf
384
+ await fs__default.mkdir(dir, { recursive: true }).catch(() => void 0);
385
+ }
386
+ // if file does not exist, create it (touch)
387
+ if (!(await FileExsit(logFile))) {
388
+ await fs__default.writeFile(logFile, "");
389
+ }
390
+ }
391
+ catch (err) {
392
+ // if we can't prepare the log file, output to stderr but don't crash
393
+ console.error("[logger] unable to prepare log file:", err);
394
+ return;
395
+ }
396
+ try {
397
+ await fs__default.appendFile(logFile, "\n" + logContent);
398
+ }
399
+ catch (err) {
400
+ console.error("[logger] failed to append to log file:", err);
401
+ }
402
+ }
403
+ const asy = write();
404
+ Logger.run.push(asy.then(_clean(asy)));
405
+ }
406
+ class Logger {
407
+ // 写入日志池
408
+ static LogFile = logFile;
409
+ static run = [];
410
+ static _b(tag, msg, t) {
411
+ const date = new Date();
412
+ const logContent = [
413
+ `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`,
414
+ `[${t} ${tag}]`,
415
+ msg,
416
+ ].join(" ");
417
+ writeLog(logContent);
418
+ }
419
+ static w(tag, msg) {
420
+ Logger._b(tag, msg, "WARN");
421
+ }
422
+ static e(tag, msg) {
423
+ Logger._b(tag, msg, "ERROR");
424
+ }
425
+ static i(tag, msg) {
426
+ Logger._b(tag, msg, "INFO");
427
+ }
428
+ static d(tag, msg) {
429
+ Logger._b(tag, msg, "DEBUG");
430
+ }
431
+ }
432
+
433
+ // 该模块用于从字符串生成哈希转 uuid
434
+ const fromString = (input, salt = '') => {
435
+ const combinedInput = salt + input;
436
+ const hash = crypto
437
+ .createHash('sha256')
438
+ .update(combinedInput)
439
+ .digest('hex');
440
+ const base = hash
441
+ .slice(0, 32); // 取前 32 个 hex 字符(16 字节)
442
+ const ls = '89ab';
443
+ const r = (t) => ls[(combinedInput.length + t + salt.length) % ls.length];
444
+ // 构造成标准 UUID v4 格式:xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
445
+ const uuid = `${base.substring(0, 8)}-${base.substring(8, 12)}-4${base.substring(12, 15)}-8${r(1)}${r(2)}${r(3)}-${base.substring(18, 30)}`;
446
+ return uuid;
447
+ };
448
+ ({
449
+ uuid: crypto.randomUUID
450
+ });
451
+
452
+ const config = {
453
+ tmpdir: path.join(tmpdir(), ".mbler")};
454
+
455
+ /**
456
+ * Compare two dotted version strings ("major.minor.patch").
457
+ * Returns negative if a < b, positive if a > b, zero if equal.
458
+ */
459
+ const exp = (function () {
460
+ const cacheFile = path.join(config.tmpdir, "_sapi_version.json");
461
+ // cacheData is an array of entries keyed by the embedded mc version string
462
+ let cacheData = null;
463
+ /**
464
+ * Pull every published version for a package and reduce it to a mapping
465
+ * from the embedded Minecraft version (e.g. "1.21.60") to the most
466
+ * recent formal/beta release we were able to parse.
467
+ */
468
+ async function fetchData(pkgName) {
469
+ const data = (await json(`/${pkgName}`));
470
+ const pkgVersions = Object.keys(data.versions);
471
+ const reValue = {};
472
+ // helper to extract the embedded MC version ("yyyy") from a full
473
+ // npm package version string. returns null when the expected pattern
474
+ // cannot be found.
475
+ const mcVersionFrom = (str) => {
476
+ const m = str.match(/-(?:rc|beta)(?:\.[^-.]+)*?\.((?:\d+\.){2}\d+)/);
477
+ return m ? m[1] : null;
478
+ };
479
+ for (const v of pkgVersions) {
480
+ const mcVersion = mcVersionFrom(v);
481
+ if (!mcVersion)
482
+ continue;
483
+ const isStable = /(?:-stable)(?:$|[-.])/.test(v);
484
+ let entry = reValue[mcVersion];
485
+ if (!entry) {
486
+ entry = { formal: "", beta: "", _v: -1 };
487
+ reValue[mcVersion] = entry;
488
+ }
489
+ if (isStable) {
490
+ // pick the lexically greatest stable version string
491
+ if (!entry.formal || v > entry.formal) {
492
+ entry.formal = v;
493
+ }
494
+ entry._v = Infinity;
495
+ }
496
+ else {
497
+ // non-stable release; treat everything else as a beta candidate
498
+ if (!entry.beta || v > entry.beta) {
499
+ entry.beta = v;
500
+ }
501
+ if (entry._v !== Infinity)
502
+ entry._v = 1;
503
+ }
504
+ }
505
+ return reValue;
506
+ }
507
+ async function refresh() {
508
+ // grab the two packages we care about and merge the keys
509
+ const serverMap = await fetchData("@minecraft/server");
510
+ const uiMap = await fetchData("@minecraft/server-ui");
511
+ const versions = new Set([
512
+ ...Object.keys(serverMap),
513
+ ...Object.keys(uiMap),
514
+ ]);
515
+ const arr = [];
516
+ for (const ver of Array.from(versions)) {
517
+ arr.push({
518
+ version: ver,
519
+ server: serverMap[ver]
520
+ ? { formal: serverMap[ver].formal, beta: serverMap[ver].beta }
521
+ : { formal: "", beta: "" },
522
+ "server-ui": uiMap[ver]
523
+ ? { formal: uiMap[ver].formal, beta: uiMap[ver].beta }
524
+ : { formal: "", beta: "" },
525
+ });
526
+ }
527
+ arr.sort((a, b) => compareVersion(a.version, b.version));
528
+ cacheData = arr;
529
+ await fs$1.promises
530
+ .mkdir(config.tmpdir, { recursive: true })
531
+ .catch(() => void 0);
532
+ await fs$1.promises.writeFile(cacheFile, JSON.stringify(arr, null, 2), "utf-8");
533
+ }
534
+ async function generateVersion(module, mcVersion, isBeta) {
535
+ if (!cacheData) {
536
+ try {
537
+ const txt = await fs$1.promises.readFile(cacheFile, "utf-8");
538
+ cacheData = JSON.parse(txt);
539
+ }
540
+ catch {
541
+ await refresh();
542
+ }
543
+ }
544
+ if (!cacheData) {
545
+ throw new Error("unable to load sapi cache data");
546
+ }
547
+ // try exact match first
548
+ let entry = cacheData.find((e) => e.version === mcVersion);
549
+ if (!entry) {
550
+ // find closest entry less than or equal to requested version
551
+ const sorted = cacheData.slice();
552
+ let candidate = null;
553
+ for (const e of sorted) {
554
+ if (compareVersion(e.version, mcVersion) <= 0) {
555
+ candidate = e;
556
+ }
557
+ else {
558
+ break;
559
+ }
560
+ }
561
+ if (!candidate) {
562
+ candidate = sorted[0];
563
+ }
564
+ entry = candidate;
565
+ }
566
+ const moduleKey = module === "@minecraft/server" ? "server" : "server-ui";
567
+ const entryModule = entry[moduleKey];
568
+ let result = isBeta ? entryModule.beta : entryModule.formal;
569
+ if (!result) {
570
+ // fall back to whatever is available
571
+ result = entryModule.formal || entryModule.beta;
572
+ }
573
+ return result || "";
574
+ }
575
+ return {
576
+ refresh,
577
+ generateVersion,
578
+ };
579
+ })();
580
+
581
+ async function generateManifest(config, type) {
582
+ const manifest = {
583
+ format_version: 2,
584
+ header: {
585
+ name: config.name,
586
+ description: config.description,
587
+ uuid: fromString(config.name, BuildConfig.salt.header + type),
588
+ version: stringToNumberArray(config.version),
589
+ min_engine_version: stringToNumberArray(typeof config.mcVersion === "string"
590
+ ? config.mcVersion
591
+ : (() => {
592
+ throw new Error("mcVersion in mblerconfig should be a string");
593
+ })()),
594
+ },
595
+ modules: [
596
+ {
597
+ type: type,
598
+ uuid: fromString(config.name, BuildConfig.salt.module + type),
599
+ description: `From Mbler(https://github.com/RuanhoR/mbler). welcome to star and contribute!`,
600
+ version: stringToNumberArray(config.version),
601
+ },
602
+ ],
603
+ };
604
+ if (type === "data" && config.script) {
605
+ manifest.modules.push({
606
+ type: "script",
607
+ uuid: fromString(config.name, BuildConfig.salt.sapi + type),
608
+ description: `sapi generate by mbler, weclome to download and star at https://github.com/RuanhoR/mbler`,
609
+ version: stringToNumberArray(config.version),
610
+ });
611
+ manifest.capabilities = ["script_eval"];
612
+ manifest.dependencies = [
613
+ {
614
+ module_name: "@minecraft/server",
615
+ version: (await exp.generateVersion("@minecraft/server", config.mcVersion, config.script?.UseBeta || false)).split("-")[0], // only major.minor.patch, remove -beta or -rc
616
+ },
617
+ ];
618
+ if (config.script.ui) {
619
+ manifest.dependencies.push({
620
+ module_name: "@minecraft/server-ui",
621
+ version: (await exp.generateVersion("@minecraft/server-ui", config.mcVersion, config.script?.UseBeta || false)).split("-")[0], // only major.minor.patch, remove -beta or -rc
622
+ });
623
+ }
624
+ }
625
+ return manifest;
626
+ }
627
+
628
+ function createFullZip(dir) {
629
+ const zip = new AdmZip();
630
+ zip.addLocalFolder(dir);
631
+ return zip;
632
+ }
633
+ async function createZipWithMoreFolder(dir) {
634
+ const zip = new AdmZip();
635
+ for (const folder of dir) {
636
+ await zip.addLocalFolderPromise(folder[0], {
637
+ zipPath: folder[1]
638
+ });
639
+ }
640
+ return zip;
641
+ }
642
+ async function generateRelease(build) {
643
+ if (!build.srcDirs)
644
+ throw new Error("invaild Build");
645
+ if (env.BUILD_MODULE !== "release")
646
+ return;
647
+ let zip;
648
+ if (build.module == "all") {
649
+ zip = await createZipWithMoreFolder([
650
+ [build.srcDirs?.behavior, "behavior"],
651
+ [build.srcDirs.resources, "resources"]
652
+ ]);
653
+ }
654
+ else if (build.module == "behavior") {
655
+ zip = createFullZip(build.srcDirs.behavior);
656
+ }
657
+ else {
658
+ zip = createFullZip(build.srcDirs.resources);
659
+ }
660
+ await zip.writeZipPromise(build.outdirs?.dist);
661
+ }
662
+
663
+ // cjs support
664
+ const chalk$1 = _chalk instanceof Function ? _chalk : _chalk.default;
665
+ class Postgress {
666
+ max;
667
+ constructor(max) {
668
+ this.max = max;
669
+ }
670
+ update(current) {
671
+ const percentage = Math.min(current, this.max) / this.max;
672
+ const barWidth = 30;
673
+ const filledWidth = Math.round(barWidth * percentage);
674
+ const emptyWidth = barWidth - filledWidth;
675
+ const filledBar = chalk$1.green('█'.repeat(filledWidth));
676
+ const emptyBar = chalk$1.white('█'.repeat(emptyWidth));
677
+ const progressBar = `${filledBar}${emptyBar}`;
678
+ const percentText = chalk$1.blue(`${Math.round(percentage * 100)}%`);
679
+ const progressText = `\n\u001B[1A\r[${progressBar}] ${percentText} (${current}/${this.max})`;
680
+ showText(progressText, false);
681
+ if (current == this.max) {
682
+ showText("", true);
683
+ }
684
+ }
685
+ }
686
+
687
+ /**
688
+ * 运行 MCX TypeScript 编译器
689
+ * 为 .mcx 文件提供 TypeScript 类型检查支持
690
+ */
691
+ function runTSC(tscpath = require.resolve("typescript/lib/tsc")) {
692
+ runTsc(tscpath, {
693
+ extraSupportedExtensions: ['.mcx'],
694
+ extraExtensionsToRemove: ['.mcx'],
695
+ }, (ts) => {
696
+ return [createMCXLanguagePlugin(ts)];
697
+ });
698
+ }
699
+
700
+ // cjs support
701
+ const chalk = _chalk instanceof Function ? _chalk : _chalk.default;
702
+ class Build {
703
+ baseBuildDir;
704
+ resolve;
705
+ isWatch;
706
+ currentConfig = null;
707
+ srcDirs = null;
708
+ outdirs = null;
709
+ mcxTs;
710
+ mcxLanguagePluginCreator = null;
711
+ constructor(opts, baseBuildDir, resolve, isWatch = false) {
712
+ this.baseBuildDir = baseBuildDir;
713
+ this.resolve = resolve;
714
+ this.isWatch = isWatch;
715
+ // 初始化 MCX 语言插件创建器,传入 tsHook.ts 使用
716
+ try {
717
+ const tsModule = require("typescript");
718
+ this.mcxLanguagePluginCreator = createMCXLanguagePlugin;
719
+ this.mcxTs = tsModule;
720
+ Logger.i("Build", "MCX Volar language plugin creator initialized successfully");
721
+ }
722
+ catch (error) {
723
+ this.mcxTs = require("typescript");
724
+ Logger.w("Build", `Failed to initialize MCX language plugin: ${error}`);
725
+ }
726
+ }
727
+ /**
728
+ * Start the watch mode.
729
+ * This will perform an initial build (if not already done) and then
730
+ * start filesystem and rollup watchers.
731
+ * Returns the watcher handles once they are created so that callers
732
+ * (for example tests) can clean them up later.
733
+ */
734
+ async watch() {
735
+ try {
736
+ onEnd(() => {
737
+ if (this.watchers) {
738
+ this.watchers.chokidar.close();
739
+ this.watchers.rollup.close();
740
+ }
741
+ });
742
+ await this._watch();
743
+ }
744
+ catch (e) {
745
+ if (e instanceof Error) {
746
+ Logger.e('Watcher', e.stack || e.message);
747
+ }
748
+ else {
749
+ Logger.e('Watcher', e + '');
750
+ }
751
+ showText('MBLER__ERR__WATCHER: ' + e + ' Log at ' + Logger.LogFile);
752
+ this.resolve(1);
753
+ return null;
754
+ }
755
+ }
756
+ async start() {
757
+ try {
758
+ return await this.build();
759
+ }
760
+ catch (e) {
761
+ if (e instanceof Error) {
762
+ Logger.e('Build', e.stack || e.message);
763
+ }
764
+ else {
765
+ Logger.e('Build', e + '');
766
+ }
767
+ showText('MBLER__ERR__BUILD: ' + e.stack + ' Log at ' + Logger.LogFile);
768
+ this.resolve(1);
769
+ }
770
+ }
771
+ /**
772
+ * Handles returned from the currently-active watchers.
773
+ * Set by {@link createWatcher} and exposed via {@link getWatchers}
774
+ * so that external callers can close them when necessary (e.g. tests).
775
+ */
776
+ watchers = null;
777
+ /**
778
+ * Returns the watcher handles if watch mode has been started.
779
+ * Can be safely called even before `watch()` has been invoked.
780
+ */
781
+ getWatchers() {
782
+ return this.watchers;
783
+ }
784
+ /**
785
+ * Close any active watchers. The build process does not automatically
786
+ * terminate the watchers unless the process exits; tests or CLI wrappers
787
+ * can call this method to clean up resources.
788
+ */
789
+ closeWatchers() {
790
+ if (this.watchers) {
791
+ this.watchers.chokidar.close();
792
+ this.watchers.rollup.close();
793
+ this.watchers = null;
794
+ }
795
+ }
796
+ rollupPlugin = null;
797
+ init = false;
798
+ /**
799
+ * Which modules are present in the current project.
800
+ * - "behavior" when only behavior code exists
801
+ * - "resources" when only resource files exist
802
+ * - "all" when both are present
803
+ * This field is populated during `handlerOtherAddon`.
804
+ */
805
+ module = null;
806
+ /**
807
+ * Determine whether a path refers to a regular file or a directory.
808
+ * Follows symbolic links recursively. Throws if the path exists but
809
+ * is not one of the expected types.
810
+ *
811
+ * @param filePath file system path to inspect
812
+ * @returns "file" or "directory"
813
+ */
814
+ async fileType(filePath) {
815
+ const stat = await fs.lstat(filePath);
816
+ if (stat.isFile()) {
817
+ return 'file';
818
+ }
819
+ if (stat.isDirectory()) {
820
+ return 'directory';
821
+ }
822
+ if (stat.isSymbolicLink()) {
823
+ return await this.fileType(await fs.readlink(filePath));
824
+ }
825
+ throw new Error('[build addon]: invaild file type');
826
+ }
827
+ /**
828
+ * Perform a single build of the project located at {@link baseBuildDir}.
829
+ * The process is roughly:
830
+ * 1. load and validate the configuration file
831
+ * 2. prepare source and output directory information
832
+ * 3. copy addon files (behavior/resources)
833
+ * 4. generate manifest.json files
834
+ * 5. run rollup to bundle any script entry point
835
+ *
836
+ * If anything goes wrong the promise returned by the public wrapper
837
+ * (`build()` function exported at the bottom of this file) will be
838
+ * resolved with a non-zero code and appropriate log entries will be
839
+ * emitted.
840
+ */
841
+ async build() {
842
+ const progress = new Postgress(100);
843
+ this.init = true;
844
+ if (!isAbsolute(this.baseBuildDir)) {
845
+ throw new Error('[init build]: build dir is not absolute path');
846
+ }
847
+ this.currentConfig = await ReadProjectMblerConfig(this.baseBuildDir);
848
+ this.loadData();
849
+ if (!this.isWatch)
850
+ progress.update(10);
851
+ await this.handlerOtherAddon();
852
+ await this.handlerManifest();
853
+ if (!this.isWatch)
854
+ progress.update(30);
855
+ const rBuild = (await this.createRollup());
856
+ if (!this.rollupPlugin || !this.outdirs) {
857
+ throw new Error(`[build addon]: can't resolve rollup instance`);
858
+ }
859
+ if (!this.isWatch)
860
+ progress.update(50);
861
+ // write script
862
+ let output = this.currentConfig.script?.main;
863
+ if (!output)
864
+ output = "index.js";
865
+ if (path__default.extname(output) !== "js")
866
+ output = output.slice(0, output.length - path__default.extname(output).length) + ".js";
867
+ if (this.currentConfig.script)
868
+ await rBuild.write({
869
+ file: join(path__default.join(this.outdirs.behavior, "scripts"), output),
870
+ format: 'esm',
871
+ sourcemap: false,
872
+ });
873
+ if (!this.isWatch)
874
+ progress.update(70);
875
+ await generateRelease(this);
876
+ if (!this.isWatch)
877
+ progress.update(80);
878
+ if (!this.isWatch)
879
+ this.resolve(0);
880
+ if (!this.isWatch)
881
+ progress.update(100);
882
+ }
883
+ /**
884
+ * Create and return a Rollup build instance configured for the
885
+ * project's script. The Rollup configuration mirrors the options
886
+ * used by the CLI when running manual builds.
887
+ *
888
+ * Returns undefined if the project does not define a script section
889
+ * (in which case nothing needs to be bundled).
890
+ */
891
+ async createRollup() {
892
+ if (!this.currentConfig || !this.srcDirs || !this.outdirs)
893
+ throw new Error(`[build addon]: can't first can this method`);
894
+ if (!this.currentConfig.script)
895
+ return;
896
+ const main = path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig.script.main);
897
+ if (!(await FileExsit(main))) {
898
+ throw new Error(`[build addon]: main script ${main} is not exist: can't resolve entry`);
899
+ }
900
+ const plugin = [
901
+ jsonPlugin(),
902
+ resolvePlugin({
903
+ extensions: ['.ts', '.js', '.json'],
904
+ }),
905
+ commonjs()
906
+ ];
907
+ const moduleDir = path__default.join(this.baseBuildDir, 'node_modules');
908
+ if (!(await FileExsit(moduleDir))) {
909
+ throw new Error(`[build addon]: node_modules is not exist in project root: can't resolve node_modules for rollup: ${moduleDir}`);
910
+ }
911
+ if (this.currentConfig.minify) {
912
+ plugin.push(minifyPlugin({
913
+ format: {
914
+ comments: false,
915
+ },
916
+ compress: {
917
+ unused: true,
918
+ },
919
+ }));
920
+ }
921
+ if (this.currentConfig.script.lang == "ts") {
922
+ const tsconfigPath = path__default.join(this.baseBuildDir, 'tsconfig.json');
923
+ if (!(await FileExsit(tsconfigPath))) {
924
+ throw new Error(`[build addon]: ts-lang: tsconfig.json is not exist in project root: can't resolve tsconfig for rollup: ${tsconfigPath}`);
925
+ }
926
+ plugin.push(typescript({
927
+ sourceMap: false,
928
+ tsconfig: tsconfigPath,
929
+ exclude: [
930
+ this.outdirs.behavior,
931
+ this.outdirs.resources
932
+ ],
933
+ include: [
934
+ this.srcDirs.behavior
935
+ ]
936
+ }));
937
+ }
938
+ if (this.currentConfig.script?.lang == 'mcx') {
939
+ try {
940
+ const tsconfigPath = path__default.join(this.baseBuildDir, 'tsconfig.json');
941
+ if (!(await FileExsit(tsconfigPath))) {
942
+ throw new Error(`[build addon]: ts-lang: tsconfig.json is not exist in project root: can't resolve tsconfig for rollup: ${tsconfigPath}`);
943
+ }
944
+ const pluginConfig = {
945
+ moduleDir: moduleDir,
946
+ tsconfigPath: tsconfigPath,
947
+ sourcemap: false,
948
+ ts: this.mcxTs,
949
+ mcxLanguagePlugin: this.mcxLanguagePluginCreator
950
+ };
951
+ if (this.mcxLanguagePluginCreator) {
952
+ pluginConfig.mcxLanguagePlugin = this.mcxLanguagePluginCreator;
953
+ }
954
+ plugin.push(mcxDef.plugin(pluginConfig, this.outdirs));
955
+ }
956
+ catch (err) {
957
+ throw new Error(`[build addon]: mcx plugin is required but '@mbler/mcx-core' could not be loaded: ${err}`);
958
+ }
959
+ }
960
+ // save plugin array for watcher re-use
961
+ this.rollupPlugin = plugin;
962
+ return await rollup.rollup({
963
+ input: main,
964
+ external: ['@minecraft/server', '@minecraft/server-ui'],
965
+ plugins: plugin,
966
+ });
967
+ }
968
+ /**
969
+ * Internal helper invoked by {@link watch}.
970
+ * Ensures a build has been run before starting the watchers.
971
+ */
972
+ async _watch() {
973
+ // init build
974
+ if (!this.init) {
975
+ await this.build();
976
+ }
977
+ this.createWatcher();
978
+ // watchers field is populated by createWatcher
979
+ }
980
+ isParent(parent, dir) {
981
+ const relative = path__default.relative(parent, dir);
982
+ return (!!relative && !relative.startsWith('..') && !path__default.isAbsolute(relative));
983
+ }
984
+ isChange(oldObj, newObj, checkKeys) {
985
+ for (const key of checkKeys) {
986
+ if (typeof oldObj[key] === 'object' &&
987
+ typeof newObj[key] === 'object' &&
988
+ oldObj[key] !== null &&
989
+ newObj[key] !== null) {
990
+ if (this.isChange(oldObj[key], newObj[key], Object.getOwnPropertyNames(oldObj[key]))) {
991
+ return true;
992
+ }
993
+ }
994
+ else if (oldObj[key] !== newObj[key]) {
995
+ return true;
996
+ }
997
+ }
998
+ return false;
999
+ }
1000
+ createRollupWatcher() {
1001
+ if (!this.srcDirs ||
1002
+ !this.outdirs ||
1003
+ !this.currentConfig ||
1004
+ !this.rollupPlugin)
1005
+ throw new Error(`[build addon]: can't first can this method`);
1006
+ let output = this.currentConfig.script?.main;
1007
+ if (!output)
1008
+ output = "index.js";
1009
+ if (path__default.extname(output) !== "js")
1010
+ output = output.slice(0, output.length - path__default.extname(output).length) + ".js";
1011
+ const rollupWatcher = rollup.watch({
1012
+ input: path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1013
+ external: ['@minecraft/server', '@minecraft/server-ui'],
1014
+ plugins: this.rollupPlugin,
1015
+ output: {
1016
+ file: join(path__default.join(this.outdirs.behavior, "scripts"), output),
1017
+ format: 'esm',
1018
+ sourcemap: false,
1019
+ },
1020
+ cache: true,
1021
+ watch: {
1022
+ clearScreen: false,
1023
+ include: path__default.join(this.srcDirs.behavior, 'scripts/**/*'),
1024
+ exclude: [
1025
+ path__default.join(this.baseBuildDir, 'node_modules/**/*'),
1026
+ this.outdirs.behavior,
1027
+ this.outdirs.resources,
1028
+ this.outdirs.dist,
1029
+ ],
1030
+ },
1031
+ });
1032
+ rollupWatcher.on('change', async (filePath) => {
1033
+ Logger.i('Watcher', `file changed: ${filePath}, start rebuild`);
1034
+ });
1035
+ rollupWatcher.on('event', async (event) => {
1036
+ if (event.code === 'ERROR') {
1037
+ Logger.e('Watcher', `rollup error: ${event.error.stack || event.error}`);
1038
+ showText('MBLER__ERR__ROLLUP: ' +
1039
+ (event.error.stack || event.error) +
1040
+ ' Log at ' +
1041
+ Logger.LogFile);
1042
+ }
1043
+ else if (event.code === 'END') {
1044
+ Logger.i('Watcher', `rebuild success`);
1045
+ }
1046
+ });
1047
+ return rollupWatcher;
1048
+ }
1049
+ async onChange(filePath) {
1050
+ if (!this.srcDirs ||
1051
+ !this.outdirs ||
1052
+ !this.currentConfig ||
1053
+ !this.rollupPlugin ||
1054
+ !this.watchers)
1055
+ throw new Error(`[build addon]: can't first can this method`);
1056
+ const isConfigChange = path__default.relative(path__default.join(this.baseBuildDir, 'mbler.config.json'), filePath) === '';
1057
+ const isBehaviorChange = this.isParent(this.srcDirs.behavior, filePath) && !this.isParent(path__default.join(this.srcDirs.behavior, 'scripts'), filePath);
1058
+ const isResourcesChange = this.isParent(this.srcDirs.resources, filePath);
1059
+ if (isConfigChange) {
1060
+ const oldConfig = this.currentConfig;
1061
+ Logger.i('Watcher', 'detected mbler.config.json change, reload config');
1062
+ this.currentConfig = await ReadProjectMblerConfig(this.baseBuildDir);
1063
+ this.loadData();
1064
+ if (this.isChange(oldConfig, this.currentConfig, [
1065
+ 'name',
1066
+ 'version',
1067
+ 'description',
1068
+ 'mcVersion',
1069
+ ])) {
1070
+ await this.handlerManifest();
1071
+ }
1072
+ if (this.isChange(oldConfig, this.currentConfig, ['script', 'outdir'])) {
1073
+ this.watchers.rollup.close();
1074
+ await this.createRollup();
1075
+ this.watchers.rollup = rollup.watch({
1076
+ input: path__default.join(this.srcDirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1077
+ external: ['@minecraft/server', '@minecraft/server-ui'],
1078
+ plugins: this.rollupPlugin,
1079
+ output: {
1080
+ file: path__default.join(this.outdirs.behavior, 'scripts', this.currentConfig?.script?.main || ''),
1081
+ format: 'esm',
1082
+ },
1083
+ });
1084
+ }
1085
+ }
1086
+ // if behavior or resources change, we can just copy the changed file instead of copy all files again.
1087
+ if (isBehaviorChange || isResourcesChange) {
1088
+ const handlerBP = async () => {
1089
+ if (!this.srcDirs || !this.outdirs)
1090
+ throw new Error(`[build addon]: can't first can this method`);
1091
+ const relativePath = path__default.relative(this.srcDirs.behavior, filePath);
1092
+ await fs.cp(path__default.join(this.srcDirs.behavior, relativePath), path__default.join(this.outdirs.behavior, relativePath), {
1093
+ recursive: true,
1094
+ force: true,
1095
+ });
1096
+ };
1097
+ const handlerRP = async () => {
1098
+ if (!this.srcDirs || !this.outdirs)
1099
+ throw new Error(`[build addon]: can't first can this method`);
1100
+ const relativePath = path__default.relative(this.srcDirs.resources, filePath);
1101
+ await fs.cp(path__default.join(this.srcDirs.resources, relativePath), path__default.join(this.outdirs.resources, relativePath), {
1102
+ recursive: true,
1103
+ force: true,
1104
+ });
1105
+ };
1106
+ if (isBehaviorChange) {
1107
+ await handlerBP();
1108
+ }
1109
+ if (isResourcesChange) {
1110
+ await handlerRP();
1111
+ }
1112
+ }
1113
+ showText(`[${chalk.green('mbler')}] ${chalk.bgYellow(`file changed: ${filePath}`)}`);
1114
+ }
1115
+ createWatcher() {
1116
+ if (!this.srcDirs || !this.outdirs || !this.rollupPlugin)
1117
+ throw new Error(`[build addon]: can't first can this method`);
1118
+ const chokidar = watch$1(this.baseBuildDir, {
1119
+ ignored: [
1120
+ this.outdirs.behavior,
1121
+ this.outdirs.resources,
1122
+ this.outdirs.dist,
1123
+ path__default.join(this.baseBuildDir, 'node_modules'),
1124
+ ],
1125
+ ignoreInitial: true,
1126
+ interval: 100,
1127
+ });
1128
+ const onChange = async (filePath) => {
1129
+ await this.onChange(filePath);
1130
+ };
1131
+ chokidar.on('change', onChange);
1132
+ const rollupWatcher = this.createRollupWatcher();
1133
+ this.watchers = {
1134
+ chokidar,
1135
+ rollup: rollupWatcher,
1136
+ };
1137
+ }
1138
+ async handlerManifest() {
1139
+ if (!this.currentConfig || !this.outdirs || !this.srcDirs || !this.module)
1140
+ throw new Error(`[build addon]: can't first can this method`);
1141
+ const otherManifestOption = {
1142
+ behavior: {},
1143
+ resources: {},
1144
+ };
1145
+ const handlerBP = async () => {
1146
+ if (!this.outdirs || !this.currentConfig)
1147
+ throw new Error(`[build addon]: can't first can this method`);
1148
+ const manifest = await generateManifest(this.currentConfig, 'data');
1149
+ await writeJSON(path__default.join(this.outdirs.behavior, 'manifest.json'), {
1150
+ ...manifest,
1151
+ ...otherManifestOption.behavior,
1152
+ });
1153
+ };
1154
+ const handlerRP = async () => {
1155
+ if (!this.outdirs || !this.currentConfig)
1156
+ throw new Error(`[build addon]: can't first can this method`);
1157
+ const manifest = await generateManifest(this.currentConfig, 'resources');
1158
+ await writeJSON(path__default.join(this.outdirs.resources, 'manifest.json'), {
1159
+ ...manifest,
1160
+ ...otherManifestOption.resources,
1161
+ });
1162
+ };
1163
+ if (this.module == 'behavior' || this.module == 'all') {
1164
+ const filePath = path__default.join(this.srcDirs.behavior, 'manifest.json');
1165
+ if (await FileExsit(filePath)) {
1166
+ try {
1167
+ const content = await fs.readFile(filePath, 'utf-8');
1168
+ const json = JSON.parse(content);
1169
+ otherManifestOption.behavior = json;
1170
+ }
1171
+ catch (err) {
1172
+ Logger.w('Build', 'invalid manifest.json in behavior');
1173
+ }
1174
+ }
1175
+ await handlerBP();
1176
+ }
1177
+ if (this.module == 'resources' || this.module == 'all') {
1178
+ const filePath = path__default.join(this.srcDirs.resources, 'manifest.json');
1179
+ if (await FileExsit(filePath)) {
1180
+ try {
1181
+ const content = await fs.readFile(filePath, 'utf-8');
1182
+ const json = JSON.parse(content);
1183
+ otherManifestOption.resources = json;
1184
+ }
1185
+ catch (err) {
1186
+ Logger.w('Build', 'invalid manifest.json in resources');
1187
+ }
1188
+ }
1189
+ await handlerRP();
1190
+ }
1191
+ }
1192
+ loadData() {
1193
+ // check run time
1194
+ if (!this.currentConfig || !this.baseBuildDir)
1195
+ throw new Error("[build data]: can't resolve again");
1196
+ // source code dir
1197
+ this.srcDirs = {
1198
+ behavior: path__default.join(this.baseBuildDir, BuildConfig.behavior),
1199
+ resources: path__default.join(this.baseBuildDir, BuildConfig.resources), // res
1200
+ };
1201
+ // output dir
1202
+ this.outdirs = {
1203
+ behavior: this.currentConfig.outdir?.behavior
1204
+ ? join(this.baseBuildDir, this.currentConfig.outdir.behavior)
1205
+ : path__default.join(this.baseBuildDir, 'dist/dep'),
1206
+ resources: this.currentConfig.outdir?.resources
1207
+ ? join(this.baseBuildDir, this.currentConfig.outdir.resources)
1208
+ : path__default.join(this.baseBuildDir, 'dist/res'),
1209
+ dist: this.currentConfig.outdir?.dist
1210
+ ? join(this.baseBuildDir, this.currentConfig.outdir.dist)
1211
+ : path__default.join(this.baseBuildDir, 'dist-pkg'),
1212
+ };
1213
+ }
1214
+ /**
1215
+ * Copy the various files (behavior/resources) into the corresponding
1216
+ * output directories and determine which modules exist in the project
1217
+ * by inspecting the source directories.
1218
+ */
1219
+ async handlerOtherAddon() {
1220
+ if (!this.srcDirs)
1221
+ throw new Error("[build addon]: can't first can this method");
1222
+ const isHasBp = await FileExsit(this.srcDirs.behavior);
1223
+ if (!isHasBp)
1224
+ throw new Error("[build addon]: can't resolve behavior");
1225
+ // init copy resources
1226
+ const handlerBP = async () => {
1227
+ if (!this.srcDirs || !this.outdirs)
1228
+ throw new Error("[build addon]: can't first can this method");
1229
+ for (const f of await fs.readdir(this.srcDirs.behavior)) {
1230
+ const fType = await this.fileType(path__default.join(this.srcDirs.behavior, f));
1231
+ const includeType = BuildConfig.includes.behavior[f] || BuildConfig.includes.public[f];
1232
+ if (includeType == fType) {
1233
+ await fs.cp(path__default.join(this.srcDirs.behavior, f), path__default.join(this.outdirs.behavior, f), {
1234
+ recursive: true,
1235
+ force: true,
1236
+ });
1237
+ }
1238
+ else if (includeType == 'skip') {
1239
+ continue;
1240
+ }
1241
+ else {
1242
+ throw new Error(`[build addon]: invaild file: ${path__default.join(this.srcDirs.behavior, f)}: type: ${fType}`);
1243
+ }
1244
+ }
1245
+ };
1246
+ const handlerRP = async () => {
1247
+ if (!this.srcDirs || !this.outdirs)
1248
+ throw new Error("[build addon]: can't first can this method");
1249
+ for (const f of await fs.readdir(this.srcDirs.resources)) {
1250
+ const fType = await this.fileType(path__default.join(this.srcDirs.resources, f));
1251
+ const includeType = BuildConfig.includes.resources[f] || BuildConfig.includes.public[f];
1252
+ if (includeType == fType) {
1253
+ await fs.cp(path__default.join(this.srcDirs.resources, f), path__default.join(this.outdirs.resources, f), {
1254
+ recursive: true,
1255
+ force: true,
1256
+ });
1257
+ }
1258
+ else if (includeType == 'skip') {
1259
+ continue;
1260
+ }
1261
+ else {
1262
+ throw new Error(`[build addon]: invaild file: ${path__default.join(this.srcDirs.resources, f)}: type: ${fType}`);
1263
+ }
1264
+ }
1265
+ };
1266
+ const tasks = [];
1267
+ if (await FileExsit(this.srcDirs.behavior)) {
1268
+ this.module = 'behavior';
1269
+ tasks.push(handlerBP());
1270
+ }
1271
+ if (await FileExsit(this.srcDirs.resources)) {
1272
+ if (this.module == 'behavior') {
1273
+ this.module = 'all';
1274
+ }
1275
+ else {
1276
+ this.module = 'resources';
1277
+ }
1278
+ tasks.push(handlerRP());
1279
+ }
1280
+ if (!this.module) {
1281
+ throw new Error("[build addon]: couldn't resolve source code(your behaivor or reources code is not found)");
1282
+ }
1283
+ await Promise.all(tasks);
1284
+ }
1285
+ }
1286
+ function build(cliParam, work) {
1287
+ return new Promise((resolve) => {
1288
+ new Build(cliParam.opts, work, resolve).start();
1289
+ });
1290
+ }
1291
+ function watch(cliParam, work) {
1292
+ return new Promise((resolve, reject) => {
1293
+ try {
1294
+ const build = new Build(cliParam.opts, work, resolve, true);
1295
+ build.start().then(() => {
1296
+ build.watch();
1297
+ showText(`[${chalk.green('mbler')}] ${chalk.bgYellow('watching for file changes...')}`);
1298
+ });
1299
+ }
1300
+ catch (err) {
1301
+ if (err instanceof Error) {
1302
+ reject(`[watcher]: error ${err.stack || err.message}`);
1303
+ }
1304
+ else {
1305
+ reject(err);
1306
+ }
1307
+ }
1308
+ });
1309
+ }
1310
+
1311
+ export { Build, runTSC as McxTsc, build, watch };
1312
+ //# sourceMappingURL=build.esm.js.map