@playcraft/build 0.1.88 → 0.1.90

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 (101) hide show
  1. package/dist/audio-source-files.d.ts +5 -0
  2. package/dist/audio-source-files.js +135 -0
  3. package/dist/base-builder.js +41 -2
  4. package/dist/delivery/agent-build-runner.d.ts +44 -0
  5. package/dist/delivery/agent-build-runner.js +365 -0
  6. package/dist/delivery/agent-build-source.d.ts +8 -0
  7. package/dist/delivery/agent-build-source.js +25 -0
  8. package/dist/delivery/artifact-descriptor.d.ts +31 -0
  9. package/dist/delivery/artifact-descriptor.js +237 -0
  10. package/dist/delivery/artifact-package.d.ts +43 -0
  11. package/dist/delivery/artifact-package.js +283 -0
  12. package/dist/delivery/build-plan.d.ts +4 -0
  13. package/dist/delivery/build-plan.js +189 -0
  14. package/dist/delivery/build-plan.types.d.ts +51 -0
  15. package/dist/delivery/build-plan.types.js +1 -0
  16. package/dist/delivery/command-isolation.d.ts +7 -0
  17. package/dist/delivery/command-isolation.js +252 -0
  18. package/dist/delivery/commands.d.ts +5 -0
  19. package/dist/delivery/commands.js +137 -0
  20. package/dist/delivery/files.d.ts +9 -0
  21. package/dist/delivery/files.js +144 -0
  22. package/dist/delivery/git-source-fingerprint.d.ts +2 -0
  23. package/dist/delivery/git-source-fingerprint.js +58 -0
  24. package/dist/delivery/isolated-source.d.ts +5 -0
  25. package/dist/delivery/isolated-source.js +126 -0
  26. package/dist/delivery/output-publication.d.ts +21 -0
  27. package/dist/delivery/output-publication.js +444 -0
  28. package/dist/delivery/project-delivery.d.ts +6 -0
  29. package/dist/delivery/project-delivery.js +287 -0
  30. package/dist/delivery/recipe-build-plan.d.ts +4 -0
  31. package/dist/delivery/recipe-build-plan.js +53 -0
  32. package/dist/delivery/recipe.d.ts +20 -0
  33. package/dist/delivery/recipe.js +211 -0
  34. package/dist/delivery/safe-path.d.ts +2 -0
  35. package/dist/delivery/safe-path.js +18 -0
  36. package/dist/delivery/types.d.ts +76 -0
  37. package/dist/delivery/types.js +1 -0
  38. package/dist/engines/engine-detector.js +4 -0
  39. package/dist/engines/generic-adapter.js +14 -19
  40. package/dist/index.d.ts +19 -4
  41. package/dist/index.js +11 -2
  42. package/dist/platforms/adikteev.js +1 -0
  43. package/dist/platforms/applovin.js +1 -0
  44. package/dist/platforms/base.js +2 -2
  45. package/dist/platforms/bigo.js +1 -0
  46. package/dist/platforms/facebook.js +1 -0
  47. package/dist/platforms/google.js +1 -0
  48. package/dist/platforms/inmobi.js +1 -0
  49. package/dist/platforms/ironsource.js +1 -0
  50. package/dist/platforms/liftoff.js +1 -0
  51. package/dist/platforms/mintegral.js +1 -0
  52. package/dist/platforms/moloco.js +1 -0
  53. package/dist/platforms/playcraft.js +1 -0
  54. package/dist/platforms/remerge.js +1 -0
  55. package/dist/platforms/snapchat.js +1 -0
  56. package/dist/platforms/tiktok.js +1 -0
  57. package/dist/platforms/unity.js +1 -0
  58. package/dist/production-animation-presence.d.ts +2 -0
  59. package/dist/production-animation-presence.js +146 -0
  60. package/dist/production-inputs.d.ts +30 -0
  61. package/dist/production-inputs.js +262 -0
  62. package/dist/production-source-paths.d.ts +5 -0
  63. package/dist/production-source-paths.js +27 -0
  64. package/dist/types.d.ts +5 -0
  65. package/dist/validation/artifact.js +1 -1
  66. package/dist/validation/html-validator.d.ts +2 -0
  67. package/dist/validation/html-validator.js +16 -14
  68. package/dist/validation/package-validator.d.ts +2 -0
  69. package/dist/validation/package-validator.js +24 -15
  70. package/dist/validation/profiles.d.ts +13 -1
  71. package/dist/validation/profiles.js +27 -0
  72. package/dist/validation/types.d.ts +5 -0
  73. package/dist/validation/validation-runner.d.ts +11 -1
  74. package/dist/validation/validation-runner.js +37 -2
  75. package/dist/validation/zip-reader.d.ts +7 -1
  76. package/dist/validation/zip-reader.js +150 -25
  77. package/dist/vite/config-builder-generic.d.ts +3 -1
  78. package/dist/vite/config-builder-generic.js +9 -7
  79. package/dist/vite/config-builder.js +1 -1
  80. package/dist/vite/plugin-platform.js +30 -54
  81. package/dist/vite/plugin-source-builder.d.ts +2 -14
  82. package/dist/vite/plugin-source-builder.js +61 -997
  83. package/dist/vite/source-builder-asset-paths.d.ts +25 -0
  84. package/dist/vite/source-builder-asset-paths.js +154 -0
  85. package/dist/vite/source-builder-esm.d.ts +7 -0
  86. package/dist/vite/source-builder-esm.js +877 -0
  87. package/dist/vite/source-builder-types.d.ts +14 -0
  88. package/dist/vite/source-builder-types.js +1 -0
  89. package/dist/vite/workspace.d.ts +6 -0
  90. package/dist/vite/workspace.js +41 -0
  91. package/dist/vite-builder.d.ts +4 -5
  92. package/dist/vite-builder.js +33 -34
  93. package/dist/workspace-css-imports.d.ts +2 -0
  94. package/dist/workspace-css-imports.js +139 -0
  95. package/dist/workspace-model-source.d.ts +14 -0
  96. package/dist/workspace-model-source.js +184 -0
  97. package/dist/workspace-public-imports.d.ts +11 -0
  98. package/dist/workspace-public-imports.js +232 -0
  99. package/dist/workspace-public-source.d.ts +15 -0
  100. package/dist/workspace-public-source.js +564 -0
  101. package/package.json +15 -3
