@playcraft/build 0.1.90 → 0.1.92-test
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base-builder.js +2 -41
- package/dist/engines/engine-detector.js +0 -4
- package/dist/engines/generic-adapter.js +19 -14
- package/dist/index.d.ts +4 -19
- package/dist/index.js +2 -11
- package/dist/platforms/adikteev.js +0 -1
- package/dist/platforms/applovin.js +0 -1
- package/dist/platforms/base.js +2 -2
- package/dist/platforms/bigo.js +0 -1
- package/dist/platforms/facebook.js +0 -1
- package/dist/platforms/google.js +0 -1
- package/dist/platforms/inmobi.js +0 -1
- package/dist/platforms/ironsource.js +0 -1
- package/dist/platforms/liftoff.js +0 -1
- package/dist/platforms/mintegral.js +0 -1
- package/dist/platforms/moloco.js +0 -1
- package/dist/platforms/playcraft.js +0 -1
- package/dist/platforms/remerge.js +0 -1
- package/dist/platforms/snapchat.js +0 -1
- package/dist/platforms/tiktok.js +0 -1
- package/dist/platforms/unity.js +0 -1
- package/dist/types.d.ts +0 -5
- package/dist/validation/html-validator.d.ts +0 -5
- package/dist/validation/html-validator.js +17 -19
- package/dist/validation/index.d.ts +0 -4
- package/dist/validation/index.js +0 -4
- package/dist/validation/package-validator.d.ts +0 -2
- package/dist/validation/package-validator.js +64 -25
- package/dist/validation/profiles.d.ts +1 -13
- package/dist/validation/profiles.js +0 -27
- package/dist/validation/source-scanner.d.ts +0 -11
- package/dist/validation/source-scanner.js +2 -32
- package/dist/validation/types.d.ts +2 -155
- package/dist/validation/types.js +1 -1
- package/dist/validation/validation-runner.d.ts +2 -22
- package/dist/validation/validation-runner.js +3 -68
- package/dist/validation/zip-reader.d.ts +0 -7
- package/dist/validation/zip-reader.js +26 -159
- package/dist/vite/config-builder-generic.d.ts +1 -3
- package/dist/vite/config-builder-generic.js +7 -9
- package/dist/vite/config-builder.js +1 -1
- package/dist/vite/plugin-platform.js +54 -30
- package/dist/vite/plugin-source-builder.d.ts +14 -2
- package/dist/vite/plugin-source-builder.js +997 -61
- package/dist/vite-builder.d.ts +5 -4
- package/dist/vite-builder.js +34 -33
- package/package.json +10 -22
- package/dist/audio-source-files.d.ts +0 -5
- package/dist/audio-source-files.js +0 -135
- package/dist/delivery/agent-build-runner.d.ts +0 -44
- package/dist/delivery/agent-build-runner.js +0 -365
- package/dist/delivery/agent-build-source.d.ts +0 -8
- package/dist/delivery/agent-build-source.js +0 -25
- package/dist/delivery/artifact-descriptor.d.ts +0 -31
- package/dist/delivery/artifact-descriptor.js +0 -237
- package/dist/delivery/artifact-package.d.ts +0 -43
- package/dist/delivery/artifact-package.js +0 -283
- package/dist/delivery/build-plan.d.ts +0 -4
- package/dist/delivery/build-plan.js +0 -189
- package/dist/delivery/build-plan.types.d.ts +0 -51
- package/dist/delivery/build-plan.types.js +0 -1
- package/dist/delivery/command-isolation.d.ts +0 -7
- package/dist/delivery/command-isolation.js +0 -252
- package/dist/delivery/commands.d.ts +0 -5
- package/dist/delivery/commands.js +0 -137
- package/dist/delivery/files.d.ts +0 -9
- package/dist/delivery/files.js +0 -144
- package/dist/delivery/git-source-fingerprint.d.ts +0 -2
- package/dist/delivery/git-source-fingerprint.js +0 -58
- package/dist/delivery/isolated-source.d.ts +0 -5
- package/dist/delivery/isolated-source.js +0 -126
- package/dist/delivery/output-publication.d.ts +0 -21
- package/dist/delivery/output-publication.js +0 -444
- package/dist/delivery/project-delivery.d.ts +0 -6
- package/dist/delivery/project-delivery.js +0 -287
- package/dist/delivery/recipe-build-plan.d.ts +0 -4
- package/dist/delivery/recipe-build-plan.js +0 -53
- package/dist/delivery/recipe.d.ts +0 -20
- package/dist/delivery/recipe.js +0 -211
- package/dist/delivery/safe-path.d.ts +0 -2
- package/dist/delivery/safe-path.js +0 -18
- package/dist/delivery/types.d.ts +0 -76
- package/dist/delivery/types.js +0 -1
- package/dist/production-animation-presence.d.ts +0 -2
- package/dist/production-animation-presence.js +0 -146
- package/dist/production-inputs.d.ts +0 -30
- package/dist/production-inputs.js +0 -262
- package/dist/production-source-paths.d.ts +0 -5
- package/dist/production-source-paths.js +0 -27
- package/dist/validation/artifact-qa.d.ts +0 -44
- package/dist/validation/artifact-qa.js +0 -170
- package/dist/validation/artifact-rules.d.ts +0 -28
- package/dist/validation/artifact-rules.js +0 -440
- package/dist/validation/artifact.d.ts +0 -14
- package/dist/validation/artifact.js +0 -188
- package/dist/validation/runtime-load.d.ts +0 -89
- package/dist/validation/runtime-load.js +0 -654
- package/dist/vite/source-builder-asset-paths.d.ts +0 -25
- package/dist/vite/source-builder-asset-paths.js +0 -154
- package/dist/vite/source-builder-esm.d.ts +0 -7
- package/dist/vite/source-builder-esm.js +0 -877
- package/dist/vite/source-builder-types.d.ts +0 -14
- package/dist/vite/source-builder-types.js +0 -1
- package/dist/vite/workspace.d.ts +0 -6
- package/dist/vite/workspace.js +0 -41
- package/dist/workspace-css-imports.d.ts +0 -2
- package/dist/workspace-css-imports.js +0 -139
- package/dist/workspace-model-source.d.ts +0 -14
- package/dist/workspace-model-source.js +0 -184
- package/dist/workspace-public-imports.d.ts +0 -11
- package/dist/workspace-public-imports.js +0 -232
- package/dist/workspace-public-source.d.ts +0 -15
- package/dist/workspace-public-source.js +0 -564
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { generateESMTemplate } from './source-builder-esm.js';
|
|
2
|
-
import { buildFolderFullPathMap, resolveTreePathFromPathArray, } from './source-builder-asset-paths.js';
|
|
3
1
|
import fs from 'fs/promises';
|
|
4
2
|
import path from 'path';
|
|
5
3
|
import { fileURLToPath } from 'url';
|
|
@@ -56,11 +54,7 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
56
54
|
}
|
|
57
55
|
// 通过 Import Map 解析裸模块说明符(如 gameRule、planck 等)
|
|
58
56
|
// Import Map 中的路径是相对于 assets/ 目录的(Import Map 文件本身在 assets/Import Map.json 中)
|
|
59
|
-
if (options.importMap?.content?.imports &&
|
|
60
|
-
!id.startsWith('./') &&
|
|
61
|
-
!id.startsWith('../') &&
|
|
62
|
-
!id.startsWith('/') &&
|
|
63
|
-
!id.startsWith('\0')) {
|
|
57
|
+
if (options.importMap?.content?.imports && !id.startsWith('./') && !id.startsWith('../') && !id.startsWith('/') && !id.startsWith('\0')) {
|
|
64
58
|
const imports = options.importMap.content.imports;
|
|
65
59
|
const assetsDir = path.join(options.projectDir, 'assets');
|
|
66
60
|
// 精确匹配(如 "gameRule" -> "./Generated/GameRule/BreakshotPoolRule.mjs")
|
|
@@ -111,16 +105,14 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
111
105
|
if (id === '\0virtual:game-scripts') {
|
|
112
106
|
// 生成入口文件,直接导入所有真实的脚本文件
|
|
113
107
|
// 让 Vite 自然地处理这些文件及其依赖关系
|
|
114
|
-
const imports = userScripts
|
|
115
|
-
.map((script) => {
|
|
108
|
+
const imports = userScripts.map(script => {
|
|
116
109
|
const scriptPath = path.join(options.projectDir, script.path);
|
|
117
110
|
// 将 Windows 路径中的反斜杠转换为正斜杠,避免在 import 语句中被解释为转义字符
|
|
118
111
|
// 使用 split + join 方式更可靠地处理路径分隔符
|
|
119
112
|
const normalizedPath = scriptPath.split(path.sep).join('/');
|
|
120
113
|
console.log(`[SourceBuilder] 脚本路径: ${scriptPath} -> ${normalizedPath}`);
|
|
121
114
|
return `import '${normalizedPath}';`;
|
|
122
|
-
})
|
|
123
|
-
.join('\n');
|
|
115
|
+
}).join('\n');
|
|
124
116
|
console.log(`[SourceBuilder] 虚拟模块内容:\n${imports}`);
|
|
125
117
|
return imports || '// No user scripts';
|
|
126
118
|
}
|
|
@@ -145,7 +137,9 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
145
137
|
console.log('[SourceBuilder] 生成 config.json');
|
|
146
138
|
// 生成 __settings__.js
|
|
147
139
|
// 如果 config.scenes 中有场景,使用第一个场景的 URL
|
|
148
|
-
const firstScenePath = config.scenes && config.scenes.length > 0
|
|
140
|
+
const firstScenePath = config.scenes && config.scenes.length > 0
|
|
141
|
+
? config.scenes[0].url
|
|
142
|
+
: undefined;
|
|
149
143
|
const settings = generateSettings(projectConfig, firstScenePath);
|
|
150
144
|
await fs.writeFile(path.join(options.outputDir, '__settings__.js'), settings, 'utf-8');
|
|
151
145
|
console.log('[SourceBuilder] 生成 __settings__.js');
|
|
@@ -181,7 +175,6 @@ async function detectFormat(projectDir) {
|
|
|
181
175
|
if (manifest.format === 'playcraft' || Array.isArray(manifest.assets)) {
|
|
182
176
|
return 'playcraft';
|
|
183
177
|
}
|
|
184
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
185
178
|
}
|
|
186
179
|
catch (error) {
|
|
187
180
|
// manifest.json 不存在或格式不对
|
|
@@ -201,7 +194,6 @@ function buildScriptPathMapping(projectConfig, userScripts, projectDir) {
|
|
|
201
194
|
// 构建文件夹 ID 到名称的映射
|
|
202
195
|
const folderMap = new Map();
|
|
203
196
|
for (const [assetId, asset] of Object.entries(assets)) {
|
|
204
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
205
197
|
const assetData = asset;
|
|
206
198
|
if (assetData.type === 'folder') {
|
|
207
199
|
folderMap.set(assetId, assetData.name);
|
|
@@ -209,7 +201,6 @@ function buildScriptPathMapping(projectConfig, userScripts, projectDir) {
|
|
|
209
201
|
}
|
|
210
202
|
// 为每个脚本构建模块路径
|
|
211
203
|
for (const script of userScripts) {
|
|
212
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
213
204
|
const asset = assets[script.id];
|
|
214
205
|
if (!asset)
|
|
215
206
|
continue;
|
|
@@ -251,7 +242,6 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
251
242
|
for (const scriptId of scriptIds) {
|
|
252
243
|
const asset = pcProject.assets[String(scriptId)];
|
|
253
244
|
if (asset && asset.type === 'script') {
|
|
254
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
255
245
|
const assetData = asset;
|
|
256
246
|
// 检查 preload 属性(默认为 true)
|
|
257
247
|
const preload = assetData.preload !== false;
|
|
@@ -268,7 +258,6 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
268
258
|
code,
|
|
269
259
|
name: assetData.name || `script_${scriptId}`,
|
|
270
260
|
});
|
|
271
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
272
261
|
}
|
|
273
262
|
catch (error) {
|
|
274
263
|
console.warn(`警告: 无法读取脚本文件: ${scriptPath}`);
|
|
@@ -284,7 +273,6 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
284
273
|
for (const scriptId of scriptIds) {
|
|
285
274
|
const asset = pcProject.assets[String(scriptId)];
|
|
286
275
|
if (asset && asset.type === 'script') {
|
|
287
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
288
276
|
const assetData = asset;
|
|
289
277
|
// 检查 preload 属性(默认为 true)
|
|
290
278
|
const preload = assetData.preload !== false;
|
|
@@ -301,7 +289,6 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
301
289
|
code,
|
|
302
290
|
name: assetData.name || `script_${scriptId}`,
|
|
303
291
|
});
|
|
304
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
305
292
|
}
|
|
306
293
|
catch (error) {
|
|
307
294
|
console.warn(`警告: 无法读取脚本文件: ${scriptPath}`);
|
|
@@ -344,22 +331,19 @@ async function copyTemplates(outputDir) {
|
|
|
344
331
|
/**
|
|
345
332
|
* 复制资源文件
|
|
346
333
|
*/
|
|
347
|
-
async function copyAssets(projectConfig, projectDir, outputDir,
|
|
348
|
-
|
|
349
|
-
assetsOverride, skipScripts) {
|
|
334
|
+
async function copyAssets(projectConfig, projectDir, outputDir, assetsOverride, skipScripts // ESM 模式下跳过脚本(脚本由 copyUserScriptsForESM 处理)
|
|
335
|
+
) {
|
|
350
336
|
const assetsOutputDir = path.join(outputDir, 'files');
|
|
351
337
|
await fs.mkdir(assetsOutputDir, { recursive: true });
|
|
352
|
-
const assets = assetsOverride ||
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
: projectConfig.assets);
|
|
338
|
+
const assets = assetsOverride || (projectConfig.format === 'playcanvas'
|
|
339
|
+
? projectConfig.assets
|
|
340
|
+
: projectConfig.assets);
|
|
356
341
|
// 使用 Set 去重,避免重复复制同一个文件
|
|
357
342
|
const copiedUrls = new Set();
|
|
358
343
|
let copiedCount = 0;
|
|
359
344
|
let failedCount = 0;
|
|
360
345
|
// 遍历 assets
|
|
361
346
|
for (const [, asset] of Object.entries(assets)) {
|
|
362
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
363
347
|
const assetData = asset;
|
|
364
348
|
if (!assetData.file?.url || assetData.file.url.startsWith('data:')) {
|
|
365
349
|
continue;
|
|
@@ -385,7 +369,6 @@ assetsOverride, skipScripts) {
|
|
|
385
369
|
// 标记为已复制
|
|
386
370
|
copiedUrls.add(assetData.file.url);
|
|
387
371
|
copiedCount++;
|
|
388
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
389
372
|
}
|
|
390
373
|
catch (error) {
|
|
391
374
|
// 资源文件可能不存在(可能是内联的)
|
|
@@ -398,7 +381,6 @@ assetsOverride, skipScripts) {
|
|
|
398
381
|
* 收集项目中所有已注册的脚本名称
|
|
399
382
|
* 从脚本资产中提取 scriptName(ESM 脚本通过 static scriptName 定义)
|
|
400
383
|
*/
|
|
401
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
402
384
|
function collectRegisteredScriptNames(assets) {
|
|
403
385
|
const scriptNames = new Set();
|
|
404
386
|
for (const [, asset] of Object.entries(assets)) {
|
|
@@ -447,27 +429,20 @@ function collectRegisteredScriptNames(assets) {
|
|
|
447
429
|
* 验证并清理场景中的无效脚本引用
|
|
448
430
|
* 移除引用了不存在脚本的组件
|
|
449
431
|
*/
|
|
450
|
-
function validateAndCleanSceneScripts(
|
|
451
|
-
|
|
452
|
-
sceneData, registeredScripts,
|
|
453
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
454
|
-
_sceneName) {
|
|
432
|
+
function validateAndCleanSceneScripts(sceneData, registeredScripts, _sceneName // 保留参数用于将来的日志输出
|
|
433
|
+
) {
|
|
455
434
|
const removedScripts = [];
|
|
456
435
|
if (!sceneData?.entities) {
|
|
457
436
|
return { cleaned: sceneData, removedScripts };
|
|
458
437
|
}
|
|
459
438
|
// 深拷贝场景数据以避免修改原始数据
|
|
460
439
|
const cleaned = JSON.parse(JSON.stringify(sceneData));
|
|
461
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
462
440
|
for (const [entityId, entity] of Object.entries(cleaned.entities)) {
|
|
463
441
|
const scriptComp = entity?.components?.script;
|
|
464
442
|
if (!scriptComp)
|
|
465
443
|
continue;
|
|
466
444
|
// 处理 ESM 格式:scripts 是对象 { scriptName: {...}, ... }
|
|
467
|
-
if (scriptComp.scripts &&
|
|
468
|
-
typeof scriptComp.scripts === 'object' &&
|
|
469
|
-
!Array.isArray(scriptComp.scripts)) {
|
|
470
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
445
|
+
if (scriptComp.scripts && typeof scriptComp.scripts === 'object' && !Array.isArray(scriptComp.scripts)) {
|
|
471
446
|
const validScripts = {};
|
|
472
447
|
for (const [scriptName, scriptData] of Object.entries(scriptComp.scripts)) {
|
|
473
448
|
if (registeredScripts.has(scriptName)) {
|
|
@@ -488,7 +463,6 @@ _sceneName) {
|
|
|
488
463
|
}
|
|
489
464
|
// 处理 Classic 格式:scripts 是数组 [{ name: 'xxx' }, ...]
|
|
490
465
|
if (scriptComp.scripts && Array.isArray(scriptComp.scripts)) {
|
|
491
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
492
466
|
const validScripts = scriptComp.scripts.filter((s) => {
|
|
493
467
|
if (!s?.name)
|
|
494
468
|
return false;
|
|
@@ -524,13 +498,11 @@ outputDir, selectedScenes) {
|
|
|
524
498
|
? pcProject.scenes
|
|
525
499
|
: Object.entries(pcProject.scenes).map(([keyId, scene]) => {
|
|
526
500
|
// keyId 是场景文件名使用的 ID(如 "2388047")
|
|
527
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
528
501
|
return { ...scene, sceneFileId: keyId };
|
|
529
502
|
});
|
|
530
503
|
// 如果提供了 selectedScenes,只生成这些场景
|
|
531
504
|
if (selectedScenes && selectedScenes.length > 0) {
|
|
532
|
-
const selectedUrls = new Set(selectedScenes.map(
|
|
533
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
505
|
+
const selectedUrls = new Set(selectedScenes.map(s => s.url));
|
|
534
506
|
scenes = scenes.filter((scene) => {
|
|
535
507
|
// 优先使用 sceneFileId(来自 scenes.json 的 key)
|
|
536
508
|
const sceneId = scene.sceneFileId || scene.id || scene.name || 'scene';
|
|
@@ -540,7 +512,6 @@ outputDir, selectedScenes) {
|
|
|
540
512
|
}
|
|
541
513
|
let totalRemoved = 0;
|
|
542
514
|
for (const scene of scenes) {
|
|
543
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
544
515
|
const sceneData = scene;
|
|
545
516
|
// 优先使用 sceneFileId(来自 scenes.json 的 key)
|
|
546
517
|
const sceneId = sceneData.sceneFileId || sceneData.id || sceneData.name || 'scene';
|
|
@@ -550,7 +521,7 @@ outputDir, selectedScenes) {
|
|
|
550
521
|
if (removedScripts.length > 0) {
|
|
551
522
|
totalRemoved += removedScripts.length;
|
|
552
523
|
console.warn(`\n⚠️ 场景 "${sceneData.name || sceneId}" 中发现 ${removedScripts.length} 个无效脚本引用,已移除:`);
|
|
553
|
-
removedScripts.slice(0, 10).forEach(
|
|
524
|
+
removedScripts.slice(0, 10).forEach(s => console.warn(` - ${s}`));
|
|
554
525
|
if (removedScripts.length > 10) {
|
|
555
526
|
console.warn(` ... 还有 ${removedScripts.length - 10} 个`);
|
|
556
527
|
}
|
|
@@ -569,8 +540,7 @@ outputDir, selectedScenes) {
|
|
|
569
540
|
let scenes = pcProject.scenes;
|
|
570
541
|
// 如果提供了 selectedScenes,只生成这些场景
|
|
571
542
|
if (selectedScenes && selectedScenes.length > 0) {
|
|
572
|
-
const selectedNames = new Set(selectedScenes.map(
|
|
573
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
543
|
+
const selectedNames = new Set(selectedScenes.map(s => s.name));
|
|
574
544
|
scenes = scenes.filter((scene) => {
|
|
575
545
|
const sceneName = scene.name || scene.id || 'scene';
|
|
576
546
|
return selectedNames.has(sceneName);
|
|
@@ -578,7 +548,6 @@ outputDir, selectedScenes) {
|
|
|
578
548
|
}
|
|
579
549
|
let totalRemoved = 0;
|
|
580
550
|
for (const scene of scenes) {
|
|
581
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
582
551
|
const sceneData = scene;
|
|
583
552
|
const sceneId = sceneData.id || sceneData.name || 'scene';
|
|
584
553
|
const scenePath = path.join(outputDir, `${sceneId}.json`);
|
|
@@ -587,7 +556,7 @@ outputDir, selectedScenes) {
|
|
|
587
556
|
if (removedScripts.length > 0) {
|
|
588
557
|
totalRemoved += removedScripts.length;
|
|
589
558
|
console.warn(`\n⚠️ 场景 "${sceneData.name || sceneId}" 中发现 ${removedScripts.length} 个无效脚本引用,已移除:`);
|
|
590
|
-
removedScripts.slice(0, 10).forEach(
|
|
559
|
+
removedScripts.slice(0, 10).forEach(s => console.warn(` - ${s}`));
|
|
591
560
|
if (removedScripts.length > 10) {
|
|
592
561
|
console.warn(` ... 还有 ${removedScripts.length - 10} 个`);
|
|
593
562
|
}
|
|
@@ -600,6 +569,52 @@ outputDir, selectedScenes) {
|
|
|
600
569
|
}
|
|
601
570
|
}
|
|
602
571
|
}
|
|
572
|
+
/**
|
|
573
|
+
* 构建文件夹 ID -> 完整目录路径的映射
|
|
574
|
+
* PlayCraft Git 项目的 assets.json 中,资产的 path 字段是文件夹 ID 数组(如 [30097022, 30097024]),
|
|
575
|
+
* 需要通过递归遍历构建每个 folder ID 对应的完整路径(如 "LiteCreator/System")
|
|
576
|
+
*/
|
|
577
|
+
function buildFolderFullPathMap(assets) {
|
|
578
|
+
const folderMap = new Map();
|
|
579
|
+
const buildPath = (folderId, visited = new Set()) => {
|
|
580
|
+
if (visited.has(folderId))
|
|
581
|
+
return '';
|
|
582
|
+
if (folderMap.has(folderId))
|
|
583
|
+
return folderMap.get(folderId);
|
|
584
|
+
visited.add(folderId);
|
|
585
|
+
const folder = assets[folderId];
|
|
586
|
+
if (!folder || folder.type !== 'folder')
|
|
587
|
+
return '';
|
|
588
|
+
const pathIds = folder.path || [];
|
|
589
|
+
if (pathIds.length === 0) {
|
|
590
|
+
folderMap.set(folderId, folder.name);
|
|
591
|
+
return folder.name;
|
|
592
|
+
}
|
|
593
|
+
// 最后一个 ID 是直接父文件夹
|
|
594
|
+
const parentId = String(pathIds[pathIds.length - 1]);
|
|
595
|
+
const parentPath = buildPath(parentId, visited);
|
|
596
|
+
const fullPath = parentPath ? `${parentPath}/${folder.name}` : folder.name;
|
|
597
|
+
folderMap.set(folderId, fullPath);
|
|
598
|
+
return fullPath;
|
|
599
|
+
};
|
|
600
|
+
for (const [id, asset] of Object.entries(assets)) {
|
|
601
|
+
if (asset.type === 'folder') {
|
|
602
|
+
buildPath(id);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
return folderMap;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* 从资产的 path 数组(文件夹 ID 列表)重建 treePath
|
|
609
|
+
* path 数组中最后一个 ID 是直接父文件夹
|
|
610
|
+
*/
|
|
611
|
+
function resolveTreePathFromPathArray(pathIds, folderFullPathMap) {
|
|
612
|
+
if (!pathIds || !Array.isArray(pathIds) || pathIds.length === 0) {
|
|
613
|
+
return '';
|
|
614
|
+
}
|
|
615
|
+
const parentFolderId = String(pathIds[pathIds.length - 1]);
|
|
616
|
+
return folderFullPathMap.get(parentFolderId) || '';
|
|
617
|
+
}
|
|
603
618
|
/**
|
|
604
619
|
* 规范化资源 URL(补齐 file.url)
|
|
605
620
|
* 源码导出中的资源只有 file.filename,没有 file.url
|
|
@@ -614,16 +629,13 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
614
629
|
let normalizedCount = 0;
|
|
615
630
|
let notFoundCount = 0;
|
|
616
631
|
for (const [assetId, asset] of Object.entries(assets)) {
|
|
617
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
618
632
|
const assetData = asset;
|
|
619
633
|
// 跳过没有 file 的资源
|
|
620
634
|
if (!assetData.file) {
|
|
621
635
|
continue;
|
|
622
636
|
}
|
|
623
637
|
// 如果已有有效的本地 url(非 API URL),验证文件是否存在
|
|
624
|
-
if (assetData.file.url &&
|
|
625
|
-
!assetData.file.url.startsWith('/api/') &&
|
|
626
|
-
!assetData.file.url.startsWith('http')) {
|
|
638
|
+
if (assetData.file.url && !assetData.file.url.startsWith('/api/') && !assetData.file.url.startsWith('http')) {
|
|
627
639
|
// 已有有效的本地 url,验证文件存在性
|
|
628
640
|
try {
|
|
629
641
|
await fs.access(path.join(projectDir, assetData.file.url));
|
|
@@ -635,8 +647,7 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
635
647
|
}
|
|
636
648
|
}
|
|
637
649
|
// 如果 url 是 API URL(PlayCraft 格式残留),清除它
|
|
638
|
-
if (assetData.file.url &&
|
|
639
|
-
(assetData.file.url.startsWith('/api/') || assetData.file.url.startsWith('http'))) {
|
|
650
|
+
if (assetData.file.url && (assetData.file.url.startsWith('/api/') || assetData.file.url.startsWith('http'))) {
|
|
640
651
|
delete assetData.file.url;
|
|
641
652
|
}
|
|
642
653
|
// 如果已经有有效 url 了(由之前的 loader 设置的),跳过
|
|
@@ -679,7 +690,6 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
679
690
|
normalizedCount++;
|
|
680
691
|
found = true;
|
|
681
692
|
break;
|
|
682
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
683
693
|
}
|
|
684
694
|
catch (error) {
|
|
685
695
|
// 继续尝试下一个
|
|
@@ -694,14 +704,12 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
694
704
|
/**
|
|
695
705
|
* 为脚本资产补齐 __game-scripts.js 信息
|
|
696
706
|
*/
|
|
697
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
698
707
|
async function patchScriptAssets(config, outputDir) {
|
|
699
708
|
if (!config?.assets) {
|
|
700
709
|
return;
|
|
701
710
|
}
|
|
702
711
|
const scriptIds = Array.isArray(config?.application_properties?.scripts)
|
|
703
|
-
?
|
|
704
|
-
config.application_properties.scripts.map((id) => String(id))
|
|
712
|
+
? config.application_properties.scripts.map((id) => String(id))
|
|
705
713
|
: [];
|
|
706
714
|
if (scriptIds.length === 0) {
|
|
707
715
|
return;
|
|
@@ -713,13 +721,11 @@ async function patchScriptAssets(config, outputDir) {
|
|
|
713
721
|
const buffer = await fs.readFile(gameScriptsPath);
|
|
714
722
|
stat = { size: buffer.byteLength };
|
|
715
723
|
hash = crypto.createHash('md5').update(buffer).digest('hex');
|
|
716
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
717
724
|
}
|
|
718
725
|
catch (error) {
|
|
719
726
|
// __game-scripts.js 可能不存在
|
|
720
727
|
}
|
|
721
728
|
for (const [assetId, asset] of Object.entries(config.assets)) {
|
|
722
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
723
729
|
const assetData = asset;
|
|
724
730
|
if (!scriptIds.includes(String(assetId))) {
|
|
725
731
|
continue;
|
|
@@ -735,3 +741,933 @@ async function patchScriptAssets(config, outputDir) {
|
|
|
735
741
|
}
|
|
736
742
|
}
|
|
737
743
|
}
|
|
744
|
+
/**
|
|
745
|
+
* Analyze script file import dependencies and add missing dependency scripts to config.assets.
|
|
746
|
+
* This handles cases like: BoardRandomFiller.mjs imports ./BoardShapeGenerator.mjs,
|
|
747
|
+
* which is not directly referenced in the scene or templates.
|
|
748
|
+
*/
|
|
749
|
+
async function collectScriptImportDependencies(projectConfig, projectDir, importMap, configAssets) {
|
|
750
|
+
const assets = projectConfig.format === 'playcanvas'
|
|
751
|
+
? projectConfig.assets
|
|
752
|
+
: projectConfig.assets;
|
|
753
|
+
// Build folder ID -> name mapping
|
|
754
|
+
const folderMap = new Map();
|
|
755
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
756
|
+
if (asset.type === 'folder') {
|
|
757
|
+
folderMap.set(assetId, asset.name);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
// Build reverse mapping: targetPath -> assetId (for ALL script assets, not just configAssets)
|
|
761
|
+
const targetPathToAssetId = new Map();
|
|
762
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
763
|
+
const assetData = asset;
|
|
764
|
+
if (assetData.type !== 'script')
|
|
765
|
+
continue;
|
|
766
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
767
|
+
const pathIds = assetData.path || [];
|
|
768
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
769
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
770
|
+
if (targetPath) {
|
|
771
|
+
targetPathToAssetId.set(targetPath.replace(/\\/g, '/'), assetId);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
// Regex to extract import specifiers from script content
|
|
775
|
+
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
776
|
+
const importsMap = importMap.content.imports || {};
|
|
777
|
+
// Iteratively discover new script dependencies
|
|
778
|
+
const processedScripts = new Set();
|
|
779
|
+
let newDepsFound = true;
|
|
780
|
+
while (newDepsFound) {
|
|
781
|
+
newDepsFound = false;
|
|
782
|
+
const currentScriptIds = Object.keys(configAssets).filter(id => configAssets[id].type === 'script' && !processedScripts.has(id));
|
|
783
|
+
for (const scriptId of currentScriptIds) {
|
|
784
|
+
processedScripts.add(scriptId);
|
|
785
|
+
const assetData = assets[scriptId];
|
|
786
|
+
if (!assetData)
|
|
787
|
+
continue;
|
|
788
|
+
// Resolve source file path
|
|
789
|
+
const sourcePath = await resolveScriptSourcePath(assetData, scriptId, projectDir);
|
|
790
|
+
if (!sourcePath)
|
|
791
|
+
continue;
|
|
792
|
+
let content;
|
|
793
|
+
try {
|
|
794
|
+
content = await fs.readFile(sourcePath, 'utf-8');
|
|
795
|
+
}
|
|
796
|
+
catch {
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
// Get current script's target path for relative path resolution
|
|
800
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
801
|
+
const pathIds = assetData.path || [];
|
|
802
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
803
|
+
const scriptTargetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
804
|
+
if (!scriptTargetPath)
|
|
805
|
+
continue;
|
|
806
|
+
const scriptDir = path.dirname(scriptTargetPath).replace(/\\/g, '/');
|
|
807
|
+
// Parse all import statements
|
|
808
|
+
let match;
|
|
809
|
+
importRegex.lastIndex = 0;
|
|
810
|
+
while ((match = importRegex.exec(content)) !== null) {
|
|
811
|
+
const modulePath = match[2] || match[5];
|
|
812
|
+
if (!modulePath)
|
|
813
|
+
continue;
|
|
814
|
+
let resolvedTargetPath = null;
|
|
815
|
+
if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
|
|
816
|
+
// Relative import: resolve against script's directory
|
|
817
|
+
const joined = path.posix.join(scriptDir, modulePath);
|
|
818
|
+
resolvedTargetPath = path.posix.normalize(joined);
|
|
819
|
+
}
|
|
820
|
+
else if (!modulePath.startsWith('/') && !modulePath.startsWith('http')) {
|
|
821
|
+
// Import Map alias: resolve via import map
|
|
822
|
+
resolvedTargetPath = resolveModulePathViaImportMap(modulePath, importsMap);
|
|
823
|
+
}
|
|
824
|
+
if (!resolvedTargetPath)
|
|
825
|
+
continue;
|
|
826
|
+
resolvedTargetPath = resolvedTargetPath.replace(/\\/g, '/');
|
|
827
|
+
// Look up the asset by target path
|
|
828
|
+
const depAssetId = targetPathToAssetId.get(resolvedTargetPath);
|
|
829
|
+
if (depAssetId === undefined) {
|
|
830
|
+
console.warn(`Warning: resolvedTargetPath '${resolvedTargetPath}' not found in targetPathToAssetId`);
|
|
831
|
+
}
|
|
832
|
+
else if (!configAssets[depAssetId]) {
|
|
833
|
+
// Found a missing dependency — add it to configAssets
|
|
834
|
+
configAssets[depAssetId] = assets[depAssetId];
|
|
835
|
+
newDepsFound = true;
|
|
836
|
+
console.log(`📜 [ScriptDeps] ${assetData.name} imports ${assets[depAssetId].name} (${depAssetId}) — added to configAssets`);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Resolve the source file path for a script asset.
|
|
844
|
+
* @param assets - 可选,所有资产的 map,用于从 path 数组重建 treePath(PlayCraft Git 仓库场景)
|
|
845
|
+
*/
|
|
846
|
+
async function resolveScriptSourcePath(assetData, scriptId, projectDir, assets) {
|
|
847
|
+
if (assetData.file?.url) {
|
|
848
|
+
const fullPath = path.join(projectDir, assetData.file.url);
|
|
849
|
+
try {
|
|
850
|
+
await fs.access(fullPath);
|
|
851
|
+
return fullPath;
|
|
852
|
+
}
|
|
853
|
+
catch {
|
|
854
|
+
// file.url 指向的文件不存在,继续搜索
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
if (assetData.file?.filename) {
|
|
858
|
+
const filename = assetData.file.filename;
|
|
859
|
+
const revision = assetData.revision ?? 1;
|
|
860
|
+
const candidates = [
|
|
861
|
+
// PlayCanvas 标准结构
|
|
862
|
+
path.join(projectDir, 'files', 'assets', String(scriptId), String(revision), filename),
|
|
863
|
+
path.join(projectDir, 'files', 'assets', String(scriptId), '1', filename),
|
|
864
|
+
path.join(projectDir, 'files', 'assets', String(scriptId), filename),
|
|
865
|
+
];
|
|
866
|
+
// PlayCraft 结构:使用 treePath
|
|
867
|
+
if (assetData.treePath) {
|
|
868
|
+
candidates.push(path.join(projectDir, 'assets', assetData.treePath, filename));
|
|
869
|
+
candidates.push(path.join(projectDir, assetData.treePath, filename));
|
|
870
|
+
}
|
|
871
|
+
// PlayCraft Git 仓库:从 path 数组重建 treePath
|
|
872
|
+
if (assets && assetData.path && Array.isArray(assetData.path) && assetData.path.length > 0) {
|
|
873
|
+
const folderFullPathMap = buildFolderFullPathMap(assets);
|
|
874
|
+
const computedTreePath = resolveTreePathFromPathArray(assetData.path, folderFullPathMap);
|
|
875
|
+
if (computedTreePath) {
|
|
876
|
+
candidates.push(path.join(projectDir, 'assets', computedTreePath, filename));
|
|
877
|
+
candidates.push(path.join(projectDir, computedTreePath, filename));
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
// 最后尝试直接在 assets/ 根目录下查找
|
|
881
|
+
candidates.push(path.join(projectDir, 'assets', filename));
|
|
882
|
+
for (const candidate of candidates) {
|
|
883
|
+
try {
|
|
884
|
+
await fs.access(candidate);
|
|
885
|
+
return candidate;
|
|
886
|
+
}
|
|
887
|
+
catch {
|
|
888
|
+
// try next
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* 生成 ESM 模板文件
|
|
896
|
+
*/
|
|
897
|
+
async function generateESMTemplate(projectConfig, options, config) {
|
|
898
|
+
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
899
|
+
const outputDir = options.outputDir;
|
|
900
|
+
// 1. 生成 index.html (修复 Import Map 路径)
|
|
901
|
+
const htmlTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.html'), 'utf-8');
|
|
902
|
+
const projectName = projectConfig.format === 'playcanvas'
|
|
903
|
+
? projectConfig.project.name || 'PlayCanvas Project'
|
|
904
|
+
: projectConfig.manifest.name || 'PlayCanvas Project';
|
|
905
|
+
// 修复 Import Map 中的路径(将 ./Lib/ 改为 ./)
|
|
906
|
+
const fixedImportMap = fixImportMapPaths(options.importMap?.content || { imports: {} });
|
|
907
|
+
const importMapJson = JSON.stringify(fixedImportMap, null, 2);
|
|
908
|
+
const html = htmlTemplate
|
|
909
|
+
.replace(/\{\{PROJECT_NAME\}\}/g, projectName)
|
|
910
|
+
.replace(/\{\{IMPORT_MAP\}\}/g, importMapJson);
|
|
911
|
+
await fs.writeFile(path.join(outputDir, 'index.html'), html, 'utf-8');
|
|
912
|
+
// 2. 复制 PlayCanvas Engine(UMD 格式)和 ESM 包装器
|
|
913
|
+
const jsDir = path.join(outputDir, 'js');
|
|
914
|
+
await fs.mkdir(jsDir, { recursive: true });
|
|
915
|
+
// 复制 UMD 引擎
|
|
916
|
+
const engineSourcePath = path.join(templatesDir, 'playcanvas-stable.min.js');
|
|
917
|
+
const engineTargetPath = path.join(jsDir, 'playcanvas-engine-umd.js');
|
|
918
|
+
try {
|
|
919
|
+
await fs.copyFile(engineSourcePath, engineTargetPath);
|
|
920
|
+
console.log('[SourceBuilder] PlayCanvas Engine (UMD) 已复制');
|
|
921
|
+
}
|
|
922
|
+
catch (error) {
|
|
923
|
+
console.warn('[SourceBuilder] 警告: 无法复制 PlayCanvas Engine:', error);
|
|
924
|
+
}
|
|
925
|
+
// 复制 ESM 包装器
|
|
926
|
+
const wrapperSourcePath = path.join(templatesDir, 'playcanvas-esm-wrapper.mjs');
|
|
927
|
+
const wrapperTargetPath = path.join(jsDir, 'playcanvas-engine.mjs');
|
|
928
|
+
try {
|
|
929
|
+
await fs.copyFile(wrapperSourcePath, wrapperTargetPath);
|
|
930
|
+
console.log('[SourceBuilder] PlayCanvas ESM 包装器已复制');
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
console.warn('[SourceBuilder] 警告: 无法复制 ESM 包装器:', error);
|
|
934
|
+
}
|
|
935
|
+
// 3. 分析脚本文件的 import 依赖,将缺失的依赖脚本添加到 config.assets
|
|
936
|
+
if (options.importMap) {
|
|
937
|
+
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
938
|
+
}
|
|
939
|
+
// 4. 收集用户脚本的导入路径(传入 config.assets 以包含 template 依赖 + import 依赖的脚本)
|
|
940
|
+
const scriptImportPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
941
|
+
// 5. 从 Import Map 中提取 gameRule 路径
|
|
942
|
+
let gameRulePath = '';
|
|
943
|
+
if (options.importMap?.content?.imports) {
|
|
944
|
+
const imports = options.importMap.content.imports;
|
|
945
|
+
if (imports['gameRule']) {
|
|
946
|
+
// 将 "./Generated/..." 格式转换为相对于 js/ 目录的路径 "../Generated/..."
|
|
947
|
+
gameRulePath = imports['gameRule'];
|
|
948
|
+
if (gameRulePath.startsWith('./')) {
|
|
949
|
+
gameRulePath = '..' + gameRulePath.slice(1); // "./" -> "../"
|
|
950
|
+
}
|
|
951
|
+
console.log(`[SourceBuilder] GameRule 路径: ${gameRulePath}`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
// 5.1 从场景 SystemManager 的 GameConfig.json 中收集 Rule 脚本
|
|
955
|
+
if (options.importMap && projectConfig.format === 'playcanvas') {
|
|
956
|
+
const allAssets = projectConfig.assets || {};
|
|
957
|
+
const pcScenes = projectConfig.scenes;
|
|
958
|
+
// Iterate over selected scenes (from config.scenes) and find the scene data
|
|
959
|
+
for (const sceneRef of (config.scenes || [])) {
|
|
960
|
+
// Extract scene file ID from url (e.g. "4577025.json" -> "4577025")
|
|
961
|
+
const sceneFileId = (sceneRef.url || '').replace(/\.json$/, '');
|
|
962
|
+
const sceneData = pcScenes?.[sceneFileId];
|
|
963
|
+
if (!sceneData?.entities)
|
|
964
|
+
continue;
|
|
965
|
+
// Find SystemManager entity
|
|
966
|
+
for (const [, entity] of Object.entries(sceneData.entities)) {
|
|
967
|
+
if (entity?.name !== 'SystemManager')
|
|
968
|
+
continue;
|
|
969
|
+
const smScript = entity.components?.script?.scripts?.systemManager;
|
|
970
|
+
if (!smScript?.attributes?.gameConfigAsset)
|
|
971
|
+
continue;
|
|
972
|
+
const jsonAssetId = String(smScript.attributes.gameConfigAsset);
|
|
973
|
+
const jsonAsset = allAssets[jsonAssetId];
|
|
974
|
+
if (!jsonAsset || jsonAsset.type !== 'json')
|
|
975
|
+
continue;
|
|
976
|
+
// Read the GameConfig JSON file
|
|
977
|
+
const jsonFilePath = await resolveScriptSourcePath(jsonAsset, jsonAssetId, options.projectDir, allAssets);
|
|
978
|
+
if (!jsonFilePath)
|
|
979
|
+
continue;
|
|
980
|
+
let gameConfig;
|
|
981
|
+
try {
|
|
982
|
+
const content = await fs.readFile(jsonFilePath, 'utf-8');
|
|
983
|
+
gameConfig = JSON.parse(content);
|
|
984
|
+
}
|
|
985
|
+
catch {
|
|
986
|
+
console.warn(`[SourceBuilder] 无法读取 GameConfig.json (${jsonAssetId})`);
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
const ruleName = gameConfig?.Gameplay?.Rule;
|
|
990
|
+
if (!ruleName)
|
|
991
|
+
continue;
|
|
992
|
+
// Resolve Rule script: look for a script asset named "{ruleName}.mjs"
|
|
993
|
+
const ruleFileName = `${ruleName}.mjs`;
|
|
994
|
+
let ruleAssetId = null;
|
|
995
|
+
for (const [assetId, asset] of Object.entries(allAssets)) {
|
|
996
|
+
if (asset.type === 'script' && (asset.file?.filename === ruleFileName || asset.name === ruleFileName)) {
|
|
997
|
+
ruleAssetId = assetId;
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
if (ruleAssetId && !config.assets[ruleAssetId]) {
|
|
1002
|
+
config.assets[ruleAssetId] = allAssets[ruleAssetId];
|
|
1003
|
+
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — added to configAssets`);
|
|
1004
|
+
// Also collect its import dependencies
|
|
1005
|
+
if (options.importMap) {
|
|
1006
|
+
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
1007
|
+
}
|
|
1008
|
+
// Rebuild script import paths to include the new Rule script
|
|
1009
|
+
const newPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
1010
|
+
for (const p of newPaths) {
|
|
1011
|
+
if (!scriptImportPaths.includes(p)) {
|
|
1012
|
+
scriptImportPaths.push(p);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
else if (ruleAssetId) {
|
|
1017
|
+
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — already in configAssets`);
|
|
1018
|
+
}
|
|
1019
|
+
else {
|
|
1020
|
+
console.warn(`⚠️ [GameConfig] Rule "${ruleName}" 对应的脚本 ${ruleFileName} 未找到`);
|
|
1021
|
+
}
|
|
1022
|
+
// Use the rule path from 5.1 if Import Map didn't provide a gameRule mapping (step 5)
|
|
1023
|
+
if (ruleAssetId && !gameRulePath) {
|
|
1024
|
+
const ruleAsset = allAssets[ruleAssetId];
|
|
1025
|
+
// Build folder map for path resolution
|
|
1026
|
+
const folderMap = new Map();
|
|
1027
|
+
for (const [aid, a] of Object.entries(allAssets)) {
|
|
1028
|
+
if (a.type === 'folder')
|
|
1029
|
+
folderMap.set(aid, a.name);
|
|
1030
|
+
}
|
|
1031
|
+
const ruleFilename = ruleAsset.file?.filename || ruleAsset.name + '.mjs';
|
|
1032
|
+
const ruleFolderPath = buildScriptFolderPath(ruleAsset.path || [], folderMap);
|
|
1033
|
+
const targetPath = resolveTargetPathFromImportMap(ruleFolderPath, ruleFilename, options.importMap);
|
|
1034
|
+
if (targetPath) {
|
|
1035
|
+
gameRulePath = '../' + targetPath;
|
|
1036
|
+
console.log(`📜 [GameConfig] 使用 5.1 收集的 Rule 路径: ${gameRulePath}`);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
// 6. 生成 js/index.mjs(包含脚本导入),使用过滤后的 config.scenes
|
|
1043
|
+
await generateESMEntry(projectConfig, outputDir, scriptImportPaths, config.scenes, gameRulePath);
|
|
1044
|
+
// 7. 在 ESM 模式下,复制用户脚本为独立文件,并更新 config.assets 中的 URL
|
|
1045
|
+
if (options.importMap) {
|
|
1046
|
+
const scriptUrlMap = await copyUserScriptsForESM(projectConfig, options.projectDir, outputDir, options.importMap, config.assets);
|
|
1047
|
+
console.log('[SourceBuilder] 用户脚本已复制为独立 ESM 模块');
|
|
1048
|
+
// 更新 config.assets 中脚本的 URL
|
|
1049
|
+
if (scriptUrlMap.size > 0 && config.assets) {
|
|
1050
|
+
for (const [scriptId, newUrl] of scriptUrlMap) {
|
|
1051
|
+
if (config.assets[scriptId] && config.assets[scriptId].file) {
|
|
1052
|
+
config.assets[scriptId].file.url = newUrl;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
// 重新写入 config.json
|
|
1056
|
+
await fs.writeFile(path.join(outputDir, 'config.json'), JSON.stringify(config, null, 2), 'utf-8');
|
|
1057
|
+
console.log(`[SourceBuilder] 更新了 ${scriptUrlMap.size} 个脚本的 URL`);
|
|
1058
|
+
}
|
|
1059
|
+
// 8. 复制 Import Map 中引用的第三方库文件
|
|
1060
|
+
await copyImportMapLibraries(projectConfig, options.projectDir, outputDir, options.importMap);
|
|
1061
|
+
}
|
|
1062
|
+
// 9. 复制其他必要的模板文件
|
|
1063
|
+
const templateFiles = [
|
|
1064
|
+
'__start__.js', // 可能不需要了,但先保留
|
|
1065
|
+
'__modules__.js',
|
|
1066
|
+
'__loading__.js',
|
|
1067
|
+
'styles.css',
|
|
1068
|
+
'manifest.json',
|
|
1069
|
+
];
|
|
1070
|
+
for (const file of templateFiles) {
|
|
1071
|
+
const sourcePath = path.join(templatesDir, file);
|
|
1072
|
+
const targetPath = path.join(outputDir, file);
|
|
1073
|
+
try {
|
|
1074
|
+
await fs.copyFile(sourcePath, targetPath);
|
|
1075
|
+
}
|
|
1076
|
+
catch (error) {
|
|
1077
|
+
// 某些文件可能不存在,忽略
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* 修复 Import Map 中的路径
|
|
1083
|
+
* 将 ./Lib/xxx.mjs 等错误路径修复为正确的相对路径
|
|
1084
|
+
* 并添加必要的模块映射(如 playcanvas)
|
|
1085
|
+
*/
|
|
1086
|
+
function fixImportMapPaths(importMap) {
|
|
1087
|
+
const fixedImports = {};
|
|
1088
|
+
// 添加 playcanvas 引擎映射(脚本中使用 import from 'playcanvas')
|
|
1089
|
+
fixedImports['playcanvas'] = './js/playcanvas-engine.mjs';
|
|
1090
|
+
for (const [key, value] of Object.entries(importMap.imports || {})) {
|
|
1091
|
+
// 修复 ./Lib/ 路径(通常第三方库文件会被复制到根目录)
|
|
1092
|
+
let fixedValue = value;
|
|
1093
|
+
if (value.startsWith('./Lib/')) {
|
|
1094
|
+
// 将 ./Lib/xxx.mjs 改为 ./xxx.mjs
|
|
1095
|
+
fixedValue = './' + value.slice(6);
|
|
1096
|
+
}
|
|
1097
|
+
fixedImports[key] = fixedValue;
|
|
1098
|
+
}
|
|
1099
|
+
return { imports: fixedImports };
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* 收集 ESM 脚本的导入路径
|
|
1103
|
+
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
1104
|
+
*/
|
|
1105
|
+
async function collectESMScriptImports(projectConfig, options, configAssets) {
|
|
1106
|
+
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
1107
|
+
let assets;
|
|
1108
|
+
if (projectConfig.format === 'playcanvas') {
|
|
1109
|
+
assets = projectConfig.assets;
|
|
1110
|
+
}
|
|
1111
|
+
else {
|
|
1112
|
+
assets = projectConfig.assets;
|
|
1113
|
+
}
|
|
1114
|
+
// 收集所有需要导入的脚本 ID:
|
|
1115
|
+
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
1116
|
+
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
1117
|
+
const scriptIdsToImport = new Set();
|
|
1118
|
+
if (configAssets) {
|
|
1119
|
+
console.log(`📜 [DEBUG-ESMImports] 使用 configAssets 收集脚本, configAssets 总数: ${Object.keys(configAssets).length}`);
|
|
1120
|
+
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
1121
|
+
if (asset.type === 'script') {
|
|
1122
|
+
scriptIdsToImport.add(assetId);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
console.log(`[ESMImports] 从 configAssets 收集到 ${scriptIdsToImport.size} 个脚本`);
|
|
1126
|
+
}
|
|
1127
|
+
else {
|
|
1128
|
+
console.log(`[ESMImports] configAssets 未传入, 回退到 settings.scripts`);
|
|
1129
|
+
// Fallback: use settings.scripts
|
|
1130
|
+
let scriptIds;
|
|
1131
|
+
if (projectConfig.format === 'playcanvas') {
|
|
1132
|
+
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
1133
|
+
}
|
|
1134
|
+
else {
|
|
1135
|
+
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
1136
|
+
}
|
|
1137
|
+
for (const id of scriptIds) {
|
|
1138
|
+
scriptIdsToImport.add(String(id));
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
const importPaths = [];
|
|
1142
|
+
// 构建文件夹 ID 到名称的映射
|
|
1143
|
+
const folderMap = new Map();
|
|
1144
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1145
|
+
const assetData = asset;
|
|
1146
|
+
if (assetData.type === 'folder') {
|
|
1147
|
+
folderMap.set(assetId, assetData.name);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
// 遍历每个脚本,构建导入路径
|
|
1151
|
+
for (const scriptId of scriptIdsToImport) {
|
|
1152
|
+
const asset = assets[String(scriptId)];
|
|
1153
|
+
if (!asset || asset.type !== 'script')
|
|
1154
|
+
continue;
|
|
1155
|
+
const assetData = asset;
|
|
1156
|
+
// 获取正确的文件名(带扩展名)
|
|
1157
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
1158
|
+
// 获取脚本的文件夹路径
|
|
1159
|
+
const pathIds = assetData.path || [];
|
|
1160
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
1161
|
+
// 根据 import map 确定目标路径
|
|
1162
|
+
if (options.importMap) {
|
|
1163
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, options.importMap);
|
|
1164
|
+
console.log(`[ESM Imports] ${assetData.name}: folderPath=${folderPath}, filename=${filename}, targetPath=${targetPath}`);
|
|
1165
|
+
if (targetPath) {
|
|
1166
|
+
// 生成相对于 js/ 目录的导入路径
|
|
1167
|
+
// 入口文件在 js/index.mjs,脚本在根目录,所以需要 ../
|
|
1168
|
+
importPaths.push('../' + targetPath);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
return importPaths;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* 生成 ESM 入口文件 js/index.mjs
|
|
1176
|
+
*/
|
|
1177
|
+
async function generateESMEntry(projectConfig, outputDir, scriptImportPaths = [], configScenes, gameRulePath = '') {
|
|
1178
|
+
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
1179
|
+
const esmTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.mjs'), 'utf-8');
|
|
1180
|
+
// 获取项目设置
|
|
1181
|
+
let settings;
|
|
1182
|
+
let scripts = [];
|
|
1183
|
+
if (projectConfig.format === 'playcanvas') {
|
|
1184
|
+
const pcProject = projectConfig;
|
|
1185
|
+
settings = pcProject.project.settings || {};
|
|
1186
|
+
scripts = settings.scripts || [];
|
|
1187
|
+
}
|
|
1188
|
+
else {
|
|
1189
|
+
const pcProject = projectConfig;
|
|
1190
|
+
settings = pcProject.manifest.settings || {};
|
|
1191
|
+
scripts = settings.scripts || [];
|
|
1192
|
+
}
|
|
1193
|
+
// 确定场景路径(优先使用传入的 configScenes,否则从原始 projectConfig 获取)
|
|
1194
|
+
let scenePath = '';
|
|
1195
|
+
if (configScenes && configScenes.length > 0) {
|
|
1196
|
+
// 使用过滤后的配置场景
|
|
1197
|
+
scenePath = configScenes[0].url;
|
|
1198
|
+
}
|
|
1199
|
+
else if (projectConfig.format === 'playcanvas') {
|
|
1200
|
+
const pcProject = projectConfig;
|
|
1201
|
+
if (pcProject.scenes) {
|
|
1202
|
+
const scenes = Array.isArray(pcProject.scenes)
|
|
1203
|
+
? pcProject.scenes
|
|
1204
|
+
: Object.values(pcProject.scenes);
|
|
1205
|
+
if (scenes.length > 0) {
|
|
1206
|
+
const firstScene = scenes[0];
|
|
1207
|
+
scenePath = firstScene.url || firstScene.file || `${firstScene.id || 'scene'}.json`;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
else {
|
|
1212
|
+
const pcProject = projectConfig;
|
|
1213
|
+
if (pcProject.scenes && pcProject.scenes.length > 0) {
|
|
1214
|
+
const firstScene = pcProject.scenes[0];
|
|
1215
|
+
scenePath = firstScene.url || `${firstScene.id || 'scene'}.json`;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
// 构建 CONTEXT_OPTIONS
|
|
1219
|
+
const contextOptions = {
|
|
1220
|
+
antialias: settings.antiAlias ?? true,
|
|
1221
|
+
alpha: false,
|
|
1222
|
+
preserveDrawingBuffer: settings.preserveDrawingBuffer ?? false,
|
|
1223
|
+
deviceTypes: ['webgl2', 'webgl1'],
|
|
1224
|
+
powerPreference: settings.powerPreference || 'high-performance'
|
|
1225
|
+
};
|
|
1226
|
+
// 构建 INPUT_SETTINGS
|
|
1227
|
+
const inputSettings = {
|
|
1228
|
+
useKeyboard: settings.useKeyboard ?? true,
|
|
1229
|
+
useMouse: settings.useMouse ?? true,
|
|
1230
|
+
useGamepads: settings.useGamepads ?? false,
|
|
1231
|
+
useTouch: settings.useTouch ?? true
|
|
1232
|
+
};
|
|
1233
|
+
// 提取预加载模块(WASM 等)
|
|
1234
|
+
const preloadModules = [];
|
|
1235
|
+
// TODO: 从 assets 中提取 WASM 模块
|
|
1236
|
+
// 生成脚本导入路径数组(延迟加载)
|
|
1237
|
+
console.log(`[ESMEntry] 生成 ${scriptImportPaths.length} 个脚本导入路径`);
|
|
1238
|
+
// 替换模板占位符
|
|
1239
|
+
const entry = esmTemplate
|
|
1240
|
+
.replace(/\{\{SCRIPT_IMPORT_PATHS\}\}/g, JSON.stringify(scriptImportPaths))
|
|
1241
|
+
.replace(/\{\{GAME_RULE_PATH\}\}/g, gameRulePath)
|
|
1242
|
+
.replace(/\{\{ASSET_PREFIX\}\}/g, '')
|
|
1243
|
+
.replace(/\{\{SCRIPT_PREFIX\}\}/g, '')
|
|
1244
|
+
.replace(/\{\{SCENE_PATH\}\}/g, scenePath)
|
|
1245
|
+
.replace(/\{\{CONTEXT_OPTIONS\}\}/g, JSON.stringify(contextOptions))
|
|
1246
|
+
.replace(/\{\{SCRIPTS\}\}/g, JSON.stringify(scripts))
|
|
1247
|
+
.replace(/\{\{INPUT_SETTINGS\}\}/g, JSON.stringify(inputSettings))
|
|
1248
|
+
.replace(/\{\{PRELOAD_MODULES\}\}/g, JSON.stringify(preloadModules))
|
|
1249
|
+
.replace(/\{\{LEGACY_SCRIPTS\}\}/g, String(settings.useLegacyScripts ?? false));
|
|
1250
|
+
// 写入 js/index.mjs
|
|
1251
|
+
const jsDir = path.join(outputDir, 'js');
|
|
1252
|
+
await fs.mkdir(jsDir, { recursive: true });
|
|
1253
|
+
await fs.writeFile(path.join(jsDir, 'index.mjs'), entry, 'utf-8');
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* 在 ESM 模式下复制用户脚本为独立文件
|
|
1257
|
+
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
1258
|
+
* @returns 脚本ID到新URL的映射
|
|
1259
|
+
*/
|
|
1260
|
+
async function copyUserScriptsForESM(projectConfig, projectDir, outputDir, importMap, configAssets) {
|
|
1261
|
+
const scriptUrlMap = new Map();
|
|
1262
|
+
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
1263
|
+
let assets;
|
|
1264
|
+
if (projectConfig.format === 'playcanvas') {
|
|
1265
|
+
assets = projectConfig.assets;
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
assets = projectConfig.assets;
|
|
1269
|
+
}
|
|
1270
|
+
// 收集所有需要复制的脚本 ID:
|
|
1271
|
+
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
1272
|
+
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
1273
|
+
const scriptIdsToProcess = new Set();
|
|
1274
|
+
if (configAssets) {
|
|
1275
|
+
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
1276
|
+
if (asset.type === 'script') {
|
|
1277
|
+
scriptIdsToProcess.add(assetId);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
else {
|
|
1282
|
+
let scriptIds;
|
|
1283
|
+
if (projectConfig.format === 'playcanvas') {
|
|
1284
|
+
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
1285
|
+
}
|
|
1286
|
+
else {
|
|
1287
|
+
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
1288
|
+
}
|
|
1289
|
+
for (const id of scriptIds) {
|
|
1290
|
+
scriptIdsToProcess.add(String(id));
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
console.log(`[copyUserScriptsForESM] 复制 ${scriptIdsToProcess.size} 个脚本`);
|
|
1294
|
+
// 构建文件夹 ID 到名称的映射
|
|
1295
|
+
const folderMap = new Map();
|
|
1296
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1297
|
+
const assetData = asset;
|
|
1298
|
+
if (assetData.type === 'folder') {
|
|
1299
|
+
folderMap.set(assetId, assetData.name);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
// 遍历每个脚本
|
|
1303
|
+
for (const scriptId of scriptIdsToProcess) {
|
|
1304
|
+
const asset = assets[String(scriptId)];
|
|
1305
|
+
if (!asset || asset.type !== 'script')
|
|
1306
|
+
continue;
|
|
1307
|
+
const assetData = asset;
|
|
1308
|
+
// 获取脚本源文件路径(使用统一的解析函数,支持 PlayCraft Git 仓库结构)
|
|
1309
|
+
const sourcePath = await resolveScriptSourcePath(assetData, String(scriptId), projectDir, assets);
|
|
1310
|
+
if (!sourcePath) {
|
|
1311
|
+
console.warn(`[ESM] 无法找到脚本 ${assetData.name} 的源文件,跳过`);
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
// 获取脚本的文件夹路径
|
|
1315
|
+
const pathIds = assetData.path || [];
|
|
1316
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
1317
|
+
// 获取正确的文件名(带扩展名)
|
|
1318
|
+
const scriptFilename = assetData.file?.filename || assetData.name + '.mjs';
|
|
1319
|
+
// 根据 import map 确定目标路径
|
|
1320
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, scriptFilename, importMap);
|
|
1321
|
+
if (!targetPath) {
|
|
1322
|
+
console.warn(`[ESM] 无法为脚本 ${assetData.name} 确定目标路径,跳过`);
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
console.log(`[ESM] 脚本 ${assetData.name}: folderPath=${folderPath}, targetPath=${targetPath}`);
|
|
1326
|
+
// 复制文件(并重写 import 语句中的 Import Map 别名)
|
|
1327
|
+
const outputPath = path.join(outputDir, targetPath);
|
|
1328
|
+
try {
|
|
1329
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1330
|
+
// 读取源文件
|
|
1331
|
+
let content = await fs.readFile(sourcePath, 'utf-8');
|
|
1332
|
+
// 修复已知的代码问题(如未定义变量的错误日志)
|
|
1333
|
+
console.log(`[copyUserScriptsForESM] 处理脚本: ${assetData.name}`);
|
|
1334
|
+
content = fixKnownCodeIssues(content, assetData.name);
|
|
1335
|
+
// 重写 import 语句,将 Import Map 别名转换为相对路径
|
|
1336
|
+
content = rewriteImportsWithImportMap(content, targetPath, importMap);
|
|
1337
|
+
// 重写 pc.app 访问,确保在 ESM 模式下能正确获取 app 实例
|
|
1338
|
+
content = rewritePcAppAccess(content);
|
|
1339
|
+
// 写入目标文件
|
|
1340
|
+
await fs.writeFile(outputPath, content, 'utf-8');
|
|
1341
|
+
// 记录脚本ID到新URL的映射
|
|
1342
|
+
scriptUrlMap.set(String(scriptId), targetPath);
|
|
1343
|
+
}
|
|
1344
|
+
catch (error) {
|
|
1345
|
+
console.warn(`[ESM] 无法复制脚本 ${assetData.name}:`, error);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
return scriptUrlMap;
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* 重写脚本内容中的 import 语句
|
|
1352
|
+
* 将 Import Map 别名转换为相对于脚本位置的相对路径
|
|
1353
|
+
*/
|
|
1354
|
+
function rewriteImportsWithImportMap(content, scriptTargetPath, importMap) {
|
|
1355
|
+
const imports = importMap.content.imports || {};
|
|
1356
|
+
// 获取脚本所在目录(相对于输出根目录)
|
|
1357
|
+
const scriptDir = path.dirname(scriptTargetPath);
|
|
1358
|
+
// 正则匹配 import 语句中的模块说明符
|
|
1359
|
+
// 匹配: import ... from 'xxx' 或 import ... from "xxx" 或 import('xxx') 等
|
|
1360
|
+
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
1361
|
+
return content.replace(importRegex, (match, p1, p2, p3, p4, p5, p6) => {
|
|
1362
|
+
const prefix = p1 || p4;
|
|
1363
|
+
const modulePath = p2 || p5;
|
|
1364
|
+
const suffix = p3 || p6;
|
|
1365
|
+
// 如果已经是相对路径(./ 或 ../)或绝对路径(/ 或 http),不处理
|
|
1366
|
+
if (modulePath.startsWith('./') || modulePath.startsWith('../') ||
|
|
1367
|
+
modulePath.startsWith('/') || modulePath.startsWith('http://') ||
|
|
1368
|
+
modulePath.startsWith('https://')) {
|
|
1369
|
+
return match;
|
|
1370
|
+
}
|
|
1371
|
+
// 尝试通过 Import Map 解析模块路径
|
|
1372
|
+
const resolvedPath = resolveModulePathViaImportMap(modulePath, imports);
|
|
1373
|
+
if (resolvedPath) {
|
|
1374
|
+
// 计算从脚本位置到解析后路径的相对路径
|
|
1375
|
+
const relativePath = calculateRelativePath(scriptDir, resolvedPath);
|
|
1376
|
+
return prefix + relativePath + suffix;
|
|
1377
|
+
}
|
|
1378
|
+
// 如果无法解析,保持原样
|
|
1379
|
+
return match;
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* 通过 Import Map 解析模块路径
|
|
1384
|
+
* 注意:需要应用与 fixImportMapPaths 相同的路径修复逻辑
|
|
1385
|
+
*/
|
|
1386
|
+
function resolveModulePathViaImportMap(modulePath, imports) {
|
|
1387
|
+
// 1. 精确匹配
|
|
1388
|
+
if (imports[modulePath]) {
|
|
1389
|
+
let resolved = imports[modulePath];
|
|
1390
|
+
// 去掉开头的 ./
|
|
1391
|
+
if (resolved.startsWith('./')) {
|
|
1392
|
+
resolved = resolved.slice(2);
|
|
1393
|
+
}
|
|
1394
|
+
// 修复 Lib/ 路径(与 fixImportMapPaths 保持一致)
|
|
1395
|
+
// 将 Lib/xxx.mjs 改为 xxx.mjs(因为这些文件会被复制到根目录)
|
|
1396
|
+
if (resolved.startsWith('Lib/')) {
|
|
1397
|
+
resolved = resolved.slice(4);
|
|
1398
|
+
}
|
|
1399
|
+
return resolved;
|
|
1400
|
+
}
|
|
1401
|
+
// 2. 前缀匹配(目录别名)
|
|
1402
|
+
for (const [prefix, target] of Object.entries(imports)) {
|
|
1403
|
+
if (prefix.endsWith('/') && modulePath.startsWith(prefix)) {
|
|
1404
|
+
const remainder = modulePath.slice(prefix.length);
|
|
1405
|
+
let targetBase = target;
|
|
1406
|
+
// 去掉开头的 ./
|
|
1407
|
+
if (targetBase.startsWith('./')) {
|
|
1408
|
+
targetBase = targetBase.slice(2);
|
|
1409
|
+
}
|
|
1410
|
+
// 修复 Lib/ 路径
|
|
1411
|
+
if (targetBase.startsWith('Lib/')) {
|
|
1412
|
+
targetBase = targetBase.slice(4);
|
|
1413
|
+
}
|
|
1414
|
+
// 去掉结尾的 /
|
|
1415
|
+
if (targetBase.endsWith('/')) {
|
|
1416
|
+
targetBase = targetBase.slice(0, -1);
|
|
1417
|
+
}
|
|
1418
|
+
return targetBase + '/' + remainder;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return null;
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* 计算从源目录到目标路径的相对路径
|
|
1425
|
+
*/
|
|
1426
|
+
function calculateRelativePath(fromDir, toPath) {
|
|
1427
|
+
// 将路径统一使用正斜杠
|
|
1428
|
+
fromDir = fromDir.replace(/\\/g, '/');
|
|
1429
|
+
toPath = toPath.replace(/\\/g, '/');
|
|
1430
|
+
// 分割路径
|
|
1431
|
+
const fromParts = fromDir ? fromDir.split('/').filter(p => p) : [];
|
|
1432
|
+
const toParts = toPath.split('/').filter(p => p);
|
|
1433
|
+
// 找到共同前缀
|
|
1434
|
+
let commonLength = 0;
|
|
1435
|
+
for (let i = 0; i < Math.min(fromParts.length, toParts.length); i++) {
|
|
1436
|
+
if (fromParts[i] === toParts[i]) {
|
|
1437
|
+
commonLength++;
|
|
1438
|
+
}
|
|
1439
|
+
else {
|
|
1440
|
+
break;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
// 计算需要向上走多少级
|
|
1444
|
+
const upCount = fromParts.length - commonLength;
|
|
1445
|
+
// 构建相对路径
|
|
1446
|
+
const upPath = '../'.repeat(upCount);
|
|
1447
|
+
const downPath = toParts.slice(commonLength).join('/');
|
|
1448
|
+
const result = upPath + downPath;
|
|
1449
|
+
// 如果结果为空或不以 ./ 或 ../ 开头,添加 ./
|
|
1450
|
+
if (!result || (!result.startsWith('./') && !result.startsWith('../'))) {
|
|
1451
|
+
return './' + result;
|
|
1452
|
+
}
|
|
1453
|
+
return result;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* 修复已知的代码问题
|
|
1457
|
+
* 这些是项目源代码中的 bug,需要在打包时自动修复
|
|
1458
|
+
*/
|
|
1459
|
+
function fixKnownCodeIssues(content, scriptName) {
|
|
1460
|
+
let modified = content;
|
|
1461
|
+
let fixCount = 0;
|
|
1462
|
+
// 修复 1: GameplaySystem.mjs 中 ruleName 未定义的问题
|
|
1463
|
+
// 原代码: console.error(`[LC] Load game rule '${ruleName}' failed`);
|
|
1464
|
+
// 问题: ruleName 变量在上面被注释掉了,但错误日志仍然引用它
|
|
1465
|
+
if (content.includes("console.error(`[LC] Load game rule '${ruleName}' failed`)")) {
|
|
1466
|
+
modified = modified.replace("console.error(`[LC] Load game rule '${ruleName}' failed`)", "console.error(`[LC] Load game rule failed - GameplaySystem.gameRule is null`)");
|
|
1467
|
+
fixCount++;
|
|
1468
|
+
console.log(`[SourceBuilder] 修复 ${scriptName}: ruleName 未定义问题`);
|
|
1469
|
+
}
|
|
1470
|
+
// 修复 2: AimAdjustmentBar.mjs 中 sprite 可能为 null 的问题
|
|
1471
|
+
// 原代码: const frameKey = this.wheel.element.sprite.frameKeys[frameNum];
|
|
1472
|
+
// 问题: sprite 资源可能还没加载完成或引用丢失
|
|
1473
|
+
if (content.includes('this.wheel.element.sprite.frameKeys[frameNum]')) {
|
|
1474
|
+
// 直接替换整行
|
|
1475
|
+
const oldLine = 'const frameKey = this.wheel.element.sprite.frameKeys[frameNum];';
|
|
1476
|
+
const newLines = `const sprite = this.wheel.element.sprite;
|
|
1477
|
+
if (!sprite || !sprite.frameKeys || !sprite.atlas) {
|
|
1478
|
+
console.warn('[AimAdjustmentBar] Sprite not ready, skipping wheel initialization');
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
const frameKey = sprite.frameKeys[frameNum];`;
|
|
1482
|
+
if (content.includes(oldLine)) {
|
|
1483
|
+
modified = modified.replace(oldLine, newLines);
|
|
1484
|
+
// 同时替换 atlas 的访问
|
|
1485
|
+
const oldAtlas = 'const atlas = this.wheel.element.sprite.atlas;';
|
|
1486
|
+
const newAtlas = 'const atlas = sprite.atlas;';
|
|
1487
|
+
modified = modified.replace(oldAtlas, newAtlas);
|
|
1488
|
+
// 添加对 atlas.frames 的空值检查
|
|
1489
|
+
const oldRect = 'const rect = atlas.frames[frameKey].rect;';
|
|
1490
|
+
const newRect = `if (!atlas.frames || !atlas.frames[frameKey]) {
|
|
1491
|
+
console.warn('[AimAdjustmentBar] Atlas frame not found:', frameKey);
|
|
1492
|
+
return;
|
|
1493
|
+
}
|
|
1494
|
+
const rect = atlas.frames[frameKey].rect;`;
|
|
1495
|
+
modified = modified.replace(oldRect, newRect);
|
|
1496
|
+
fixCount++;
|
|
1497
|
+
console.log(`[SourceBuilder] 修复 ${scriptName}: sprite 空值检查`);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
// 可以在这里添加更多已知问题的修复...
|
|
1501
|
+
if (fixCount > 0) {
|
|
1502
|
+
console.log(`[SourceBuilder] 共修复 ${scriptName} 中的 ${fixCount} 个已知问题`);
|
|
1503
|
+
}
|
|
1504
|
+
return modified;
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* 重写 pc.app 访问为 window.pc.app
|
|
1508
|
+
*
|
|
1509
|
+
* 问题背景:
|
|
1510
|
+
* 在 ESM 模式下,用户脚本通过 `import * as pc from 'playcanvas'` 导入。
|
|
1511
|
+
* ESM 命名空间对象是静态的、冻结的,无法在运行时添加 `app` 属性。
|
|
1512
|
+
* 但 PlayCanvas 脚本习惯使用 `pc.app.root`、`pc.app.assets` 等方式访问应用实例。
|
|
1513
|
+
*
|
|
1514
|
+
* 解决方案:
|
|
1515
|
+
* 将代码中的 `pc.app` 重写为 `window.pc.app`,因为 `window.pc` 是可变的,
|
|
1516
|
+
* 在 index.esm.mjs 中会设置 `window.pc.app = app`。
|
|
1517
|
+
*/
|
|
1518
|
+
function rewritePcAppAccess(content) {
|
|
1519
|
+
// 匹配 pc.app 的访问模式
|
|
1520
|
+
// 不匹配已经是 window.pc.app 的情况
|
|
1521
|
+
// 使用负向后瞻确保前面不是 window. 或其他字母
|
|
1522
|
+
// 使用两个步骤:
|
|
1523
|
+
// 1. 先统计需要替换的数量
|
|
1524
|
+
// 2. 再执行替换
|
|
1525
|
+
const pcAppRegex = /(?<!window\.)(?<!\w)pc\.app\b/g;
|
|
1526
|
+
// 统计匹配数量(在替换前)
|
|
1527
|
+
const matches = content.match(pcAppRegex);
|
|
1528
|
+
const matchCount = matches ? matches.length : 0;
|
|
1529
|
+
// 如果没有需要替换的内容,直接返回
|
|
1530
|
+
if (matchCount === 0) {
|
|
1531
|
+
return content;
|
|
1532
|
+
}
|
|
1533
|
+
// 执行替换
|
|
1534
|
+
const modified = content.replace(pcAppRegex, 'window.pc.app');
|
|
1535
|
+
console.log(`[SourceBuilder] 重写了 ${matchCount} 处 pc.app -> window.pc.app`);
|
|
1536
|
+
return modified;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* 构建脚本的文件夹路径(从 asset.path 数组)
|
|
1540
|
+
*/
|
|
1541
|
+
function buildScriptFolderPath(pathIds, folderMap) {
|
|
1542
|
+
const pathNames = [];
|
|
1543
|
+
// 跳过根文件夹(第一个元素),构建路径
|
|
1544
|
+
for (let i = 1; i < pathIds.length; i++) {
|
|
1545
|
+
const folderId = String(pathIds[i]);
|
|
1546
|
+
const folderName = folderMap.get(folderId);
|
|
1547
|
+
if (folderName) {
|
|
1548
|
+
pathNames.push(folderName);
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
return pathNames.join('/');
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* 根据 import map 确定目标路径
|
|
1555
|
+
*/
|
|
1556
|
+
function resolveTargetPathFromImportMap(folderPath, filename, importMap) {
|
|
1557
|
+
const imports = importMap.content.imports || {};
|
|
1558
|
+
// 尝试匹配 import map 中的前缀
|
|
1559
|
+
for (const [prefix, target] of Object.entries(imports)) {
|
|
1560
|
+
// prefix 可能是 "Gameplay/" 这样的目录前缀
|
|
1561
|
+
if (prefix.endsWith('/')) {
|
|
1562
|
+
const prefixName = prefix.slice(0, -1); // 移除末尾的 '/'
|
|
1563
|
+
// 检查文件夹路径是否以该前缀开始
|
|
1564
|
+
if (folderPath === prefixName || folderPath.startsWith(prefixName + '/')) {
|
|
1565
|
+
// 计算相对于前缀的剩余路径
|
|
1566
|
+
const relativePath = folderPath === prefixName
|
|
1567
|
+
? ''
|
|
1568
|
+
: folderPath.slice(prefixName.length + 1);
|
|
1569
|
+
// 构建目标路径(使用正斜杠,因为 ESM import 需要 URL 风格路径)
|
|
1570
|
+
const targetBase = target.startsWith('./') ? target.slice(2) : target;
|
|
1571
|
+
const resultPath = relativePath
|
|
1572
|
+
? path.join(targetBase, relativePath, filename)
|
|
1573
|
+
: path.join(targetBase, filename);
|
|
1574
|
+
// 确保使用正斜杠(Windows 兼容)
|
|
1575
|
+
return resultPath.replace(/\\/g, '/');
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
// 如果没有匹配的前缀,使用原始路径
|
|
1580
|
+
const defaultPath = folderPath ? path.join(folderPath, filename) : filename;
|
|
1581
|
+
// 确保使用正斜杠(Windows 兼容)
|
|
1582
|
+
return defaultPath.replace(/\\/g, '/');
|
|
1583
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* 复制 Import Map 中引用的第三方库文件
|
|
1586
|
+
* 例如 planck.mjs 等
|
|
1587
|
+
*/
|
|
1588
|
+
async function copyImportMapLibraries(projectConfig, projectDir, outputDir, importMap) {
|
|
1589
|
+
const imports = importMap.content.imports || {};
|
|
1590
|
+
const assets = projectConfig.format === 'playcanvas'
|
|
1591
|
+
? projectConfig.assets
|
|
1592
|
+
: projectConfig.assets;
|
|
1593
|
+
for (const [key, value] of Object.entries(imports)) {
|
|
1594
|
+
// 跳过目录前缀(以 / 结尾的)
|
|
1595
|
+
if (key.endsWith('/'))
|
|
1596
|
+
continue;
|
|
1597
|
+
// 跳过 playcanvas 引擎(由模板处理)
|
|
1598
|
+
if (key === 'playcanvas')
|
|
1599
|
+
continue;
|
|
1600
|
+
// 处理单个文件的导入(如 "planck": "./Lib/planck.mjs")
|
|
1601
|
+
let targetPath = value;
|
|
1602
|
+
// 修复路径(./Lib/ -> ./)
|
|
1603
|
+
if (targetPath.startsWith('./Lib/')) {
|
|
1604
|
+
targetPath = './' + targetPath.slice(6);
|
|
1605
|
+
}
|
|
1606
|
+
// 移除 ./ 前缀
|
|
1607
|
+
const outputRelPath = targetPath.startsWith('./') ? targetPath.slice(2) : targetPath;
|
|
1608
|
+
const outputPath = path.join(outputDir, outputRelPath);
|
|
1609
|
+
// 检查目标文件是否已存在(可能已被 copyUserScriptsForESM 复制)
|
|
1610
|
+
try {
|
|
1611
|
+
await fs.access(outputPath);
|
|
1612
|
+
console.log(`[ESM] 第三方库已存在,跳过: ${key} -> ${outputRelPath}`);
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
catch {
|
|
1616
|
+
// 文件不存在,需要复制
|
|
1617
|
+
}
|
|
1618
|
+
// 查找源文件
|
|
1619
|
+
// 1. 首先检查是否是 asset 引用(通过 name 查找),使用统一的解析函数
|
|
1620
|
+
let sourceFound = false;
|
|
1621
|
+
const filename = path.basename(outputRelPath);
|
|
1622
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1623
|
+
const assetData = asset;
|
|
1624
|
+
if (assetData.type !== 'script')
|
|
1625
|
+
continue;
|
|
1626
|
+
if (assetData.name !== key && assetData.file?.filename !== filename)
|
|
1627
|
+
continue;
|
|
1628
|
+
// 使用统一的解析函数查找源文件(支持 PlayCraft Git 仓库结构)
|
|
1629
|
+
const sourcePath = await resolveScriptSourcePath(assetData, assetId, projectDir, assets);
|
|
1630
|
+
if (sourcePath) {
|
|
1631
|
+
try {
|
|
1632
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1633
|
+
await fs.copyFile(sourcePath, outputPath);
|
|
1634
|
+
console.log(`[ESM] 复制第三方库: ${key} -> ${outputRelPath}`);
|
|
1635
|
+
sourceFound = true;
|
|
1636
|
+
}
|
|
1637
|
+
catch (error) {
|
|
1638
|
+
console.warn(`[ESM] 无法复制第三方库 ${key}:`, error);
|
|
1639
|
+
}
|
|
1640
|
+
break;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
// 2. 如果没有在 assets 中找到,尝试在项目目录中直接查找
|
|
1644
|
+
if (!sourceFound) {
|
|
1645
|
+
// 尝试原始路径(例如 ./Lib/planck.mjs)
|
|
1646
|
+
const originalPath = value.startsWith('./') ? value.slice(2) : value;
|
|
1647
|
+
const candidates = [
|
|
1648
|
+
path.join(projectDir, originalPath),
|
|
1649
|
+
path.join(projectDir, filename),
|
|
1650
|
+
path.join(projectDir, 'Lib', filename),
|
|
1651
|
+
// PlayCraft Git 仓库结构
|
|
1652
|
+
path.join(projectDir, 'assets', filename),
|
|
1653
|
+
path.join(projectDir, 'assets', originalPath),
|
|
1654
|
+
];
|
|
1655
|
+
for (const candidate of candidates) {
|
|
1656
|
+
try {
|
|
1657
|
+
await fs.access(candidate);
|
|
1658
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1659
|
+
await fs.copyFile(candidate, outputPath);
|
|
1660
|
+
console.log(`[ESM] 复制第三方库(从目录): ${key} -> ${outputRelPath}`);
|
|
1661
|
+
sourceFound = true;
|
|
1662
|
+
break;
|
|
1663
|
+
}
|
|
1664
|
+
catch {
|
|
1665
|
+
// 继续尝试
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
if (!sourceFound) {
|
|
1670
|
+
console.warn(`[ESM] 未找到第三方库 ${key} 的源文件`);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
}
|