sapdon 3.2.2 → 3.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +245 -121
  2. package/doc/dev/architecture.md +415 -0
  3. package/doc/dev/cli.md +467 -0
  4. package/doc/dev/core.md +717 -0
  5. package/doc/dev/oc.md +582 -0
  6. package/doc/user/api/biome.md +558 -0
  7. package/doc/user/api/block.md +945 -0
  8. package/doc/user/api/entity.md +685 -0
  9. package/doc/user/api/extra.md +231 -0
  10. package/doc/user/api/item.md +896 -0
  11. package/doc/user/api/recipe.md +427 -0
  12. package/doc/user/api/texture.md +181 -0
  13. package/doc/user/config/build-config.md +84 -0
  14. package/doc/user/config/mod-info.md +33 -0
  15. package/doc/user/faq.md +160 -0
  16. package/doc/user/quick-start.md +108 -0
  17. package/doc/user/tutorials/block.md +463 -0
  18. package/doc/user/tutorials/entity.md +356 -0
  19. package/doc/user/tutorials/item.md +449 -0
  20. package/doc/user/tutorials/recipe.md +278 -0
  21. package/package.json +4 -3
  22. package/prod/cli/index.js +1 -1
  23. package/prod/cli/start.js +1 -1458
  24. package/prod/core/index.d.ts +3290 -2150
  25. package/prod/core/index.js +1 -59015
  26. package/prod/core/package.json +7 -0
  27. package/prod/oc/index.d.ts +348 -108
  28. package/prod/oc/index.js +1 -1
  29. package/prod/oc/package.json +7 -0
  30. package/prod/utils/index.d.ts +20 -2
  31. package/prod/utils/index.js +1 -1
  32. package/prod/utils/package.json +7 -0
  33. package/doc/BlockAPI.md +0 -145
  34. package/doc/api.md +0 -128
  35. package/doc/oc/index.md +0 -0
  36. package/doc/sapdon-ts.md +0 -64
  37. package/src/templates/js_sapdon/build.config +0 -23
  38. package/src/templates/js_sapdon/main.mjs +0 -4
  39. package/src/templates/js_sapdon/mod.info +0 -7
  40. package/src/templates/js_sapdon/pack_icon.png +0 -0
  41. package/src/templates/js_sapdon/package.json +0 -20
  42. package/src/templates/js_sapdon/res/animations/animation_item.animation.json +0 -34
  43. package/src/templates/js_sapdon/res/animations/large_item.animation.json +0 -27
  44. package/src/templates/js_sapdon/res/models/blocks/crop.geo.json +0 -48
  45. package/src/templates/js_sapdon/res/models/entity/animation/animation_item.geo.json +0 -26
  46. package/src/templates/js_sapdon/res/models/entity/animation/large_item.geo.json +0 -28
  47. package/src/templates/js_sapdon/res/textures/blocks/none.png +0 -0
  48. package/src/templates/js_sapdon/res/textures/blocks/test_log_oak.png +0 -0
  49. package/src/templates/js_sapdon/res/textures/blocks/test_log_top.png +0 -0
  50. package/src/templates/js_sapdon/res/textures/items/masterball.png +0 -0
  51. package/src/templates/js_sapdon/scripts/custom_components/cropComponent.js +0 -50
  52. package/src/templates/js_sapdon/scripts/custom_components/items/gui_book.js +0 -37
  53. package/src/templates/js_sapdon/scripts/custom_components/registry.js +0 -25
  54. package/src/templates/js_sapdon/scripts/index.js +0 -0
  55. package/src/templates/ts_sapdon/build.config +0 -23
  56. package/src/templates/ts_sapdon/main.ts +0 -11
  57. package/src/templates/ts_sapdon/mod.info +0 -7
  58. package/src/templates/ts_sapdon/pack_icon.png +0 -0
  59. package/src/templates/ts_sapdon/package.json +0 -20
  60. package/src/templates/ts_sapdon/res/models/blocks/crop.geo.json +0 -48
  61. package/src/templates/ts_sapdon/res/textures/blocks/test_log_oak.png +0 -0
  62. package/src/templates/ts_sapdon/res/textures/blocks/test_log_top.png +0 -0
  63. package/src/templates/ts_sapdon/res/textures/items/masterball.png +0 -0
  64. package/src/templates/ts_sapdon/scripts/components/cropComponent.ts +0 -44
  65. package/src/templates/ts_sapdon/scripts/components/items/guiBook.ts +0 -36
  66. package/src/templates/ts_sapdon/scripts/components/registry.ts +0 -24
  67. package/src/templates/ts_sapdon/scripts/index.ts +0 -7
  68. package/src/templates/ts_sapdon/tsconfig.json +0 -117