@@ -1,7 +1,49 @@
1
- import { inflateRawSync } from 'zlib';
1
+ import { inflateRawSync } from 'node:zlib';
2
+ const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
3
+ const MAX_ENTRY_BYTES = 64 * 1024 * 1024;
4
+ const MAX_TOTAL_BYTES = 128 * 1024 * 1024;
5
+ const MAX_ENTRIES = 4096;
6
+ const MAX_COMPRESSION_RATIO = 200;
7
+ const decoder = new TextDecoder('utf-8', { fatal: true });
8
+ function invalid(message) {
9
+ throw new Error(`Invalid ZIP: ${message}`);
10
+ }
11
+ function decode(bytes) {
12
+ try {
13
+ return decoder.decode(bytes);
14
+ }
15
+ catch {
16
+ invalid('entry filename is not valid UTF-8');
17
+ }
18
+ }
19
+ function validateEntryPath(value, directory) {
20
+ const member = directory ? value.slice(0, -1) : value;
21
+ if (!member ||
22
+ member.length > 1024 ||
23
+ member.includes('\0') ||
24
+ member.includes('\\') ||
25
+ member.startsWith('/') ||
26
+ /^[A-Za-z]:/.test(member) ||
27
+ member.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
28
+ invalid(`unsafe entry path: ${JSON.stringify(value)}`);
29
+ }
30
+ }
31
+ function crc32(bytes) {
32
+ let crc = 0xffffffff;
33
+ for (const byte of bytes) {
34
+ crc ^= byte;
35
+ for (let bit = 0; bit < 8; bit++) {
36
+ crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
37
+ }
38
+ }
39
+ return (crc ^ 0xffffffff) >>> 0;
40
+ }
41
+ /** Bounded ZIP reader used for both local reports and untrusted uploaded bytes. */
2
42
  export class SimpleZipReader {
3
43
  constructor(buffer) {
4
44
  this.buffer = buffer;
45
+ if (buffer.byteLength > MAX_ARCHIVE_BYTES)
46
+ invalid('archive exceeds the size limit');
5
47
  }
6
48
  listEntries() {
7
49
  return this.readCentralDirectory().map((entry) => ({
@@ -10,12 +52,16 @@ export class SimpleZipReader {
10
52
  uncompressedSize: entry.uncompressedSize,
11
53
  compressionMethod: entry.compressionMethod,
12
54
  isDirectory: entry.isDirectory,
55
+ externalAttributes: entry.externalAttributes,
56
+ creatorOs: entry.creatorOs,
57
+ encrypted: entry.encrypted,
58
+ crc32: entry.crc32,
13
59
  }));
14
60
  }
15
61
  readEntryText(entryPath) {
16
- return this.readEntryBuffer(entryPath)?.toString('utf-8') ?? null;
62
+ return this.readEntry(entryPath)?.toString('utf-8') ?? null;
17
63
  }
18
- readEntryBuffer(entryPath) {
64
+ readEntry(entryPath) {
19
65
  const entry = this.readCentralDirectory().find((item) => item.path === entryPath);
20
66
  if (!entry || entry.isDirectory)
21
67
  return null;
@@ -25,68 +71,147 @@ export class SimpleZipReader {
25
71
  if (this.entriesCache)
26
72
  return this.entriesCache;
27
73
  const eocdOffset = this.findEndOfCentralDirectory();
28
- if (eocdOffset < 0) {
29
- throw new Error('Invalid ZIP: end of central directory not found');
74
+ if (eocdOffset < 0)
75
+ invalid('end of central directory not found');
76
+ this.requireRange(eocdOffset, 22);
77
+ if (this.buffer.readUInt16LE(eocdOffset + 4) !== 0 ||
78
+ this.buffer.readUInt16LE(eocdOffset + 6) !== 0) {
79
+ invalid('multi-disk archives are not supported');
30
80
  }
31
81
  const totalEntries = this.buffer.readUInt16LE(eocdOffset + 10);
82
+ if (totalEntries !== this.buffer.readUInt16LE(eocdOffset + 8) || totalEntries > MAX_ENTRIES) {
83
+ invalid('entry count is inconsistent or exceeds the limit');
84
+ }
85
+ const centralDirectorySize = this.buffer.readUInt32LE(eocdOffset + 12);
32
86
  const centralDirectoryOffset = this.buffer.readUInt32LE(eocdOffset + 16);
87
+ if (centralDirectoryOffset === 0xffffffff ||
88
+ centralDirectorySize === 0xffffffff ||
89
+ centralDirectoryOffset + centralDirectorySize !== eocdOffset) {
90
+ invalid('ZIP64 or inconsistent central directory');
91
+ }
92
+ this.requireRange(centralDirectoryOffset, centralDirectorySize);
33
93
  const entries = [];
94
+ const exactPaths = new Set();
95
+ const foldedPaths = new Set();
34
96
  let offset = centralDirectoryOffset;
35
- for (let i = 0; i < totalEntries; i++) {
36
- const signature = this.buffer.readUInt32LE(offset);
37
- if (signature !== 0x02014b50) {
38
- throw new Error(`Invalid ZIP: bad central directory signature at ${offset}`);
97
+ let totalUncompressed = 0;
98
+ for (let index = 0; index < totalEntries; index++) {
99
+ this.requireRange(offset, 46);
100
+ if (this.buffer.readUInt32LE(offset) !== 0x02014b50) {
101
+ invalid(`bad central directory signature at ${offset}`);
39
102
  }
103
+ const creatorOs = this.buffer.readUInt8(offset + 5);
104
+ const flags = this.buffer.readUInt16LE(offset + 8);
40
105
  const compressionMethod = this.buffer.readUInt16LE(offset + 10);
106
+ const crc = this.buffer.readUInt32LE(offset + 16);
41
107
  const compressedSize = this.buffer.readUInt32LE(offset + 20);
42
108
  const uncompressedSize = this.buffer.readUInt32LE(offset + 24);
43
109
  const fileNameLength = this.buffer.readUInt16LE(offset + 28);
44
110
  const extraLength = this.buffer.readUInt16LE(offset + 30);
45
111
  const commentLength = this.buffer.readUInt16LE(offset + 32);
112
+ const externalAttributes = this.buffer.readUInt32LE(offset + 38);
46
113
  const localHeaderOffset = this.buffer.readUInt32LE(offset + 42);
47
- const fileNameStart = offset + 46;
48
- const entryPath = this.buffer
49
- .subarray(fileNameStart, fileNameStart + fileNameLength)
50
- .toString('utf-8')
51
- .replace(/\\/g, '/');
114
+ const entryLength = 46 + fileNameLength + extraLength + commentLength;
115
+ this.requireRange(offset, entryLength);
116
+ if (compressedSize === 0xffffffff ||
117
+ uncompressedSize === 0xffffffff ||
118
+ localHeaderOffset === 0xffffffff) {
119
+ invalid('ZIP64 entries are not supported');
120
+ }
121
+ const entryPath = decode(this.buffer.subarray(offset + 46, offset + 46 + fileNameLength));
122
+ const isDirectory = entryPath.endsWith('/');
123
+ validateEntryPath(entryPath, isDirectory);
124
+ const comparablePath = isDirectory ? entryPath.slice(0, -1) : entryPath;
125
+ const folded = comparablePath.normalize('NFC').toLowerCase();
126
+ if (exactPaths.has(comparablePath))
127
+ invalid(`duplicate entry path: ${comparablePath}`);
128
+ if (foldedPaths.has(folded))
129
+ invalid(`case-conflicting entry path: ${comparablePath}`);
130
+ exactPaths.add(comparablePath);
131
+ foldedPaths.add(folded);
132
+ const fileType = externalAttributes >>> 16;
133
+ if (!isDirectory && fileType !== 0 && (fileType & 0o170000) !== 0o100000) {
134
+ invalid(`entry is not a regular file: ${entryPath}`);
135
+ }
136
+ if (uncompressedSize > MAX_ENTRY_BYTES)
137
+ invalid(`entry exceeds the size limit: ${entryPath}`);
138
+ totalUncompressed += uncompressedSize;
139
+ if (totalUncompressed > MAX_TOTAL_BYTES)
140
+ invalid('total uncompressed size exceeds the limit');
141
+ if (uncompressedSize > 64 * 1024 &&
142
+ uncompressedSize / Math.max(1, compressedSize) > MAX_COMPRESSION_RATIO) {
143
+ invalid(`compression ratio exceeds the limit: ${entryPath}`);
144
+ }
52
145
  entries.push({
53
146
  path: entryPath,
54
147
  compressedSize,
55
148
  uncompressedSize,
56
149
  compressionMethod,
150
+ isDirectory,
151
+ externalAttributes,
152
+ creatorOs,
153
+ encrypted: (flags & 1) !== 0,
154
+ crc32: crc,
57
155
  localHeaderOffset,
58
- isDirectory: entryPath.endsWith('/'),
59
156
  });
60
- offset = fileNameStart + fileNameLength + extraLength + commentLength;
157
+ offset += entryLength;
61
158
  }
159
+ if (offset !== eocdOffset)
160
+ invalid('central directory size mismatch');
62
161
  this.entriesCache = entries;
63
162
  return entries;
64
163
  }
65
164
  readEntryData(entry) {
165
+ if (entry.encrypted)
166
+ invalid(`encrypted entry is not supported: ${entry.path}`);
167
+ if (entry.compressionMethod !== 0 && entry.compressionMethod !== 8) {
168
+ invalid(`unsupported compression method ${entry.compressionMethod}: ${entry.path}`);
169
+ }
66
170
  const offset = entry.localHeaderOffset;
67
- const signature = this.buffer.readUInt32LE(offset);
68
- if (signature !== 0x04034b50) {
69
- throw new Error(`Invalid ZIP: bad local header signature at ${offset}`);
171
+ this.requireRange(offset, 30);
172
+ if (this.buffer.readUInt32LE(offset) !== 0x04034b50) {
173
+ invalid(`bad local header signature at ${offset}`);
174
+ }
175
+ if (this.buffer.readUInt16LE(offset + 8) !== entry.compressionMethod) {
176
+ invalid(`local compression method differs: ${entry.path}`);
70
177
  }
71
178
  const fileNameLength = this.buffer.readUInt16LE(offset + 26);
72
179
  const extraLength = this.buffer.readUInt16LE(offset + 28);
180
+ this.requireRange(offset, 30 + fileNameLength + extraLength);
181
+ const localPath = decode(this.buffer.subarray(offset + 30, offset + 30 + fileNameLength));
182
+ if (localPath !== entry.path)
183
+ invalid(`local filename differs: ${entry.path}`);
73
184
  const dataStart = offset + 30 + fileNameLength + extraLength;
185
+ this.requireRange(dataStart, entry.compressedSize);
74
186
  const compressed = this.buffer.subarray(dataStart, dataStart + entry.compressedSize);
75
- if (entry.compressionMethod === 0) {
76
- return Buffer.from(compressed);
187
+ let data;
188
+ try {
189
+ data = entry.compressionMethod === 0
190
+ ? Buffer.from(compressed)
191
+ : inflateRawSync(compressed, { maxOutputLength: entry.uncompressedSize + 1 });
77
192
  }
78
- if (entry.compressionMethod === 8) {
79
- return inflateRawSync(compressed);
193
+ catch {
194
+ invalid(`entry cannot be inflated safely: ${entry.path}`);
80
195
  }
81
- throw new Error(`Unsupported ZIP compression method: ${entry.compressionMethod}`);
196
+ if (data.byteLength !== entry.uncompressedSize)
197
+ invalid(`entry size differs: ${entry.path}`);
198
+ if (crc32(data) !== entry.crc32)
199
+ invalid(`entry CRC differs: ${entry.path}`);
200
+ return data;
82
201
  }
83
202
  findEndOfCentralDirectory() {
84
203
  const minOffset = Math.max(0, this.buffer.length - 0xffff - 22);
85
204
  for (let offset = this.buffer.length - 22; offset >= minOffset; offset--) {
86
- if (this.buffer.readUInt32LE(offset) === 0x06054b50) {
205
+ if (this.buffer.readUInt32LE(offset) === 0x06054b50 &&
206
+ offset + 22 + this.buffer.readUInt16LE(offset + 20) === this.buffer.length) {
87
207
  return offset;
88
208
  }
89
209
  }
90
210
  return -1;
91
211
  }
212
+ requireRange(offset, length) {
213
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > this.buffer.length) {
214
+ invalid('truncated archive');
215
+ }
216
+ }
92
217
  }
@@ -1,5 +1,6 @@
1
1
  import { type UserConfig } from 'vite';
2
2
  import type { Platform, BuildOptions, BaseBuildMetadata } from '../types.js';
3
+ import { type ViteWorkspace } from './workspace.js';
3
4
  /**
4
5
  * 通用 Vite 配置构建器(外部引擎专用)
5
6
  *
@@ -16,9 +17,10 @@ export declare class GenericViteConfigBuilder {
16
17
  private platform;
17
18
  private options;
18
19
  private baseBuildMetadata;
20
+ private workspace?;
19
21
  private finalOutputDir;
20
22
  private viteOutputDir;
21
- constructor(baseBuildDir: string, platform: Platform, options: BuildOptions, baseBuildMetadata: BaseBuildMetadata);
23
+ constructor(baseBuildDir: string, platform: Platform, options: BuildOptions, baseBuildMetadata: BaseBuildMetadata, workspace?: ViteWorkspace | undefined);
22
24
  /**
23
25
  * 创建 Vite 配置
24
26
  */
@@ -1,4 +1,4 @@
1
- import { createLogger, defineConfig } from 'vite';
1
+ import { createLogger, defineConfig, } from 'vite';
2
2
  import path from 'path';
3
3
  import fs from 'fs';
4
4
  import { viteSingleFile } from 'vite-plugin-singlefile';
@@ -9,6 +9,7 @@ import imageminWebp from 'imagemin-webp';
9
9
  import { PLATFORM_CONFIGS } from './platform-configs.js';
10
10
  import { vitePlatformPlugin } from './plugin-platform.js';
11
11
  import { createPlatformAdapter } from '../platforms/index.js';
12
+ import { resolveViteWorkspace } from './workspace.js';
12
13
  /**
13
14
  * 通用 Vite 配置构建器(外部引擎专用)
14
15
  *
@@ -21,11 +22,12 @@ import { createPlatformAdapter } from '../platforms/index.js';
21
22
  * - viteImagemin:图片压缩
22
23
  */
23
24
  export class GenericViteConfigBuilder {
24
- constructor(baseBuildDir, platform, options, baseBuildMetadata) {
25
+ constructor(baseBuildDir, platform, options, baseBuildMetadata, workspace) {
25
26
  this.baseBuildDir = baseBuildDir;
26
27
  this.platform = platform;
27
28
  this.options = options;
28
29
  this.baseBuildMetadata = baseBuildMetadata;
30
+ this.workspace = workspace;
29
31
  this.finalOutputDir = '';
30
32
  this.viteOutputDir = '';
31
33
  // 统一规范化 baseBuildDir(与 ViteConfigBuilder 一致)
@@ -43,18 +45,18 @@ export class GenericViteConfigBuilder {
43
45
  const outputDir = this.options.outputDir || './dist';
44
46
  const playableOptions = this.getPlayableOptions(platformConfig);
45
47
  const rootDir = this.baseBuildDir;
46
- const viteOutputDir = '__dist__';
47
- const viteOutputDirAbsolute = path.join(rootDir, viteOutputDir);
48
- const finalOutputDir = path.isAbsolute(outputDir)
48
+ const workspace = this.workspace ? resolveViteWorkspace(rootDir, this.workspace) : undefined;
49
+ const viteOutputDirAbsolute = workspace?.intermediateDir ?? path.join(rootDir, '__dist__');
50
+ const finalOutputDir = workspace?.finalOutputDir ?? (path.isAbsolute(outputDir)
49
51
  ? outputDir
50
- : path.resolve(process.cwd(), outputDir);
52
+ : path.resolve(process.cwd(), outputDir));
51
53
  this.finalOutputDir = finalOutputDir;
52
54
  this.viteOutputDir = viteOutputDirAbsolute;
53
55
  console.log(`[GenericViteConfigBuilder] 路径配置:`);
54
56
  console.log(` - root: ${rootDir}`);
55
57
  console.log(` - viteOutputDir: ${viteOutputDirAbsolute}`);
56
58
  console.log(` - finalOutputDir: ${finalOutputDir}`);
57
- return this.createConfig(platformConfig, viteOutputDir, playableOptions, rootDir);
59
+ return this.createConfig(platformConfig, workspace ? viteOutputDirAbsolute : '__dist__', playableOptions, rootDir);
58
60
  }
59
61
  /**
60
62
  * 获取 Vite 的临时输出目录
@@ -1,4 +1,4 @@
1
- import { createLogger, defineConfig } from 'vite';
1
+ import { createLogger, defineConfig, } from 'vite';
2
2
  import path from 'path';
3
3
  import fs from 'fs';
4
4
  import { viteSingleFile } from 'vite-plugin-singlefile';
@@ -62,7 +62,7 @@ export function vitePlatformPlugin(options) {
62
62
  }
63
63
  if (options.outputFormat === 'zip') {
64
64
  // 等待 ZIP 创建完成
65
- await createZipOutput(options.outputDir, platformConfig.outputFileName);
65
+ await createZipOutput(options.outputDir);
66
66
  }
67
67
  },
68
68
  };
@@ -70,8 +70,8 @@ export function vitePlatformPlugin(options) {
70
70
  /**
71
71
  * 创建 ZIP 输出
72
72
  */
73
- function createZipOutput(outDir, htmlFileName) {
74
- return new Promise(async (resolve, reject) => {
73
+ function createZipOutput(outDir) {
74
+ return new Promise((resolve, reject) => {
75
75
  const zipPath = path.join(outDir, 'playable.zip');
76
76
  const output = createWriteStream(zipPath);
77
77
  const archive = archiver('zip', { zlib: { level: 9 } });
@@ -88,7 +88,7 @@ function createZipOutput(outDir, htmlFileName) {
88
88
  cwd: outDir,
89
89
  ignore: ['playable.zip'],
90
90
  });
91
- archive.finalize();
91
+ void archive.finalize().catch(reject);
92
92
  });
93
93
  }
94
94
  async function keepSingleHtml(outDir, htmlFileName) {
@@ -96,7 +96,7 @@ async function keepSingleHtml(outDir, htmlFileName) {
96
96
  try {
97
97
  entries = await fs.readdir(outDir, { withFileTypes: true });
98
98
  }
99
- catch (error) {
99
+ catch {
100
100
  return;
101
101
  }
102
102
  // 如果目标文件名不是 index.html,先重命名
@@ -107,7 +107,7 @@ async function keepSingleHtml(outDir, htmlFileName) {
107
107
  await fs.rename(indexPath, targetPath);
108
108
  console.log(`[Platform] 已重命名 index.html -> ${htmlFileName}`);
109
109
  }
110
- catch (error) {
110
+ catch {
111
111
  // index.html 可能不存在,忽略错误
112
112
  }
113
113
  }
@@ -147,7 +147,6 @@ async function applyExternFiles(outDir, externFiles) {
147
147
  const configFilename = `${folderName}/config.json`;
148
148
  await rewriteIndexHtml(outDir, assetPrefix, configFilename);
149
149
  await rewriteSettings(folderPath, assetPrefix, configFilename);
150
- await rewriteConfig(path.join(folderPath), folderPath, folderName);
151
150
  }
152
151
  async function rewriteIndexHtml(outDir, assetPrefix, configFilename) {
153
152
  const indexPath = path.join(outDir, 'index.html');
@@ -235,17 +234,7 @@ async function rewriteSettings(folderPath, assetPrefix, configFilename) {
235
234
  }
236
235
  await fs.writeFile(settingsPath, code);
237
236
  }
238
- catch (error) {
239
- // 忽略缺失
240
- }
241
- }
242
- async function rewriteConfig(configDir, _folderPath, _folderName) {
243
- // config.json 已移入资产文件夹,在此处可对其进行后处理
244
- const configPath = path.join(configDir, 'config.json');
245
- try {
246
- await fs.access(configPath);
247
- }
248
- catch (error) {
237
+ catch {
249
238
  // 忽略缺失
250
239
  }
251
240
  }
@@ -357,27 +346,25 @@ async function stripAmmoAssetsFromConfig(outDir) {
357
346
  try {
358
347
  const raw = await fs.readFile(configPath, 'utf-8');
359
348
  const configJson = JSON.parse(raw);
360
- if (!configJson.assets)
361
- return;
362
349
  const assets = configJson.assets;
350
+ if (!assets)
351
+ return;
363
352
  const ammoAssetIds = new Set();
364
353
  const ammoRelatedIds = new Set();
365
354
  // 找出所有 ammo 相关的 wasm assets 及其关联的 glue/fallback script
366
355
  for (const [id, asset] of Object.entries(assets)) {
367
- const a = asset;
368
- if (a.type === 'wasm' && a.data?.moduleName?.toLowerCase().includes('ammo')) {
356
+ if (asset.type === 'wasm' && asset.data?.moduleName?.toLowerCase().includes('ammo')) {
369
357
  ammoAssetIds.add(id);
370
- if (a.data.glueScriptId != null)
371
- ammoRelatedIds.add(String(a.data.glueScriptId));
372
- if (a.data.fallbackScriptId != null)
373
- ammoRelatedIds.add(String(a.data.fallbackScriptId));
358
+ if (asset.data.glueScriptId != null)
359
+ ammoRelatedIds.add(String(asset.data.glueScriptId));
360
+ if (asset.data.fallbackScriptId != null)
361
+ ammoRelatedIds.add(String(asset.data.fallbackScriptId));
374
362
  }
375
363
  }
376
364
  // 也检查 file.url 中包含 ammo 的 assets
377
365
  for (const [id, asset] of Object.entries(assets)) {
378
- const a = asset;
379
- const url = a.file?.url?.toLowerCase() || '';
380
- const name = (a.name || '').toLowerCase();
366
+ const url = asset.file?.url?.toLowerCase() || '';
367
+ const name = (asset.name || '').toLowerCase();
381
368
  if (url.includes('ammo') || name.includes('ammo')) {
382
369
  ammoRelatedIds.add(id);
383
370
  }
@@ -407,26 +394,9 @@ function isAmmoModule(module) {
407
394
  fallbackUrl.includes('ammo'));
408
395
  }
409
396
  async function applyMraidSupport(outDir) {
410
- // Note: We no longer patch fillMode to 'NONE' because it causes canvas scaling issues
411
- // The MRAID resize patch handles the sizing correctly with any fillMode
412
- // await patchConfigFillMode(outDir); // Removed: causes canvas scaling issues
397
+ // MRAID resize patch 会处理画布尺寸,不再修改 fillMode,避免缩放问题
413
398
  await patchStylesForMraid(outDir);
414
399
  }
415
- async function patchConfigFillMode(outDir) {
416
- const configPath = path.join(outDir, 'config.json');
417
- try {
418
- const raw = await fs.readFile(configPath, 'utf-8');
419
- const json = JSON.parse(raw);
420
- json.application_properties = {
421
- ...(json.application_properties || {}),
422
- fillMode: 'NONE',
423
- };
424
- await fs.writeFile(configPath, JSON.stringify(json));
425
- }
426
- catch (error) {
427
- // 忽略缺失
428
- }
429
- }
430
400
  async function patchStylesForMraid(outDir) {
431
401
  const cssPath = path.join(outDir, 'styles.css');
432
402
  try {
@@ -436,7 +406,7 @@ async function patchStylesForMraid(outDir) {
436
406
  await fs.writeFile(cssPath, css);
437
407
  }
438
408
  }
439
- catch (error) {
409
+ catch {
440
410
  // 忽略缺失
441
411
  }
442
412
  }
@@ -523,7 +493,7 @@ async function minifyJSFilesInDir(dir) {
523
493
  const ratio = originalSize > 0 ? ((saved / originalSize) * 100).toFixed(1) : '0';
524
494
  console.log(` ✓ ${relativePath}: ${(originalSize / 1024).toFixed(1)}KB → ${(minifiedSize / 1024).toFixed(1)}KB (-${ratio}%)`);
525
495
  }
526
- catch (error) {
496
+ catch {
527
497
  console.warn(` ⚠ ${path.relative(dir, filePath)}: 压缩失败,保留原文件`);
528
498
  }
529
499
  }
@@ -609,7 +579,7 @@ async function inlineUnsupportedAssetsIntoConfig(outDir) {
609
579
  console.warn(`[Platform] inlineUnsupportedAssets: 无法读取 config.json: ${error}`);
610
580
  return;
611
581
  }
612
- if (!configJson?.assets) {
582
+ if (!configJson.assets) {
613
583
  return;
614
584
  }
615
585
  const configDir = path.dirname(configPath);
@@ -623,7 +593,7 @@ async function inlineUnsupportedAssetsIntoConfig(outDir) {
623
593
  const url = file.url;
624
594
  if (url.startsWith('data:') || url.startsWith('http://') || url.startsWith('https://'))
625
595
  continue;
626
- const cleanUrl = url.split('?')[0];
596
+ const cleanUrl = url.split('?')[0] ?? url;
627
597
  // 检查此文件是否为 Google 不支持的类型
628
598
  if (isGoogleSupportedFile(cleanUrl))
629
599
  continue;
@@ -706,7 +676,9 @@ async function findConfigJson(outDir) {
706
676
  await fs.access(directPath);
707
677
  return directPath;
708
678
  }
709
- catch { }
679
+ catch {
680
+ // 根目录没有 config.json,继续搜索子目录
681
+ }
710
682
  // 在子目录中查找(externFiles 场景)
711
683
  const entries = await fs.readdir(outDir, { withFileTypes: true });
712
684
  for (const entry of entries) {
@@ -716,7 +688,9 @@ async function findConfigJson(outDir) {
716
688
  await fs.access(subPath);
717
689
  return subPath;
718
690
  }
719
- catch { }
691
+ catch {
692
+ // 继续尝试其他子目录
693
+ }
720
694
  }
721
695
  }
722
696
  return null;
@@ -732,7 +706,9 @@ async function cleanEmptyDirs(dir) {
732
706
  try {
733
707
  await fs.rmdir(fullPath);
734
708
  }
735
- catch { }
709
+ catch {
710
+ // 忽略删除失败
711
+ }
736
712
  }
737
713
  else {
738
714
  isEmpty = false;
@@ -1,18 +1,6 @@
1
+ import type { SourceBuilderPluginOptions } from './source-builder-types.js';
2
+ export type { SourceBuilderPluginOptions, UserScript } from './source-builder-types.js';
1
3
  import type { Plugin } from 'vite';
2
- import { type ImportMapAsset } from '../loaders/playcanvas-loader.js';
3
- export interface SourceBuilderPluginOptions {
4
- projectDir: string;
5
- outputDir: string;
6
- selectedScenes?: string[];
7
- buildMode?: 'classic' | 'esm';
8
- importMap?: ImportMapAsset;
9
- }
10
- export interface UserScript {
11
- id: string;
12
- path: string;
13
- code: string;
14
- name: string;
15
- }
16
4
  /**
17
5
  * Vite 插件:从源代码构建 PlayCanvas 项目
18
6
  */