package/prod/cli/start.js CHANGED
@@ -1,1459 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { program } from 'commander';
3
- import inquirer from 'inquirer';
4
- import path from 'path';
5
- import { fileURLToPath as fileURLToPath$1 } from 'url';
6
- import fs, { readFileSync } from 'fs';
7
- import { randomUUID } from 'crypto';
8
- import { fileURLToPath } from 'node:url';
9
- import cp from 'child_process';
10
- import fs$1 from 'fs/promises';
11
- import http from 'http';
12
- import { rollup } from 'rollup';
13
- import commonjs from '@rollup/plugin-commonjs';
14
- import { nodeResolve } from '@rollup/plugin-node-resolve';
15
- import ts from '@rollup/plugin-typescript';
16
- import { typescriptPaths } from 'rollup-plugin-typescript-paths';
17
- import json from '@rollup/plugin-json';
18
- import 'rollup-plugin-visualizer';
19
- import terser from '@rollup/plugin-terser';
20
- import os from 'os';
21
- import lodash from 'lodash';
22
-
23
- const generateUUID = () => {
24
- return randomUUID();
25
- };
26
- /**
27
- * 同步复制文件
28
- * @param {string} src 源文件路径
29
- * @param {string} dest 目标文件路径
30
- */
31
- //@ts-ignore
32
- function copyFileSync(src, dest) {
33
- try {
34
- fs.copyFileSync(src, dest);
35
- }
36
- catch (err) {
37
- console.error("文件复制失败:", err);
38
- }
39
- }
40
- //检查路径
41
- //@ts-ignore
42
- const pathNotExist = filePath => {
43
- return !fs.existsSync(filePath);
44
- };
45
- //读取文件
46
- //@ts-ignore
47
- const readFile = filePath => {
48
- try {
49
- return fs.readFileSync(filePath, "utf8");
50
- }
51
- catch (error) {
52
- console.log(error);
53
- }
54
- return null;
55
- };
56
- /**
57
- * 保存文件
58
- * @param {string} filePath 绝对路径
59
- * @param {string} data 数据
60
- */
61
- //@ts-ignore
62
- const saveFile = (filePath, data) => {
63
- // 确保目录存在
64
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
65
- // 创建文件并写入内容
66
- fs.writeFile(filePath, data, err => {
67
- if (err) {
68
- return console.error(err);
69
- }
70
- });
71
- };
72
- //@ts-ignore
73
- const copyFolder = (sourcePath, destinationPath) => {
74
- // 确保目录存在
75
- fs.mkdirSync(path.dirname(destinationPath), { recursive: true });
76
- // 检查源路径是否存在
77
- if (!fs.existsSync(sourcePath)) {
78
- console.log(`Source path ${sourcePath} does not exist.`);
79
- return;
80
- }
81
- // 检查目标路径是否存在,如果不存在则创建它
82
- if (!fs.existsSync(destinationPath)) {
83
- fs.mkdirSync(destinationPath);
84
- }
85
- // 获取源路径下的所有文件和文件夹
86
- const files = fs.readdirSync(sourcePath);
87
- // 遍历文件和文件夹
88
- files.forEach(file => {
89
- const sourceFile = path.join(sourcePath, file);
90
- const destinationFile = path.join(destinationPath, file);
91
- // 判断是文件还是文件夹
92
- if (fs.lstatSync(sourceFile).isDirectory()) {
93
- // 如果是文件夹,则递归调用copyFolder函数
94
- copyFolder(sourceFile, destinationFile);
95
- }
96
- else {
97
- // 如果是文件,则直接复制到目标路径
98
- fs.copyFileSync(sourceFile, destinationFile);
99
- }
100
- });
101
- };
102
- //@ts-ignore
103
- function dirname(importMeta) {
104
- const __filename = fileURLToPath(importMeta.url);
105
- const __dirname = path.dirname(__filename);
106
- return __dirname;
107
- }
108
- function parseJsonWithComments(jsonStr) {
109
- return JSON.parse(String(jsonStr).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1"));
110
- }
111
-
112
- const caches = new Map();
113
- function cacheSync(uri, setter) {
114
- let value = caches.get(uri);
115
- if (value) {
116
- return value;
117
- }
118
- value = setter(uri);
119
- caches.set(uri, value);
120
- return value;
121
- }
122
-
123
- function getBuildConfig() {
124
- const pwd = getProjectPath();
125
- const configFile = path.join(pwd, 'build.config');
126
- if (!fs.existsSync(configFile)) {
127
- throw new Error('未找到项目配置文件,请先初始化项目');
128
- }
129
- return cacheSync(configFile, file => parseBuildConfig(file));
130
- }
131
- function transferV1ToV2({ defaultConfig, resources, scripts }) {
132
- const buildConfig = {
133
- formatVersion: 2,
134
- buildOptions: {
135
- useHMR: true,
136
- buildMode: 'development',
137
- buildEntry: defaultConfig.buildEntry,
138
- scriptEntry: defaultConfig.scriptEntry,
139
- scriptOutput: defaultConfig.scriptEntry.replace('.ts', '.js'),
140
- useJs: scripts[0].type === 'ts' ? false : true,
141
- buildDir: defaultConfig.buildDir,
142
- dependencies: defaultConfig.dependencies,
143
- resource: {
144
- path: resources[0].path,
145
- resourceHints: true
146
- }
147
- },
148
- versionType: 'release'
149
- };
150
- return buildConfig;
151
- }
152
- function parseBuildConfig(file) {
153
- const obj = parseJsonWithComments(fs.readFileSync(file));
154
- if (obj.formatVersion === 2) {
155
- return obj;
156
- }
157
- const upgratedConfig = transferV1ToV2(obj);
158
- fs.writeFileSync(file, JSON.stringify(upgratedConfig, null, 2));
159
- return upgratedConfig;
160
- }
161
-
162
- // 获取当前文件的路径
163
- const __filename$2 = fileURLToPath$1(import.meta.url);
164
- // 获取当前文件的目录
165
- const __dirname$1 = path.dirname(__filename$2);
166
- const templateMapping = {
167
- js: 'js_sapdon',
168
- ts: 'ts_sapdon'
169
- };
170
- const initProject = (projectPath, data) => {
171
- console.log(1, data);
172
- //检查项目目录是否存在
173
- //如果不存在则创建项目目录
174
- //从模板下载项目文件
175
- //根据用户输入的项目信息生成项目配置文件
176
- //根据用户选择是否生成脚本文件,生成脚本文件
177
- if (!pathNotExist(projectPath)) {
178
- console.log("项目名称已存在,创建项目目录失败");
179
- return;
180
- }
181
- //模版目录
182
- const templateDir = path.join(__dirname$1, `../../src/templates/${templateMapping[data.language || 'js']}`);
183
- copyFolder(templateDir, projectPath);
184
- //生成模组介绍文件
185
- saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
186
- //执行npm i
187
- cp.execSync('npm i', { cwd: projectPath, stdio: 'inherit' });
188
- };
189
- const initNPMProject = (projectPath, data) => {
190
- //检查项目文件是否存在
191
- //如果不存在则创建项目
192
- //从模板下载项目文件
193
- //根据用户输入的项目信息生成项目配置文件
194
- //根据用户选择是否生成脚本文件,生成脚本文件
195
- if (!pathNotExist(path.join(projectPath, "mod.info")) || !pathNotExist(path.join(projectPath, "main.mjs")) || !pathNotExist(path.join(projectPath, "scripts")) || !pathNotExist(path.join(projectPath, "build.config"))) {
196
- console.log("项目已存在...");
197
- return;
198
- }
199
- //模版目录
200
- const templateDir = path.join(__dirname$1, "../templates/js_sapdon");
201
- copyFolder(templateDir, projectPath);
202
- //生成模组介绍文件
203
- saveFile(path.join(projectPath, "mod.info"), JSON.stringify(data, null, 2));
204
- };
205
- // 读取package.json文件并提取信息
206
- const readPackageJson = (dir) => {
207
- const packageJsonPath = path.join(dir, 'package.json');
208
- if (fs.existsSync(packageJsonPath)) {
209
- try {
210
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
211
- return {
212
- name: path.basename(dir),
213
- description: packageJson.description || "A new sapdon project",
214
- author: packageJson.author || "Sapdon",
215
- version: packageJson.version || "1.0.0"
216
- };
217
- }
218
- catch (error) {
219
- console.error("读取package.json文件时出错:", error);
220
- return null;
221
- }
222
- }
223
- else {
224
- return null;
225
- }
226
- };
227
- const globalObject = {};
228
- function getProjectPath() {
229
- const projectPath = globalObject.projectPath ?? process.cwd();
230
- if (!fs.existsSync(path.join(projectPath, "build.config"))) {
231
- throw new Error("无效的项目路径");
232
- }
233
- return projectPath;
234
- }
235
- function getProjectName() {
236
- return cacheSync('projectName', () => path.basename(getProjectPath()));
237
- }
238
- function getBuildDirBp() {
239
- const { buildDir } = getBuildConfig().buildOptions;
240
- const name = getProjectName();
241
- return path.join(getProjectPath(), buildDir, name + '_bp');
242
- }
243
-
244
- /**
245
- * 递归遍历目录,收集所有 PNG 文件的路径
246
- * @param {string} directory - 要遍历的目录
247
- * @param {string} basePath - 基础路径(用于计算相对路径)
248
- * @param {string} prefix - 路径前缀(如 "textures/items/")
249
- * @returns {Promise<Object>} - 返回一个对象,键为文件名,值为相对路径(不带 .png 后缀)
250
- */
251
- const traverseDirectory = async (directory, basePath, prefix = "") => {
252
- const texturesSet = {};
253
- const files = await fs$1.readdir(directory);
254
- for (const file of files) {
255
- const filePath = path.join(directory, file);
256
- const fileStats = await fs$1.stat(filePath);
257
- if (fileStats.isDirectory()) {
258
- // 如果是目录,递归遍历
259
- const subDirectoryTextures = await traverseDirectory(filePath, basePath, prefix);
260
- Object.assign(texturesSet, subDirectoryTextures);
261
- }
262
- else if (file.endsWith(".png")) {
263
- // 如果是 PNG 文件,提取文件名并生成 texture_data
264
- const fileName = path.basename(file, ".png"); // 去掉 .png 后缀
265
- const relativePath = path.relative(basePath, filePath).replace(/\.png$/, ""); // 去掉 .png 后缀
266
- const normalizedPath = `${prefix}${relativePath.replace(/\\/g, "/")}`; // 确保路径使用正斜杠
267
- texturesSet[fileName] = {
268
- textures: normalizedPath,
269
- };
270
- }
271
- }
272
- return texturesSet;
273
- };
274
- /**
275
- * 生成 JSON 文件
276
- * @param {string} outputPath - 输出的 JSON 文件路径
277
- * @param {Object} jsonData - 要写入的 JSON 数据
278
- * @param {string} successMessage - 成功时的日志消息
279
- */
280
- const generateJsonFile = async (outputPath, jsonData, successMessage) => {
281
- try {
282
- const jsonString = JSON.stringify(jsonData, null, 2);
283
- await fs$1.writeFile(outputPath, jsonString);
284
- console.log(successMessage);
285
- }
286
- catch (err) {
287
- console.error("Error writing JSON file:", err);
288
- }
289
- };
290
- /**
291
- * 生成 block_texture.json 文件
292
- * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
293
- * @param {string} outputPath - 输出的 JSON 文件路径
294
- * @param {string} projectName - 项目名称
295
- */
296
- async function generateBlockTextureJson(itemTexturesPath, outputPath, projectName, userTerrainTextures) {
297
- try {
298
- // 递归遍历目录,获取所有 PNG 文件的路径
299
- const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath, "textures/blocks/");
300
- // 合并用户自定义的texture_data
301
- if (userTerrainTextures) {
302
- Object.assign(itemTexturesSet, userTerrainTextures);
303
- }
304
- // 生成 JSON 数据
305
- const jsonData = {
306
- texture_name: "atlas.terrain",
307
- resource_pack_name: projectName,
308
- padding: 8,
309
- num_mip_levels: 4,
310
- texture_data: itemTexturesSet,
311
- };
312
- // 写入文件
313
- await generateJsonFile(outputPath, jsonData, "Block texture JSON file generated successfully.");
314
- }
315
- catch (err) {
316
- console.error("Error generating block texture JSON:", err);
317
- }
318
- }
319
- /**
320
- * 生成 item_texture.json 文件
321
- * @param {string} itemTexturesPath - 包含 PNG 文件的根目录
322
- * @param {string} outputPath - 输出的 JSON 文件路径
323
- */
324
- async function generateItemTextureJson(itemTexturesPath, outputPath, projectName, userItemTextures) {
325
- try {
326
- // 递归遍历目录,获取所有 PNG 文件的路径
327
- const itemTexturesSet = await traverseDirectory(itemTexturesPath, itemTexturesPath, "textures/items/");
328
- // 合并用户自定义的texture_data
329
- if (userItemTextures) {
330
- Object.assign(itemTexturesSet, userItemTextures);
331
- }
332
- // 生成 JSON 数据
333
- const jsonData = {
334
- resource_pack_name: projectName,
335
- texture_name: "atlas.items",
336
- texture_data: itemTexturesSet,
337
- };
338
- // 写入文件
339
- await generateJsonFile(outputPath, jsonData, "Item texture JSON file generated successfully.");
340
- }
341
- catch (err) {
342
- console.error("Error generating item texture JSON:", err);
343
- }
344
- }
345
-
346
- class ItemTextureManager {
347
- static item_texture_sets = new Map();
348
- static getItemTextureSet() {
349
- return this.item_texture_sets;
350
- }
351
- static getItemTextures() {
352
- return Object.fromEntries(this.item_texture_sets);
353
- }
354
- static registerTextureData(texture_name, texture_data) {
355
- this.item_texture_sets.set(texture_name, texture_data);
356
- }
357
- static registerTexture(texture_name, texture_path) {
358
- this.registerTextureData(texture_name, { textures: texture_path });
359
- }
360
- }
361
- class terrainTextureManager {
362
- static terrain_texture_sets = new Map();
363
- static getTerrainTextureSet() {
364
- return this.terrain_texture_sets;
365
- }
366
- static getTerrainTextures() {
367
- return Object.fromEntries(this.terrain_texture_sets);
368
- }
369
- static registerTextureData(texture_name, texture_data) {
370
- this.terrain_texture_sets.set(texture_name, texture_data);
371
- }
372
- static registerTexture(texture_name, texture_path) {
373
- this.registerTextureData(texture_name, { textures: texture_path });
374
- }
375
- }
376
- const FlipbookTextures = {
377
- flipbook_textures: [],
378
- registerFlipbookTexture(atlas_tile, texture, ticks_per_frame, options = {}) {
379
- const flipbook_texture = { "atlas_tile": atlas_tile, "flipbook_texture": texture, ticks_per_frame };
380
- Object.assign(flipbook_texture, options);
381
- this.flipbook_textures.push(flipbook_texture);
382
- }
383
- };
384
-
385
- if (!Symbol.metadata) {
386
- //@ts-ignore
387
- Symbol.metadata = Symbol('[[metadata]]');
388
- }
389
- function getMetadata(target) {
390
- return target?.[Symbol.metadata];
391
- }
392
-
393
- // 因为无法判断其他代码实现的接口是否真的是RawType,所以用Symbol来标记
394
- // 只要不export,其他代码就无法访问这个Symbol, 确保了唯一性
395
- const IS_RAW_SYMBOL = Symbol('isRawJSON');
396
- function isRawJSON(v) {
397
- return v?.[IS_RAW_SYMBOL] === true;
398
- }
399
-
400
- const rawTypes = [
401
- 'boolean', 'number'
402
- ];
403
- const transferableTypes = [
404
- 'string', 'undefined'
405
- ];
406
- function jsonEncoderReplacer(_, v) {
407
- const typeOf = typeof v;
408
- if (typeOf === null) {
409
- return null;
410
- }
411
- if (transferableTypes.includes(typeOf)) {
412
- return v;
413
- }
414
- if (rawTypes.includes(typeOf)) {
415
- return JSON.rawJSON(v);
416
- }
417
- if (typeOf === 'object') {
418
- if (JSON.isRawJSON(v)) {
419
- return v;
420
- }
421
- if (isRawJSON(v)) {
422
- // 字符串再包装一遍
423
- return JSON.rawJSON(v.rawJSON);
424
- }
425
- return v;
426
- }
427
- if (typeOf === 'bigint') {
428
- return JSON.rawJSON(v.toString());
429
- }
430
- throw new Error('Unexpected value');
431
- }
432
- const defaultSerializer = instance => {
433
- return structuredClone(instance);
434
- };
435
- const serializerSymbol = Symbol('serializer');
436
- const serializerMapping = new WeakMap();
437
- function serialize(inst) {
438
- const ctor = Reflect.getPrototypeOf(inst)?.constructor;
439
- if (!ctor) {
440
- throw new Error('Cannot serialize an instance of an anonymous class');
441
- }
442
- const serializer = getMetadata(ctor)?.[serializerSymbol]
443
- ?? serializerMapping.get(ctor)
444
- ?? defaultSerializer;
445
- return serializer.call(inst, inst);
446
- }
447
- const jsonEncodeDecoder = {
448
- encode(value) {
449
- return JSON.stringify(value, jsonEncoderReplacer);
450
- },
451
- decode: JSON.parse
452
- };
453
- function encode(value, encodeDecoder = jsonEncodeDecoder) {
454
- return encodeDecoder.encode(value);
455
- }
456
- function decode(value, encodeDecoder = jsonEncodeDecoder) {
457
- return encodeDecoder.decode(value);
458
- }
459
-
460
- const devServerConfig = {
461
- port: 49037,
462
- };
463
-
464
- const { port: port$1 } = devServerConfig;
465
- async function cliRequest(path, ...params) {
466
- try {
467
- await fetch(`http://localhost:${port$1}/${path}`, {
468
- method: 'POST',
469
- headers: {
470
- 'Content-Type': 'application/json'
471
- },
472
- body: encode(params)
473
- });
474
- }
475
- catch (error) {
476
- console.error(error);
477
- console.error('尝试在构建脚本中使用 server.startDevServer() 启动开发服务器');
478
- }
479
- }
480
-
481
- const { port } = devServerConfig;
482
- class DevelopmentServer {
483
- cliServerHandlers = new Map();
484
- listening = false;
485
- isListening() {
486
- return this.listening;
487
- }
488
- bootstrap() {
489
- this.listening = true;
490
- const svr = http.createServer(async (req, res) => {
491
- const handler = this.cliServerHandlers.get((req.url ?? '/').slice(1));
492
- if (handler) {
493
- try {
494
- const { promise, resolve, reject } = Promise.withResolvers();
495
- let buf = Buffer.alloc(0);
496
- req.on('data', chunk => buf = Buffer.concat([buf, chunk]));
497
- req.on('end', () => {
498
- try {
499
- resolve(decode(buf));
500
- }
501
- catch (error) {
502
- reject(error);
503
- }
504
- });
505
- await handler(...await promise);
506
- }
507
- catch (error) {
508
- console.error(error);
509
- res.writeHead(500);
510
- res.end();
511
- return;
512
- }
513
- res.writeHead(200);
514
- res.end();
515
- }
516
- else {
517
- res.writeHead(404);
518
- res.end();
519
- }
520
- }).listen(port, () => console.log(`Dev Server listening on port ${port}`));
521
- svr.on('error', () => this.listening = false);
522
- return svr;
523
- }
524
- handle(url, handler) {
525
- this.cliServerHandlers.set(url, handler);
526
- }
527
- getHandler(url) {
528
- return this.cliServerHandlers.get(url);
529
- }
530
- interceptHandler(url, interceptor) {
531
- const currentHandler = this.getHandler(url) ?? Function.prototype;
532
- const newHandler = interceptor(currentHandler);
533
- this.cliServerHandlers.set(url, newHandler);
534
- return newHandler;
535
- }
536
- }
537
- const server = new DevelopmentServer();
538
-
539
- class UISystemRegistry {
540
- static #ui_system_map = {};
541
- static #ui_def_list = [];
542
- // 注册 UISystem
543
- static registerUISystem(ui_system) {
544
- const ui_system_path = ui_system.path + ui_system.name + ".json";
545
- this.#ui_system_map[ui_system_path] = ui_system;
546
- }
547
- // 添加外部 UI 定义
548
- static addOuterUIdefs(ui_defs) {
549
- if (!Array.isArray(ui_defs)) {
550
- throw new Error("参数必须是一个数组");
551
- }
552
- this.#ui_def_list.concat(ui_defs);
553
- }
554
- static submit() {
555
- cliRequest("register-ui/def", this.#ui_def_list);
556
- cliRequest("register-ui/system", this.#ui_system_map);
557
- }
558
- }
559
- class UISystemRegistryServer {
560
- // 私有静态字段
561
- static #ui_system_map = {};
562
- static #ui_def_list = [];
563
- // 获取所有注册的 UISystem
564
- static getUISystemList() {
565
- return Object.values(this.#ui_system_map);
566
- }
567
- // 获取 UI 定义列表(剔除 "ui/server_form")
568
- static getUIdefList() {
569
- const combinedList = this.#ui_def_list.concat(Object.keys(this.#ui_system_map));
570
- return combinedList.filter(item => item !== "ui/server_form");
571
- }
572
- static startServer() {
573
- server.handle('register-ui/system', systems => {
574
- this.#ui_system_map = systems;
575
- });
576
- server.handle('register-ui/def', defs => {
577
- this.#ui_def_list = defs;
578
- });
579
- }
580
- }
581
-
582
- async function handleRemoteLogger({ level, message, timeStamp, stack }) {
583
- console[level](message, stack, `\nat ${new Date(timeStamp).toLocaleString()}`);
584
- }
585
-
586
- const clientRegistryData = [];
587
- /**
588
- * Client
589
- */
590
- class GRegistry {
591
- /**
592
- * 生成注册器
593
- * @param {string} name 文件名字
594
- * @param {string} root 根目录,如 "behavior"、"resource" 等
595
- * @param {string} path 数据的路径,如 "blocks/"、"items/"、"recipes/" 等
596
- * @param {string | object} data 实例 必须包含 toJson 方法
597
- */
598
- static register(name, root, path, data) {
599
- data = data === 'string'
600
- ? JSON.parse(data)
601
- : serialize(data);
602
- clientRegistryData.push({ name, root, path, data });
603
- }
604
- static submit() {
605
- cliRequest('submitGregistry', clientRegistryData);
606
- }
607
- }
608
- /**
609
- * Server
610
- */
611
- class GRegistryServer {
612
- static dataList = [];
613
- static getDataList() {
614
- return [...GRegistryServer.dataList];
615
- }
616
- static startServer() {
617
- server.handle('submitGregistry', (data) => {
618
- //@ts-ignore
619
- // console.log(data.map(item => item.data.description))
620
- this.dataList = data;
621
- });
622
- server.handle('remote-logger', handleRemoteLogger);
623
- }
624
- }
625
- var registry;
626
- (function (registry) {
627
- function submit() {
628
- GRegistry.submit();
629
- UISystemRegistry.submit();
630
- cliRequest('submit', {});
631
- }
632
- registry.submit = submit;
633
- })(registry || (registry = {}));
634
-
635
- /**
636
- * 处理 blocks.json 数据
637
- * @param {Object} data blocks.json 数据
638
- * @returns {Object} 处理后的 blocks 数据
639
- */
640
- const processBlocksData = (data) => {
641
- const textures_arr = data.textures;
642
- // 检查 textures 数组长度
643
- if (textures_arr.length !== 6) {
644
- console.warn(`blocks.json 的 textures 数组长度不为 6,实际长度: ${textures_arr.length}`);
645
- return {};
646
- }
647
- // 构建 blocks 数据
648
- const blocks = {};
649
- blocks[data.identifier] = {
650
- textures: {
651
- up: textures_arr[0],
652
- down: textures_arr[1],
653
- east: textures_arr[2],
654
- west: textures_arr[3],
655
- south: textures_arr[4],
656
- north: textures_arr[5]
657
- }
658
- };
659
- return blocks;
660
- };
661
- /**
662
- * Server
663
- * 加载并执行模组文件
664
- * @param {string} modPath 模组文件路径
665
- * @param {string} buildPath 构建目录路径
666
- * @param {string} projectName 项目名
667
- */
668
- const generateAddon = async (modPath, buildPath, projectName) => {
669
- try {
670
- const buildBehDirPath = path.join(buildPath, `${projectName}_BP`);
671
- const buildResDirPath = path.join(buildPath, `${projectName}_RP`);
672
- const resDir = (...name) => path.join(buildResDirPath, ...name);
673
- // 初始化 blocks.json 数据
674
- const blocksJsonPath = path.join(buildBehDirPath, "blocks.json");
675
- const blocks = { "format_version": "1.20.20" };
676
- //生成item_texture.json
677
- const item_texture_dir = resDir("textures/items");
678
- const item_texture_json_path = resDir("textures/item_texture.json");
679
- generateItemTextureJson(item_texture_dir, item_texture_json_path, projectName, ItemTextureManager.getItemTextures());
680
- //生成terrain_texture.json
681
- const terrain_texture_dir = resDir("textures/blocks");
682
- const terrain_texture_json_path = resDir("textures/terrain_texture.json");
683
- generateBlockTextureJson(terrain_texture_dir, terrain_texture_json_path, projectName, terrainTextureManager.getTerrainTextures());
684
- //生成flipbook_textures.json
685
- const flipbook_textures_path = resDir("textures/flipbook_textures.json");
686
- saveFile(flipbook_textures_path, JSON.stringify(FlipbookTextures.flipbook_textures, null, 2));
687
- //_ui_defs.json
688
- const ui_def = UISystemRegistryServer.getUIdefList();
689
- saveFile(resDir("ui/_ui_defs.json"), JSON.stringify({ "ui_defs": ui_def }, null, 2));
690
- UISystemRegistryServer.getUISystemList().forEach((ui_system) => {
691
- if (ui_system.path) {
692
- saveFile(resDir(ui_system.path, `${ui_system.name}.json`), JSON.stringify(ui_system, null, 2));
693
- }
694
- });
695
- // 从全局注册表中获取数据
696
- const dataList = GRegistryServer.getDataList();
697
- // console.log("dataList:", dataList)
698
- // 遍历数据并保存到相应的目录
699
- dataList.forEach(({ name, root, path: dataPath, data }) => {
700
- // 处理 blocks.json 数据
701
- if (dataPath === "blocks/") {
702
- const processedBlocks = processBlocksData(data);
703
- Object.assign(blocks, processedBlocks);
704
- }
705
- // 根据数据类型确定根目录
706
- const rootPath = root === "behavior" ? `${projectName}_BP` : `${projectName}_RP`;
707
- const buildRootPath = path.join(buildPath, rootPath);
708
- // 拼接文件路径
709
- const filePath = path.join(buildRootPath, dataPath, `${name}.json`);
710
- // 保存文件
711
- saveFile(filePath, JSON.stringify(data, null, 2));
712
- });
713
- // 保存 blocks.json
714
- console.log("保存 blocks.json 文件:", blocksJsonPath);
715
- saveFile(blocksJsonPath, JSON.stringify(blocks, null, 2));
716
- console.log(`已加载并执行 ${modPath} 文件!`);
717
- }
718
- catch (err) {
719
- console.error(`加载或执行 ${modPath} 失败:${err.message}`);
720
- console.error(err.stack); // 打印堆栈跟踪以便调试
721
- }
722
- };
723
-
724
- // 定义语义化版本号类
725
- // 定义头部信息类
726
- class AddonManifestHeader {
727
- constructor(name, description, version, uuid, options = {}) {
728
- this.name = name;
729
- this.description = description;
730
- this.version = version;
731
- this.uuid = uuid;
732
- this.allow_random_seed = options.allow_random_seed;
733
- this.lock_template_options = options.lock_template_options;
734
- this.pack_scope = options.pack_scope;
735
- this.base_game_version = options.base_game_version;
736
- this.min_engine_version = options.min_engine_version;
737
- }
738
- }
739
- // 定义模块信息类
740
- class AddonManifestModule {
741
- constructor(description, moduleType, uuid, version) {
742
- this.description = description;
743
- this.type = moduleType;
744
- this.uuid = uuid;
745
- this.version = version;
746
- }
747
- }
748
- // 定义元数据信息类
749
- class AddonManifestMetadata {
750
- constructor(authors, license, generatedWith, productType, url) {
751
- this.authors = authors;
752
- this.license = license;
753
- this.generated_with = generatedWith;
754
- this.product_type = productType;
755
- this.url = url;
756
- }
757
- }
758
- // 定义清单文件类
759
- class AddonManifest {
760
- constructor(formatVersion, header, modules, dependencies, capabilities = null, metadata = null) {
761
- this.format_version = formatVersion;
762
- this.header = header;
763
- this.modules = modules;
764
- this.dependencies = dependencies;
765
- if (capabilities != null)
766
- this.capabilities = capabilities;
767
- if (metadata != null)
768
- this.metadata = metadata;
769
- }
770
- }
771
-
772
- const MC_INSTALL_PATH = {
773
- MAIN: 'AppData/Local/Packages/Microsoft.MinecraftUWP_8wekyb3d8bbwe/LocalState/games/com.mojang/',
774
- BETA: 'AppData/Local/Packages/Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe/LocalState/games/com.mojang/'
775
- };
776
- function mojangPath() {
777
- return cacheSync('McInstallPath.Main', () => path.join(os.homedir(), MC_INSTALL_PATH.MAIN));
778
- }
779
- function betaPath() {
780
- return cacheSync('McInstallPath.Beta', () => path.join(os.homedir(), MC_INSTALL_PATH.BETA));
781
- }
782
- function getGamePath() {
783
- return getBuildConfig().versionType === 'beta' ? betaPath() : mojangPath();
784
- }
785
-
786
- var name = "sapdon";
787
- var version = "3.2.2";
788
- var scripts = {
789
- build: "node scripts/build.cjs",
790
- pub: "npm run build && npm publish"
791
- };
792
- var keywords = [
793
- "bedrock",
794
- "tools",
795
- "addon"
796
- ];
797
- var author = "Meteage";
798
- var license = "ISC";
799
- var type = "module";
800
- var bin = {
801
- sapdon: "prod/cli/start.js"
802
- };
803
- var description = "Sapdon is a Node.js toolkit designed for building Bedrock Edition Minecraft addon packs.";
804
- var devDependencies = {
805
- "@minecraft/server": "^2.0.0-beta.1.21.80-preview.20",
806
- "@minecraft/server-ui": "^1.3.0",
807
- "@types/lodash": "^4.17.16",
808
- "@types/node": "^22.14.0",
809
- "tsc-alias": "^1.8.13"
810
- };
811
- var dependencies = {
812
- "@rollup/plugin-commonjs": "^28.0.2",
813
- "@rollup/plugin-json": "^6.1.0",
814
- "@rollup/plugin-node-resolve": "^16.0.0",
815
- "@rollup/plugin-terser": "^0.4.4",
816
- "@rollup/plugin-typescript": "^12.1.2",
817
- chalk: "^5.4.1",
818
- commander: "^13.0.0",
819
- "download-git-repo": "^3.0.2",
820
- inquirer: "^12.3.1",
821
- lodash: "^4.17.21",
822
- ora: "^8.1.1",
823
- rollup: "^4.39.0",
824
- "rollup-plugin-dts": "^6.2.1",
825
- "rollup-plugin-typescript-paths": "^1.5.0",
826
- "rollup-plugin-visualizer": "^5.14.0",
827
- "tsconfig-paths": "^4.2.0",
828
- tslib: "^2.8.1",
829
- typescript: "^5.8.2"
830
- };
831
- var files = [
832
- "prod/**/*",
833
- "doc/**/*",
834
- "src/templates/**/*"
835
- ];
836
- var packageJson = {
837
- name: name,
838
- version: version,
839
- scripts: scripts,
840
- keywords: keywords,
841
- author: author,
842
- license: license,
843
- type: type,
844
- bin: bin,
845
- description: description,
846
- devDependencies: devDependencies,
847
- dependencies: dependencies,
848
- files: files
849
- };
850
-
851
- function getPackageJson() {
852
- return cacheSync(path.join(dirname(import.meta), '../../../package.json'), () => packageJson);
853
- }
854
-
855
- async function syncDevFilesServer(projectPath, projectName) {
856
- const buildConfig = JSON.parse(readFileSync(path.join(projectPath, "build.config")));
857
- const buildDir = path.join(projectPath, buildConfig.buildOptions.buildDir);
858
- const buildBehDirPath = path.join(buildDir, `${projectName}_BP`);
859
- const buildResDirPath = path.join(buildDir, `${projectName}_RP`);
860
- fs.cpSync(buildBehDirPath, path.join(getGamePath(), "development_behavior_packs/", `${projectName}_BP/`), { recursive: true, force: true });
861
- fs.cpSync(buildResDirPath, path.join(getGamePath(), "development_resource_packs/", `${projectName}_RP/`), { recursive: true, force: true });
862
- }
863
- async function writeLib(projectPath) {
864
- const projectModules = path.join(projectPath, "node_modules");
865
- const rootDir = path.join(dirname(import.meta), '../');
866
- const corePath = path.join(rootDir, 'core');
867
- const cliPath = path.join(rootDir, 'cli');
868
- const ocPath = path.join(rootDir, 'oc');
869
- const targetCorePath = path.join(projectModules, '@sapdon/core');
870
- const targetCliPath = path.join(projectModules, '@sapdon/cli');
871
- const targetOcPath = path.join(projectModules, '@sapdon/oc');
872
- const packageJson = getPackageJson();
873
- fs.cpSync(corePath, targetCorePath, { recursive: true, force: true });
874
- fs.cpSync(cliPath, targetCliPath, { recursive: true, force: true });
875
- fs.cpSync(ocPath, targetOcPath, { recursive: true, force: true });
876
- fs.writeFileSync(path.join(targetCorePath, 'package.json'), JSON.stringify({
877
- name: '@sapdon/core',
878
- main: 'index.js',
879
- version: packageJson.version,
880
- }));
881
- fs.writeFileSync(path.join(targetCliPath, 'package.json'), JSON.stringify({
882
- name: '@sapdon/cli',
883
- main: 'index.js',
884
- version: packageJson.version,
885
- }));
886
- fs.writeFileSync(path.join(targetOcPath, 'package.json'), JSON.stringify({
887
- name: '@sapdon/oc',
888
- main: 'index.js',
889
- version: packageJson.version,
890
- }));
891
- }
892
-
893
- function startDevServer() {
894
- if (server.isListening()) {
895
- return;
896
- }
897
- server.bootstrap();
898
- }
899
-
900
- // 获取当前文件的目录路径
901
- const __filename$1 = fileURLToPath$1(import.meta.url);
902
- path.dirname(__filename$1);
903
- //读取配置文件
904
- // const pathConfig = JSON.parse(readFile(path.join(__dirname, "./build.config")))
905
- const rollupIgnores = [
906
- 'rollup',
907
- 'typescript',
908
- '@sapdon/core',
909
- '@sapdon/cli',
910
- '@minecraft',
911
- ];
912
- //脚本打包器
913
- const scriptBundler = {
914
- js: async (source, target, sourcemap) => {
915
- const buildConfig = getBuildConfig();
916
- try {
917
- const bundle = await rollup({
918
- input: source,
919
- plugins: [
920
- nodeResolve({
921
- preferBuiltins: true
922
- }),
923
- //@ts-ignore
924
- commonjs(),
925
- //@ts-ignore
926
- json(),
927
- // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
928
- ...(buildConfig.buildOptions.buildMode === 'development' ? [] : [
929
- terser(),
930
- ]),
931
- ],
932
- external(name) {
933
- for (const candidate of rollupIgnores) {
934
- if (name.includes(candidate)) {
935
- return true;
936
- }
937
- }
938
- return false;
939
- }
940
- });
941
- await bundle.write({
942
- file: target,
943
- format: 'esm',
944
- sourcemap,
945
- });
946
- bundle.close();
947
- }
948
- catch (e) {
949
- console.error(e);
950
- }
951
- },
952
- //ts先通过rollup处理后再复制
953
- ts: async (source, target, sourcemap) => {
954
- const projectPath = getProjectPath();
955
- const buildConfig = getBuildConfig();
956
- try {
957
- const bundle = await rollup({
958
- input: source,
959
- plugins: [
960
- typescriptPaths(),
961
- nodeResolve({
962
- preferBuiltins: true
963
- }),
964
- //@ts-ignore
965
- ts({
966
- tsconfig: path.join(projectPath, 'tsconfig.json'),
967
- }),
968
- //@ts-ignore
969
- commonjs(),
970
- //@ts-ignore
971
- json(),
972
- // visualizer({ open: true }), //可视化分析, 打包出问题取消注释这一行
973
- ...(buildConfig.buildOptions.buildMode === 'development' ? [] : [
974
- terser(),
975
- ]),
976
- ],
977
- external(name) {
978
- for (const candidate of rollupIgnores) {
979
- if (name.includes(candidate)) {
980
- return true;
981
- }
982
- }
983
- return false;
984
- }
985
- });
986
- await bundle.write({
987
- file: target,
988
- format: 'esm',
989
- sourcemap,
990
- });
991
- bundle.close();
992
- }
993
- catch (e) {
994
- console.error(e);
995
- }
996
- },
997
- any: async (a, b) => {
998
- const buildConfig = getBuildConfig();
999
- buildConfig.buildOptions.useJs
1000
- ? await scriptBundler.js(a, b)
1001
- : await scriptBundler.ts(a, b);
1002
- },
1003
- };
1004
- async function bundleScripts(useJs = false) {
1005
- const elementType = useJs ? 'js' : 'ts';
1006
- const projectPath = getProjectPath();
1007
- const buildConfig = getBuildConfig();
1008
- const { scriptEntry, scriptOutput, buildMode } = buildConfig.buildOptions;
1009
- scriptBundler[elementType](path.join(projectPath, scriptEntry), path.join(getBuildDirBp(), scriptOutput), buildMode === 'development' ? true : false);
1010
- }
1011
- async function runOnChild(targetFilePath) {
1012
- const { promise, resolve } = Promise.withResolvers();
1013
- cp.fork(targetFilePath, { stdio: 'inherit' }).on('exit', resolve);
1014
- return promise;
1015
- }
1016
- async function runScript(src) {
1017
- const randomName = '.' + crypto.randomUUID() + '.js';
1018
- const targetFilePath = path.join(path.dirname(src), '.tmp', randomName);
1019
- await scriptBundler.any(src, targetFilePath);
1020
- try {
1021
- await runOnChild(targetFilePath);
1022
- }
1023
- catch (e) {
1024
- console.error(e);
1025
- }
1026
- finally {
1027
- fs.rmSync(targetFilePath, { force: true });
1028
- }
1029
- return;
1030
- }
1031
- function projectCanBuild(projectPath) {
1032
- console.log("开始构建项目");
1033
- console.log("项目路径:" + projectPath);
1034
- //检查项目是否存在
1035
- if (pathNotExist(projectPath)) {
1036
- console.log("项目不存在");
1037
- return false;
1038
- }
1039
- //检查项目是否有build.config文件
1040
- if (pathNotExist(path.join(projectPath, "build.config"))) {
1041
- console.log("项目没有build.config文件");
1042
- return false;
1043
- }
1044
- return true;
1045
- }
1046
- //构建项目
1047
- /**
1048
- * `server`
1049
- *
1050
- * 在使用前使用 `projectCanBuild` 确保项目可以构建
1051
- * @param {string} projectPath
1052
- * @param {string} projectName
1053
- */
1054
- const buildProject = async (projectPath, projectName) => {
1055
- //读取build.config文件
1056
- const buildConfig = getBuildConfig();
1057
- //读取mod.info文件
1058
- const modInfoPath = path.join(projectPath, "mod.info");
1059
- const modInfo = JSON.parse(readFile(modInfoPath));
1060
- const min_engine_version = versionStringToArray(modInfo.min_engine_version);
1061
- const buildDirPath = path.join(projectPath, buildConfig.buildOptions.buildDir);
1062
- const buildBehDirPath = path.join(buildDirPath, `${projectName}_BP/`);
1063
- const buildResDirPath = path.join(buildDirPath, `${projectName}_RP/`);
1064
- const absoluteModPath = path.join(projectPath, buildConfig.buildOptions.buildEntry);
1065
- if (!server.isListening()) {
1066
- //生成manifest.json文件
1067
- //判断manifest.json是否已经生成过了,生成过了就不用生成
1068
- const manifestPath = path.join(buildBehDirPath, "manifest.json");
1069
- if (pathNotExist(manifestPath)) {
1070
- const behManifest = generateBehManifest(modInfo.name, modInfo.description, modInfo.version, {
1071
- min_engine_version: min_engine_version,
1072
- }, buildConfig.buildOptions.dependencies, buildConfig.buildOptions.scriptEntry);
1073
- const resManifest = generateResManifest(modInfo.name, modInfo.description, modInfo.version, {
1074
- min_engine_version: min_engine_version,
1075
- }, []);
1076
- //BP
1077
- saveFile(path.join(buildBehDirPath, "manifest.json"), behManifest);
1078
- //RP
1079
- saveFile(path.join(buildResDirPath, "manifest.json"), resManifest);
1080
- }
1081
- //复制pack_icon.png
1082
- const packIconPath = path.join(projectPath, "pack_icon.png");
1083
- copyFileSync(packIconPath, path.join(buildBehDirPath, "pack_icon.png"));
1084
- copyFileSync(packIconPath, path.join(buildResDirPath, "pack_icon.png"));
1085
- // 现在只有一个resource
1086
- const resource = buildConfig.buildOptions.resource;
1087
- const sourcePath = path.join(projectPath, resource.path);
1088
- copyFolder(sourcePath, buildResDirPath);
1089
- // 在客户端启动前启动服务器
1090
- startDevServer();
1091
- GRegistryServer.startServer();
1092
- UISystemRegistryServer.startServer();
1093
- server.handle('submit', () => {
1094
- //只有当buildMode为development时才加载用户modjs文件
1095
- if (buildConfig.buildOptions.buildMode === "development") {
1096
- //动态加载用户modjs文件
1097
- generateAddon(absoluteModPath, buildDirPath, projectName);
1098
- }
1099
- });
1100
- }
1101
- // buildEntry (有可能生成ts或js文件, 所以需要先编译)
1102
- await runScript(absoluteModPath);
1103
- // scriptEntry
1104
- await bundleScripts(buildConfig.buildOptions.useJs);
1105
- await syncDevFilesServer(projectPath, projectName);
1106
- };
1107
- function versionStringToArray(versionString) {
1108
- // 使用 split 方法将字符串按 '.' 分割成数组
1109
- const parts = versionString.split('.');
1110
- // 使用 map 方法将每个部分转换为数字
1111
- const versionArray = parts.map(part => Number(part));
1112
- return versionArray;
1113
- }
1114
- const generateBehManifest = (name, description, version, options = {}, dependencies = [], entry) => {
1115
- console.log("开始生成behavior_packs/manifest.json");
1116
- console.log("Entry:", entry);
1117
- const header = new AddonManifestHeader((name + "_BP"), description, versionStringToArray(version), generateUUID(), options);
1118
- const module = new AddonManifestModule("行为模块", "data", generateUUID(), versionStringToArray(version));
1119
- const script_module = new AddonManifestModule("脚本模块", "script", generateUUID(), versionStringToArray(version));
1120
- if (entry) {
1121
- script_module.entry = entry;
1122
- }
1123
- const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
1124
- "sapdon": ["1.0.0"]
1125
- }, "addon", "https://github.com/junjun260/sapdon");
1126
- const manifest = new AddonManifest(2, //格式版本
1127
- header, [module, script_module], dependencies, null, metadata);
1128
- return JSON.stringify(manifest, null, 2);
1129
- };
1130
- const generateResManifest = (name, description, version, options = {}, dependencies = []) => {
1131
- const header = new AddonManifestHeader((name + "_RP"), description, versionStringToArray(version), generateUUID(), options);
1132
- const module = new AddonManifestModule("资源模块", "resources", generateUUID(), versionStringToArray(version));
1133
- const metadata = new AddonManifestMetadata(["@sapdon"], "MIT", {
1134
- "sapdon": ["1.0.0"]
1135
- }, "addon", "https://github.com/junjun260/sapdon");
1136
- const manifest = new AddonManifest(2, //格式版本
1137
- header, [module], [], null, metadata);
1138
- return JSON.stringify(manifest, null, 2);
1139
- };
1140
-
1141
- const classStr = `import fs from 'fs'
1142
- export class FileResource {
1143
- static cache: Record<string, FileResource> = {}
1144
- static fileSystemLoader = (uri: string) => fs.readFileSync(uri)
1145
-
1146
- private _res: any
1147
-
1148
- /**
1149
- * 不要调用构造器!
1150
- * 使用 FileResource.get(uri) 方法获取实例
1151
- * @param origin
1152
- */
1153
- constructor(public origin: string) {
1154
- this.origin = origin
1155
- FileResource.cache[origin] = this
1156
- }
1157
-
1158
- /**
1159
- * @param uri
1160
- * @returns {FileResource}
1161
- */
1162
- static get(uri: string) {
1163
- if (uri in FileResource.cache) {
1164
- return FileResource.cache[uri]
1165
- }
1166
- return new FileResource(uri)
1167
- }
1168
-
1169
- load(loader=FileResource.fileSystemLoader) {
1170
- if (this._res) {
1171
- return this._res
1172
- }
1173
- const content = loader(this.origin)
1174
- this._res = content
1175
- return content
1176
- }
1177
-
1178
- clear() {
1179
- delete FileResource.cache[this.origin]
1180
- }
1181
-
1182
- loadWithoutCache(loader=FileResource.fileSystemLoader) {
1183
- return loader(this.origin)
1184
- }
1185
-
1186
- ptr() {
1187
- const func = () => this.load()
1188
- return Object.assign(func, this)
1189
- }
1190
- }`;
1191
-
1192
- const debounce$1 = lodash.debounce;
1193
- function walk(dir, onfile, ondir) {
1194
- fs.readdirSync(dir).forEach(file => {
1195
- const filePath = path.join(dir, file);
1196
- if (fs.statSync(filePath).isDirectory()) {
1197
- ondir(file, dir);
1198
- walk(filePath, onfile, ondir);
1199
- }
1200
- else {
1201
- onfile(file, dir);
1202
- }
1203
- });
1204
- }
1205
- var ResourceHintType;
1206
- (function (ResourceHintType) {
1207
- ResourceHintType[ResourceHintType["File"] = 0] = "File";
1208
- ResourceHintType[ResourceHintType["Dir"] = 1] = "Dir";
1209
- })(ResourceHintType || (ResourceHintType = {}));
1210
- function jsIdentifier(name) {
1211
- return name.replaceAll('.', '_').replaceAll('-', '_').replaceAll('@', '$');
1212
- }
1213
- function generateResourceHint(resDir) {
1214
- const rootHint = {
1215
- type: ResourceHintType.Dir,
1216
- name: resDir,
1217
- children: {}
1218
- };
1219
- const dirHints = {
1220
- [resDir]: rootHint
1221
- };
1222
- let currentHint = rootHint;
1223
- walk(resDir, (file, dir) => {
1224
- const basename = path.basename(file);
1225
- const name = jsIdentifier(basename.slice(0, basename.lastIndexOf('.')));
1226
- const frh = {
1227
- type: ResourceHintType.File,
1228
- name,
1229
- origin: path.join(dir, file)
1230
- };
1231
- currentHint.children[name] = frh;
1232
- }, (dir, dirParent) => {
1233
- const name = jsIdentifier(dir);
1234
- const parentHint = dirHints[dirParent];
1235
- const nHint = {
1236
- type: ResourceHintType.Dir,
1237
- name,
1238
- children: {}
1239
- };
1240
- parentHint.children[name] = nHint;
1241
- dirHints[path.join(dirParent, dir)] = nHint;
1242
- currentHint = nHint;
1243
- });
1244
- return rootHint;
1245
- }
1246
- function generateHintFile(hint, targetPath) {
1247
- const root = {};
1248
- function traverse(hint, parent) {
1249
- for (const key in hint.children) {
1250
- const child = hint.children[key];
1251
- if (child.type === ResourceHintType.File) {
1252
- parent[child.name] = `<fn>${child.origin}</fn>`;
1253
- }
1254
- else {
1255
- const nParent = {};
1256
- parent[child.name] = nParent;
1257
- traverse(child, nParent);
1258
- }
1259
- }
1260
- }
1261
- traverse(hint, root);
1262
- const preloadClasses = [
1263
- classStr
1264
- ].join(';\n');
1265
- const content = `\n;export default ${JSON.stringify(root, null, 2)}`
1266
- .replace(/"\<fn\>(.*)\<\/fn\>"/g, `FileResource.get('$1').ptr()`);
1267
- fs.writeFileSync(targetPath, preloadClasses + content);
1268
- }
1269
- function checkCwd(cwd) {
1270
- if (!fs.existsSync(path.join(cwd, 'build.config'))) {
1271
- console.log('无法生成资源目录,请 cd 到项目根目录下执行 sapdon res');
1272
- return false;
1273
- }
1274
- return true;
1275
- }
1276
- function watchResourceDir() {
1277
- const cwd = process.cwd();
1278
- if (!checkCwd(cwd)) {
1279
- return;
1280
- }
1281
- fs.watch(path.join(cwd, 'res'), { recursive: true }, debounce$1((a, b) => {
1282
- cp.execSync('sapdon res');
1283
- }, 3000));
1284
- }
1285
- function initResourceDir() {
1286
- // js 项目无法使用资源目录短链接
1287
- const { buildOptions } = getBuildConfig();
1288
- if (buildOptions.buildEntry.endsWith('js')) {
1289
- return;
1290
- }
1291
- const cwd = process.cwd();
1292
- const resDir = path.join(cwd, 'res');
1293
- if (!checkCwd(cwd)) {
1294
- return;
1295
- }
1296
- if (!fs.existsSync(resDir)) {
1297
- fs.mkdirSync(resDir);
1298
- }
1299
- const resourceHint = generateResourceHint(resDir);
1300
- generateHintFile(resourceHint, path.join(cwd, 'res.hint.ts'));
1301
- }
1302
-
1303
- const debounce = lodash.debounce;
1304
- function hmr(projectPath, projectName) {
1305
- const { buildDir, useHMR } = getBuildConfig().buildOptions;
1306
- watchResourceDir();
1307
- if (useHMR) {
1308
- fs.watch(projectPath, { recursive: true }, debounce(async (eventType, filename) => {
1309
- if (!eventType || !filename) {
1310
- return;
1311
- }
1312
- if (filename.startsWith('.') ||
1313
- filename.startsWith(buildDir)) {
1314
- return;
1315
- }
1316
- if (filename.endsWith('.js') ||
1317
- filename.endsWith('.ts') ||
1318
- filename === 'build.config' ||
1319
- filename === 'mod.info') {
1320
- process.stdout.write(`File ${filename} changed, reloading...\r`);
1321
- await buildProject(projectPath, projectName);
1322
- console.log(`Reloaded ${filename}`);
1323
- }
1324
- }), 1000);
1325
- }
1326
- }
1327
-
1328
- const __filename = fileURLToPath$1(import.meta.url);
1329
- const __dirname = path.dirname(__filename);
1330
- process.removeAllListeners('warning');
1331
- async function start() {
1332
- // 额外添加的init方法
1333
- program.command("init").description("初始化一个基于NodeJS的项目").action(() => {
1334
- const currentDir = process.cwd();
1335
- const packageJsonPath = path.join(currentDir, 'package.json');
1336
- let packageJsonData;
1337
- if (!fs.existsSync(packageJsonPath)) {
1338
- console.error("没有找到package.json文件,请使改用create命令进行创建。");
1339
- return;
1340
- }
1341
- try {
1342
- packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
1343
- }
1344
- catch (error) {
1345
- console.error("读取package.json文件时出错:", error);
1346
- console.log("请使改用create命令进行创建。");
1347
- return;
1348
- }
1349
- // 添加或更新scripts字段
1350
- packageJsonData.scripts = {
1351
- ...packageJsonData.scripts,
1352
- init: "sapdon init",
1353
- pack: "sapdon pack",
1354
- config: "sapdon config"
1355
- };
1356
- try {
1357
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonData, null, 2), 'utf-8');
1358
- }
1359
- catch (error) {
1360
- console.error("写入package.json文件时出错:", error);
1361
- return;
1362
- }
1363
- inquirer.prompt([
1364
- {
1365
- type: "input",
1366
- name: "min_engine_version",
1367
- message: "最低引擎版本:",
1368
- default: "1.19.50"
1369
- }
1370
- ]).then((answers) => {
1371
- initNPMProject(currentDir, { ...readPackageJson(currentDir), ...answers });
1372
- console.log("请使用命令sapdon config配置框架的build.config文件。");
1373
- });
1374
- });
1375
- program.command("create <project-name>").description("Create a new project").action((projectName) => {
1376
- inquirer.prompt([
1377
- {
1378
- type: "input",
1379
- name: "name",
1380
- message: "Project Name:",
1381
- default: path.basename(projectName)
1382
- },
1383
- {
1384
- type: "input",
1385
- name: "description",
1386
- message: "Project Description:",
1387
- default: "A new sapdon project"
1388
- },
1389
- {
1390
- type: "input",
1391
- name: "author",
1392
- message: "Author Name:",
1393
- default: "Sapdon"
1394
- },
1395
- {
1396
- type: "input",
1397
- name: "version",
1398
- message: "Project Version:",
1399
- default: "1.0.0"
1400
- },
1401
- {
1402
- type: "input",
1403
- name: "min_engine_version",
1404
- message: "Minimum Engine Version:",
1405
- default: "1.19.50",
1406
- },
1407
- {
1408
- type: "input",
1409
- name: "language",
1410
- message: "Language:(js/ts)",
1411
- default: "ts",
1412
- },
1413
- ]).then((answers) => {
1414
- const projectPath = path.join(process.cwd(), projectName);
1415
- console.log('项目路径:', projectPath);
1416
- initProject(projectPath, answers);
1417
- writeLib(projectPath);
1418
- });
1419
- });
1420
- program.command("build <project-name>").description("Build the project").action((projectName) => {
1421
- console.log("Building the project...");
1422
- const projectPath = path.join(process.cwd(), projectName);
1423
- globalObject.projectPath = projectPath;
1424
- initResourceDir();
1425
- if (projectCanBuild(projectPath)) {
1426
- buildProject(projectPath, path.basename(projectPath));
1427
- hmr(projectPath, projectName);
1428
- }
1429
- });
1430
- // pack 命令
1431
- program.command("pack").description("Pack the current project").action(() => {
1432
- console.log("Packing the current project...");
1433
- const projectPath = process.cwd();
1434
- if (projectCanBuild(projectPath)) {
1435
- buildProject(projectPath, path.basename(projectPath));
1436
- }
1437
- });
1438
- program.command('lib').description('Generate lib files for development server.').action(() => {
1439
- const projectPath = process.cwd();
1440
- writeLib(projectPath);
1441
- });
1442
- program.command('res').description('Generate resource hints.').action(() => {
1443
- initResourceDir();
1444
- });
1445
- // 配置build.config文件的命令
1446
- program.command("config").description("Configure build.config file").action(() => {
1447
- const buildConfigPath = path.join(__dirname, "./build.config");
1448
- let buildConfigData;
1449
- try {
1450
- buildConfigData = JSON.parse(readFile(buildConfigPath));
1451
- }
1452
- catch (error) {
1453
- console.error("读取build.config文件时出错:", error);
1454
- return;
1455
- }
1456
- });
1457
- program.parse(program.argv);
1458
- }
1459
- start();
2
+ import{program as e}from"commander";import n from"inquirer";import t from"path";import{fileURLToPath as o}from"url";import i from"fs";import{randomUUID as r}from"crypto";import{fileURLToPath as s}from"node:url";import c from"child_process";import a from"fs/promises";import l from"http";import{rollup as u}from"rollup";import p from"@rollup/plugin-commonjs";import{nodeResolve as d}from"@rollup/plugin-node-resolve";import m from"@rollup/plugin-typescript";import{typescriptPaths as f}from"rollup-plugin-typescript-paths";import g from"@rollup/plugin-json";import"rollup-plugin-visualizer";import y from"@rollup/plugin-terser";import h from"os";import j from"lodash";const b=()=>r();function S(e,n){try{i.copyFileSync(e,n)}catch(e){console.error("文件复制失败:",e)}}const w=e=>!i.existsSync(e),_=e=>{try{return i.readFileSync(e,"utf8")}catch(e){console.log(e)}return null},v=(e,n)=>{i.mkdirSync(t.dirname(e),{recursive:!0}),i.writeFileSync(e,n)},O=(e,n)=>{if(i.mkdirSync(t.dirname(n),{recursive:!0}),!i.existsSync(e))return void console.log(`Source path ${e} does not exist.`);i.existsSync(n)||i.mkdirSync(n);i.readdirSync(e).forEach(o=>{const r=t.join(e,o),s=t.join(n,o);i.lstatSync(r).isDirectory()?O(r,s):i.copyFileSync(r,s)})};function k(e){const n=s(e.url);return t.dirname(n)}const x=new Map;function N(e,n){let t=x.get(e);return t||(t=n(e),x.set(e,t),t)}function J(){const e=M(),n=t.join(e,"build.config");if(!i.existsSync(n))throw new Error("未找到项目配置文件,请先初始化项目");return N(n,e=>function(e){const n=(t=i.readFileSync(e),JSON.parse(String(t).replace(/\/\/.*|\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/g,"$1")));var t;if(2===n.formatVersion)return n;const o=function({defaultConfig:e,resources:n,scripts:t}){const o={formatVersion:2,buildOptions:{useHMR:!0,buildMode:"development",buildEntry:e.buildEntry,scriptEntry:e.scriptEntry,scriptOutput:e.scriptEntry.replace(".ts",".js"),useJs:"ts"!==t[0].type,buildDir:e.buildDir,dependencies:e.dependencies,resource:{path:n[0].path,resourceHints:!0}},versionType:"release"};return o}(n);return i.writeFileSync(e,JSON.stringify(o,null,2)),o}(e))}const F=o(import.meta.url),$=t.dirname(F),R={js:"js_sapdon",ts:"ts_sapdon"},P=e=>{const n=t.join(e,"package.json");if(!i.existsSync(n))return null;try{const o=JSON.parse(i.readFileSync(n,"utf-8"));return{name:t.basename(e),description:o.description||"A new sapdon project",author:o.author||"Sapdon",version:o.version||"1.0.0"}}catch(e){return console.error("读取package.json文件时出错:",e),null}},D={};function M(){const e=D.projectPath??process.cwd();if(!i.existsSync(t.join(e,"build.config")))throw new Error("无效的项目路径");return e}function E(){const{buildDir:e}=J().buildOptions,n=N("projectName",()=>t.basename(M()));return t.join(M(),e,n+"_bp")}const B=async(e,n,o="")=>{const i={},r=await a.readdir(e);for(const s of r){const r=t.join(e,s);if((await a.stat(r)).isDirectory()){const e=await B(r,n,o);Object.assign(i,e)}else if(s.endsWith(".png")){const e=t.basename(s,".png"),c=`${o}${t.relative(n,r).replace(/\.png$/,"").replace(/\\/g,"/")}`;i[e]={textures:c}}}return i},L=async(e,n,t)=>{try{const o=JSON.stringify(n,null,2);await a.writeFile(e,o),console.log(t)}catch(e){console.error("Error writing JSON file:",e)}};Symbol.metadata||(Symbol.metadata=Symbol("[[metadata]]"));const H=Symbol("isRawJSON");const A=["boolean","number"],I=["string","undefined"];function T(e,n){const t=typeof n;if(null===t)return null;if(I.includes(t))return n;if(A.includes(t))return JSON.rawJSON(n);if("object"===t)return JSON.isRawJSON(n)?n:function(e){return!0===e?.[H]}(n)?JSON.rawJSON(n.rawJSON):n;if("bigint"===t)return JSON.rawJSON(n.toString());throw new Error("Unexpected value")}const W={encode:e=>JSON.stringify(e,T),decode:JSON.parse};const{port:C}={port:49037};const U=new class{cliServerHandlers=new Map;listening=!1;isListening(){return this.listening}bootstrap(){this.listening=!0;const e=l.createServer(async(e,n)=>{const t=this.cliServerHandlers.get((e.url??"/").slice(1));if(t){try{const{promise:n,resolve:o,reject:i}=Promise.withResolvers();let r=Buffer.alloc(0);e.on("data",e=>r=Buffer.concat([r,e])),e.on("end",()=>{try{o(function(e,n=W){return n.decode(e)}(r))}catch(e){i(e)}}),await t(...await n)}catch(e){return console.error(e),n.writeHead(500),void n.end()}n.writeHead(200),n.end()}else n.writeHead(404),n.end()}).listen(C,()=>console.log(`Dev Server listening on port ${C}`));return e.on("error",()=>this.listening=!1),e}handle(e,n){this.cliServerHandlers.set(e,n)}getHandler(e){return this.cliServerHandlers.get(e)}interceptHandler(e,n){const t=n(this.getHandler(e)??Function.prototype);return this.cliServerHandlers.set(e,t),t}};async function V({level:e,message:n,timeStamp:t,stack:o}){console[e](n,o,`\nat ${new Date(t).toLocaleString()}`)}class G{static dataList=[];static getDataList(){return[...this.dataList]}static startServer(){U.handle("submitGregistry",e=>{this.dataList=e}),U.handle("remote-logger",V)}}const q=async(e,n,o)=>{try{t.join(n,`${o}_BP`);const i=t.join(n,`${o}_RP`),r=(...e)=>t.join(i,...e),s=G.getDataList(),c={item:null,block:null,flipbook:[]};for(const{name:e,root:i,path:r,data:a}of s){switch(console.log("处理数据:",e,i,r),e){case"item_texture":c.item=a,console.log("用户物品贴图数据:",c.item);continue;case"terrain_texture":c.block=a,console.log("用户方块贴图数据:",c.block);continue;case"flipbook_textures":c.flipbook=a,console.log("用户翻书贴图数据:",c.flipbook);continue}const s="behavior"===i?`${o}_BP`:`${o}_RP`,l=t.join(n,s),u=t.join(l,r,`${e}.json`);v(u,JSON.stringify(a,null,2))}await async function(e,n,t){const o=e("textures/items"),i=e("textures/item_texture.json");await async function(e,n,t,o){try{const i=await B(e,e,"textures/items/");o&&Object.assign(i,o);const r={resource_pack_name:t,texture_name:"atlas.items",texture_data:i};await L(n,r,"Item texture JSON file generated successfully.")}catch(e){console.error("Error generating item texture JSON:",e)}}(o,i,n,t.item);const r=e("textures/blocks"),s=e("textures/terrain_texture.json");await async function(e,n,t,o){try{const i=await B(e,e,"textures/blocks/");o&&Object.assign(i,o);const r={texture_name:"atlas.terrain",resource_pack_name:t,padding:8,num_mip_levels:4,texture_data:i};await L(n,r,"Block texture JSON file generated successfully.")}catch(e){console.error("Error generating block texture JSON:",e)}}(r,s,n,t.block);const c=e("textures/flipbook_textures.json");v(c,JSON.stringify(t.flipbook,null,2))}(r,o,c),console.log(`已加载并执行 ${e} 文件!`)}catch(n){console.error(`加载或执行 ${e} 失败:${n.message}`),console.error(n.stack)}};class z{name;description;version;uuid;allow_random_seed;lock_template_options;pack_scope;base_game_version;min_engine_version;constructor(e,n,t,o,i={}){this.name=e,this.description=n,this.version=t,this.uuid=o,this.allow_random_seed=i.allow_random_seed,this.lock_template_options=i.lock_template_options,this.pack_scope=i.pack_scope,this.base_game_version=i.base_game_version,this.min_engine_version=i.min_engine_version}}class K{description;type;uuid;version;constructor(e,n,t,o){this.description=e,this.type=n,this.uuid=t,this.version=o}}class Q{authors;license;generated_with;product_type;url;constructor(e,n,t,o,i){this.authors=e,this.license=n,this.generated_with=t,this.product_type=o,this.url=i}}class X{format_version;header;modules;dependencies;capabilities;metadata;constructor(e,n,t,o,i=null,r=null){this.format_version=e,this.header=n,this.modules=t,this.dependencies=o,null!=i&&(this.capabilities=i),null!=r&&(this.metadata=r)}}const Y=process.env.MC_PATH,Z=process.env.MC_BETA_PATH,ee="AppData/Roaming/Minecraft Bedrock/Users/Shared/games/com.mojang",ne="AppData/Local/Packages/Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe/LocalState/games/com.mojang/";function te(){return"beta"===J().versionType?N("McInstallPath.Beta",()=>Z||t.join(h.homedir(),ne)):N("McInstallPath.Main",()=>Y||t.join(h.homedir(),ee))}var oe={name:"sapdon",version:"3.3.3",scripts:{build:"node scripts/build.cjs",pub:"npm run build && npm publish"},keywords:["bedrock","tools","addon"],author:"Meteage",license:"ISC",type:"module",bin:{sapdon:"prod/cli/start.js"},description:"Sapdon is a Node.js toolkit designed for building Bedrock Edition Minecraft addon packs.",devDependencies:{"@minecraft/server":"^2.0.0-beta.1.21.80-preview.20","@minecraft/server-ui":"^1.3.0","@types/d3-array":"^3.2.1","@types/lodash":"^4.17.16","@types/node":"^22.14.0","tsc-alias":"^1.8.13"},dependencies:{"@rollup/plugin-commonjs":"^28.0.2","@rollup/plugin-json":"^6.1.0","@rollup/plugin-node-resolve":"^16.0.0","@rollup/plugin-terser":"^0.4.4","@rollup/plugin-typescript":"^12.1.2",chalk:"^5.4.1",commander:"^13.0.0","d3-array":"^3.2.4","download-git-repo":"^3.0.2",inquirer:"^12.3.1",lodash:"^4.17.21",ora:"^8.1.1",rollup:"^4.39.0","rollup-plugin-dts":"^6.2.1","rollup-plugin-typescript-paths":"^1.5.0","rollup-plugin-visualizer":"^5.14.0","tsconfig-paths":"^4.2.0",tslib:"^2.8.1",typescript:"^5.8.2"},files:["prod/**/*","doc/**/*"]};function ie(){return N(t.join(k(import.meta),"../../../package.json"),()=>oe)}async function re(e,n){const o=J(),r=t.join(e,o.buildOptions.buildDir),s=t.join(r,`${n}_BP`),c=t.join(r,`${n}_RP`);i.cpSync(s,t.join(te(),"development_behavior_packs/",`${n}_BP/`),{recursive:!0,force:!0}),i.cpSync(c,t.join(te(),"development_resource_packs/",`${n}_RP/`),{recursive:!0,force:!0})}async function se(e){const n=t.join(e,"node_modules"),o=t.join(k(import.meta),"../"),r=t.join(o,"core"),s=t.join(o,"cli"),c=t.join(o,"oc"),a=t.join(n,"@sapdon/core"),l=t.join(n,"@sapdon/cli"),u=t.join(n,"@sapdon/runtime"),p=ie();i.cpSync(r,a,{recursive:!0,force:!0}),i.cpSync(s,l,{recursive:!0,force:!0}),i.cpSync(c,u,{recursive:!0,force:!0}),i.writeFileSync(t.join(a,"package.json"),JSON.stringify({name:"@sapdon/core",type:"module",main:"index.js",version:p.version})),i.writeFileSync(t.join(l,"package.json"),JSON.stringify({name:"@sapdon/cli",type:"module",main:"index.js",version:p.version})),i.writeFileSync(t.join(u,"package.json"),JSON.stringify({name:"@sapdon/runtime",type:"module",main:"index.js",version:p.version}))}const ce=o(import.meta.url);t.dirname(ce);const ae=["rollup","typescript","@sapdon/core","@sapdon/cli","@minecraft"],le={js:async(e,n,t)=>{const o=J();try{const i=await u({input:e,plugins:[d({preferBuiltins:!0}),p(),g(),..."development"===o.buildOptions.buildMode?[]:[y()]],external(e){for(const n of ae)if(e.includes(n))return!0;return!1}});await i.write({file:n,format:"esm",sourcemap:t}),i.close()}catch(e){console.error(e)}},ts:async(e,n,o)=>{const i=M(),r=J(),s={file:n,format:"esm",sourcemap:o};try{const n=await u({input:e,plugins:[f(),d({preferBuiltins:!0}),m({tsconfig:t.join(i,"tsconfig.json"),compilerOptions:{outDir:t.dirname(s.file)}}),p(),g(),..."development"===r.buildOptions.buildMode?[]:[y()]],external(e){for(const n of ae)if(e.includes(n))return!0;return!1}});await n.write(s),n.close()}catch(e){console.error(e)}},any:async(e,n)=>{J().buildOptions.useJs?await le.js(e,n):await le.ts(e,n)}};async function ue(e){const n="."+crypto.randomUUID()+".js",o=t.join(t.dirname(e),".tmp",n);await le.any(e,o);try{await async function(e){const{promise:n,resolve:t}=Promise.withResolvers();return c.fork(e,{stdio:"inherit"}).on("exit",t),n}(o)}catch(e){console.error(e)}finally{i.rmSync(o,{force:!0})}}function pe(e){return console.log("开始构建项目"),console.log("项目路径:"+e),w(e)?(console.log("项目不存在"),!1):!w(t.join(e,"build.config"))||(console.log("项目没有build.config文件"),!1)}const de=async(e,n)=>{const o=J(),i=t.join(e,"mod.info"),r=JSON.parse(_(i)),s=me(r.min_engine_version),c=t.join(e,o.buildOptions.buildDir),a=t.join(c,`${n}_BP/`),l=t.join(c,`${n}_RP/`),u=t.join(e,o.buildOptions.buildEntry);if(!U.isListening()){const i=t.join(a,"manifest.json");if(w(i)){const e=fe(r.name,r.description,r.version,{min_engine_version:s},o.buildOptions.dependencies,o.buildOptions.scriptOutput),n=ge(r.name,r.description,r.version,{min_engine_version:s},[]);v(t.join(a,"manifest.json"),e),v(t.join(l,"manifest.json"),n)}const p=t.join(e,"pack_icon.png");S(p,t.join(a,"pack_icon.png")),S(p,t.join(l,"pack_icon.png"));const d=o.buildOptions.resource,m=t.join(e,d.path);O(m,l),U.isListening()||U.bootstrap(),G.startServer(),U.handle("submit",async e=>{"development"===o.buildOptions.buildMode&&(G.dataList=e,await q(u,c,n))})}await ue(u),await async function(e=!1){const n=e?"js":"ts",o=M(),i=J(),{scriptEntry:r,scriptOutput:s,buildMode:c}=i.buildOptions;le[n](t.join(o,r),t.join(E(),s),"development"===c)}(o.buildOptions.useJs),await re(e,n)};function me(e){return e.split(".").map(e=>Number(e))}const fe=(e,n,t,o={},i=[],r)=>{console.log("开始生成behavior_packs/manifest.json"),console.log("Entry:",r);const s=new z(e+"_BP",n,me(t),b(),o),c=new K("行为模块","data",b(),me(t)),a=new K("脚本模块","script",b(),me(t));r&&(a.entry=r);const l=new Q(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),u=new X(2,s,[c,a],i,null,l);return JSON.stringify(u,null,2)},ge=(e,n,t,o={},i=[])=>{const r=new z(e+"_RP",n,me(t),b(),o),s=new K("资源模块","resources",b(),me(t)),c=new Q(["@sapdon"],"MIT",{sapdon:["1.0.0"]},"addon","https://github.com/junjun260/sapdon"),a=new X(2,r,[s],[],null,c);return JSON.stringify(a,null,2)},ye="import fs from 'fs'\nexport class FileResource {\n static cache: Record<string, FileResource> = {}\n static fileSystemLoader = (uri: string) => fs.readFileSync(uri)\n\n private _res: any\n\n /**\n * 不要调用构造器!\n * 使用 FileResource.get(uri) 方法获取实例\n * @param origin \n */\n constructor(public origin: string) {\n this.origin = origin\n FileResource.cache[origin] = this\n }\n\n /**\n * @param uri \n * @returns {FileResource}\n */\n static get(uri: string) {\n if (uri in FileResource.cache) {\n return FileResource.cache[uri]\n }\n return new FileResource(uri)\n }\n\n load(loader=FileResource.fileSystemLoader) {\n if (this._res) {\n return this._res\n }\n const content = loader(this.origin)\n this._res = content\n return content\n }\n\n clear() {\n delete FileResource.cache[this.origin]\n }\n\n loadWithoutCache(loader=FileResource.fileSystemLoader) {\n return loader(this.origin)\n }\n\n ptr() {\n const func = () => this.load()\n return Object.assign(func, this)\n }\n}",he=j.debounce;function je(e,n,o){i.readdirSync(e).forEach(r=>{const s=t.join(e,r);i.statSync(s).isDirectory()?(o(r,e),je(s,n,o)):n(r,e)})}var be;function Se(e){return e.replaceAll(".","_").replaceAll("-","_").replaceAll("@","$")}function we(e){const n={type:be.Dir,name:e,children:{}},o={[e]:n};let i=n;return je(e,(e,n)=>{const o=t.basename(e),r=Se(o.slice(0,o.lastIndexOf("."))),s={type:be.File,name:r,origin:t.join(n,e)};i.children[r]=s},(e,n)=>{const r=Se(e),s=o[n],c={type:be.Dir,name:r,children:{}};s.children[r]=c,o[t.join(n,e)]=c,i=c}),n}function _e(e){return!!i.existsSync(t.join(e,"build.config"))||(console.log("无法生成资源目录,请 cd 到项目根目录下执行 sapdon res"),!1)}function ve(){const{buildOptions:e}=J();if(e.buildEntry.endsWith("js"))return;const n=process.cwd(),o=t.join(n,"res");if(!_e(n))return;i.existsSync(o)||i.mkdirSync(o);!function(e,n){const t={};!function e(n,t){for(const o in n.children){const i=n.children[o];if(i.type===be.File)t[i.name]=`<fn>${i.origin}</fn>`;else{const n={};t[i.name]=n,e(i,n)}}}(e,t);const o=[ye].join(";\n"),r=`\n;export default ${JSON.stringify(t,null,2)}`.replace(/"\<fn\>(.*)\<\/fn\>"/g,"FileResource.get('$1').ptr()");i.writeFileSync(n,o+r)}(we(o),t.join(n,"res.hint.ts"))}!function(e){e[e.File=0]="File",e[e.Dir=1]="Dir"}(be||(be={}));const Oe=j.debounce;function ke(e,n){const{buildDir:o,useHMR:r}=J().buildOptions;!function(){const e=process.cwd();_e(e)&&i.watch(t.join(e,"res"),{recursive:!0},he((e,n)=>{c.execSync("sapdon res")},3e3))}(),r&&i.watch(e,{recursive:!0},Oe(async(i,r)=>{i&&r&&(r.startsWith(".")||r.startsWith(t.join(o,"./"))||r.includes(".tmp")||(r.endsWith(".js")||r.endsWith(".ts")||"build.config"===r||"mod.info"===r)&&(process.stdout.write(`File ${r} changed, reloading...\r`),await de(e,n),await re(e,n),console.log(`Reloaded ${r}`)))}),1e3)}const xe=o(import.meta.url),Ne=t.dirname(xe);process.removeAllListeners("warning"),e.command("init").description("初始化一个基于NodeJS的项目").action(()=>{const e=process.cwd(),o=t.join(e,"package.json");let r;if(i.existsSync(o)){try{r=JSON.parse(i.readFileSync(o,"utf-8"))}catch(e){return console.error("读取package.json文件时出错:",e),void console.log("请使改用create命令进行创建。")}r.scripts={...r.scripts,init:"sapdon init",pack:"sapdon pack",config:"sapdon config"};try{i.writeFileSync(o,JSON.stringify(r,null,2),"utf-8")}catch(e){return void console.error("写入package.json文件时出错:",e)}n.prompt([{type:"input",name:"min_engine_version",message:"最低引擎版本:",default:"1.19.50"}]).then(n=>{((e,n)=>{if(!(w(t.join(e,"mod.info"))&&w(t.join(e,"main.mjs"))&&w(t.join(e,"scripts"))&&w(t.join(e,"build.config"))))return void console.log("项目已存在...");const o=t.join($,"../templates/js_sapdon");O(o,e),v(t.join(e,"mod.info"),JSON.stringify(n,null,2))})(e,{...P(e),...n}),console.log("请使用命令sapdon config配置框架的build.config文件。")})}else console.error("没有找到package.json文件,请使改用create命令进行创建。")}),e.command("create <project-name>").description("Create a new project").action(e=>{n.prompt([{type:"input",name:"name",message:"Project Name:",default:t.basename(e)},{type:"input",name:"description",message:"Project Description:",default:"A new sapdon project"},{type:"input",name:"author",message:"Author Name:",default:"Sapdon"},{type:"input",name:"version",message:"Project Version:",default:"1.0.0"},{type:"input",name:"min_engine_version",message:"Minimum Engine Version:",default:"1.19.50"},{type:"input",name:"language",message:"Language:(js/ts)",default:"ts"}]).then(n=>{const o=t.join(process.cwd(),e);console.log("项目路径:",o),((e,n)=>{if(console.log(1,n),!w(e))return void console.log("项目名称已存在,创建项目目录失败");const o=t.join($,`../../src/templates/${R[n.language||"js"]}`);O(o,e),v(t.join(e,"mod.info"),JSON.stringify(n,null,2)),c.execSync("npm i",{cwd:e,stdio:"inherit"})})(o,n),se(o)})}),e.command("build <project-name>").description("Build the project").action(e=>{console.log("Building the project...");const n=t.join(process.cwd(),e),o=t.basename(n);D.projectPath=n,ve(),pe(n)&&(de(n,o),ke(n,o))}),e.command("pack").description("Pack the current project").action(()=>{console.log("Packing the current project...");const e=process.cwd();pe(e)&&de(e,t.basename(e))}),e.command("lib").description("Generate lib files for development server.").action(()=>{se(process.cwd())}),e.command("res").description("Generate resource hints.").action(()=>{ve()}),e.command("config").description("Configure build.config file").action(()=>{const e=t.join(Ne,"./build.config");let n;try{n=JSON.parse(_(e))}catch(e){return void console.error("读取build.config文件时出错:",e)}}),e.parse(e.argv);