@playcraft/devkit 1.0.27 → 1.0.29

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 (55) hide show
  1. package/cli/bin/playable-scripts.js +6 -44
  2. package/cli/commands/build.js +41 -170
  3. package/cli/commands/builds.js +2 -13
  4. package/cli/commands/dev.js +1 -7
  5. package/cli/commands/pack.js +39 -308
  6. package/cli/commands/vite-dev.js +1 -7
  7. package/core/batch-build.js +185 -1121
  8. package/core/constants.js +2 -16
  9. package/core/cos-uploader.js +24 -286
  10. package/core/index.d.ts +12 -5
  11. package/core/index.js +7 -76
  12. package/core/loaders/gltf-loader.js +28 -74
  13. package/core/options.js +15 -310
  14. package/core/plugins/AdikteevInjectorPlugin.js +4 -26
  15. package/core/plugins/BigoAdsInjectorPlugin.js +4 -21
  16. package/core/plugins/DAPIInjectorPlugin.js +2 -25
  17. package/core/plugins/DebuggerInjectionPlugin.js +3 -31
  18. package/core/plugins/ExitAPIInjectorPlugin.js +4 -58
  19. package/core/plugins/FflateCompressionPlugin.js +40 -231
  20. package/core/plugins/FontInjectionWebpackPlugin.js +4 -46
  21. package/core/plugins/LiftoffInjectorPlugin.js +4 -26
  22. package/core/plugins/MRAIDInjectorPlugin.js +2 -24
  23. package/core/plugins/MintegralInjectorPlugin.js +2 -25
  24. package/core/plugins/PangleInjectorPlugin.js +2 -24
  25. package/core/plugins/PlaycraftOrientationInjectorPlugin.js +7 -0
  26. package/core/plugins/SnapchatInjectorPlugin.js +4 -26
  27. package/core/plugins/SocialMediaInjectorPlugin.js +7 -119
  28. package/core/plugins/TikTokInjectorPlugin.js +2 -24
  29. package/core/plugins/UnityInjectorPlugin.js +8 -37
  30. package/core/plugins/ZipPlugin.js +20 -138
  31. package/core/plugins/socialMediaVitePlugin.js +2 -108
  32. package/core/utils/buildDefines.js +3 -29
  33. package/core/utils/buildTemplateString.js +5 -40
  34. package/core/utils/date.js +1 -16
  35. package/core/utils/fontRegistry.js +13 -81
  36. package/core/utils/fontResolver.js +37 -335
  37. package/core/utils/generateAdikteevHtmlWebpackPluginConfig.js +7 -42
  38. package/core/utils/generateBigabidHtmlWebpackPluginConfig.js +3 -30
  39. package/core/utils/generateInMobiHtmlWebpackPluginConfig.js +7 -43
  40. package/core/utils/getPlaycraftOrientationSuffix.js +6 -0
  41. package/core/utils/injectSDKPlugins.js +14 -69
  42. package/core/utils/logOptions.js +5 -37
  43. package/core/utils/mergeOptions.js +2 -19
  44. package/core/utils/parseArgvOptions.js +5 -111
  45. package/core/utils/resolveChannelFold2Zip.js +5 -17
  46. package/core/utils/validateThemeData.js +26 -227
  47. package/core/validators/pre-build-checker.js +26 -286
  48. package/core/validators/tracking-validator.js +40 -358
  49. package/core/vite.dev.js +17 -322
  50. package/core/webpack.build.js +65 -489
  51. package/core/webpack.common.js +11 -177
  52. package/core/webpack.dev.js +6 -82
  53. package/defines.d.ts +2 -1
  54. package/package.json +3 -4
  55. package/README.md +0 -262
@@ -1,504 +1,80 @@
1
- const { merge } = require('webpack-merge');
2
- const { webpackCommonConfig } = require('./webpack.common.js');
3
- const webpack = require('webpack');
4
- const TerserPlugin = require('terser-webpack-plugin');
5
- const CopyWebpackPlugin = require('copy-webpack-plugin');
6
- const HtmlInlineScriptPlugin = require('html-inline-script-webpack-plugin');
7
- const HtmlWebpackPlugin = require('html-webpack-plugin');
8
- const MiniCssExtractPlugin = require('mini-css-extract-plugin');
9
- const { ZipPlugin } = require('./plugins/ZipPlugin.js');
10
- const { FflateCompressionPlugin } = require('./plugins/FflateCompressionPlugin.js');
11
- const { generateAdikteevHtmlWebpackPluginConfig } = require('./utils/generateAdikteevHtmlWebpackPluginConfig.js');
12
- const { generateBigabidHtmlWebpackPluginConfig } = require('./utils/generateBigabidHtmlWebpackPluginConfig.js');
13
- const { generateInMobiHtmlWebpackPluginConfig } = require('./utils/generateInMobiHtmlWebpackPluginConfig.js');
14
- const path = require('path');
15
- const { mergeOptions } = require('./utils/mergeOptions.js');
16
- const { options } = require('./options.js');
17
- const { buildDefines } = require('./utils/buildDefines.js');
18
- const { buildTemplateString } = require('./utils/buildTemplateString.js');
19
- const { logOptions } = require('./utils/logOptions.js');
20
- const { injectSDKPlugins } = require('./utils/injectSDKPlugins.js');
21
- const { resolveChannelFold2Zip } = require('./utils/resolveChannelFold2Zip.js');
22
-
23
-
24
- const META = {
25
- COMMON_CHARSET: 'utf-8',
26
- COMMON_VIEWPORT: 'width=device-width,initial-scale=1.0,viewport-fit=cover,maximum-scale=1.0,user-scalable=no',
27
- MINTEGRAL_VIEWPORT: 'width=device-width,user-scalable=no,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0',
28
- };
29
-
30
- const FontFamily = {
31
- LIFTOFF: '<style>body{font-family:Roboto,"Helvetica Neue",-apple-system,BlinkMacSystemFont,sans-serif}</style>',
32
- };
33
-
34
- /**
1
+ "use strict";const{merge}=require("webpack-merge");const{webpackCommonConfig}=require("./webpack.common.js");const webpack=require("webpack");const TerserPlugin=require("terser-webpack-plugin");const CopyWebpackPlugin=require("copy-webpack-plugin");const HtmlInlineScriptPlugin=require("html-inline-script-webpack-plugin");const HtmlWebpackPlugin=require("html-webpack-plugin");const MiniCssExtractPlugin=require("mini-css-extract-plugin");const{ZipPlugin}=require("./plugins/ZipPlugin.js");const{FflateCompressionPlugin}=require("./plugins/FflateCompressionPlugin.js");const{generateAdikteevHtmlWebpackPluginConfig}=require("./utils/generateAdikteevHtmlWebpackPluginConfig.js");const{generateBigabidHtmlWebpackPluginConfig}=require("./utils/generateBigabidHtmlWebpackPluginConfig.js");const{generateInMobiHtmlWebpackPluginConfig}=require("./utils/generateInMobiHtmlWebpackPluginConfig.js");const path=require("path");const{mergeOptions}=require("./utils/mergeOptions.js");const{options}=require("./options.js");const{buildDefines}=require("./utils/buildDefines.js");const{buildTemplateString}=require("./utils/buildTemplateString.js");const{logOptions}=require("./utils/logOptions.js");const{injectSDKPlugins}=require("./utils/injectSDKPlugins.js");const{resolveChannelFold2Zip}=require("./utils/resolveChannelFold2Zip.js");const{getPlaycraftOrientationSuffix}=require("./utils/getPlaycraftOrientationSuffix.js");const{PlaycraftOrientationInjectorPlugin}=require("./plugins/PlaycraftOrientationInjectorPlugin.js");const META={COMMON_CHARSET:"utf-8",COMMON_VIEWPORT:"width=device-width,initial-scale=1.0,viewport-fit=cover,maximum-scale=1.0,user-scalable=no",MINTEGRAL_VIEWPORT:"width=device-width,user-scalable=no,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0"};const FontFamily={LIFTOFF:"<style>body{font-family:Roboto,\"Helvetica Neue\",-apple-system,BlinkMacSystemFont,sans-serif}</style>"};/**
35
2
  * HtmlWebpackPlugin beforeEmit 钩子。
36
3
  * 在最终 HTML 输出前统一修正 meta 标签:
37
4
  * - charset → 统一小写 utf-8
38
5
  * - viewport → 统一替换为渠道通道规范值
39
6
  * 项目模板无需关心 meta 标签,全部由 devkit 构建时自动处理。
40
- */
41
- class MetaTagOverridePlugin {
42
- constructor(adNetwork) {
43
- this.adNetwork = adNetwork;
44
- }
45
-
46
- apply(compiler) {
47
- compiler.hooks.compilation.tap('MetaTagOverridePlugin', (compilation) => {
48
- HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tap('MetaTagOverridePlugin', (data) => {
49
- // charset: 统一小写
50
- data.html = data.html.replace(/<meta\s+charset=["'][^"']*["']\s*\/?>/i, '<meta charset="utf-8" />');
51
- // viewport: Mintegral 需要 minimum-scale,其他渠道通用
52
- const viewportContent = this.adNetwork === 'mintegral'
53
- ? META.MINTEGRAL_VIEWPORT
54
- : META.COMMON_VIEWPORT;
55
- data.html = data.html.replace(
56
- /<meta\s+name=["']viewport["'][^>]*\/?>/i,
57
- `<meta name="viewport" content="${viewportContent}" />`
58
- );
59
- // font-family: Liftoff 渠道需要指定系统字体
60
- if (this.adNetwork === 'liftoff') {
61
- const fontStyle = FontFamily.LIFTOFF;
62
- data.html = data.html.replace('</head>', fontStyle + '</head>');
63
- }
64
-
65
- return data;
66
- });
67
- });
68
- }
69
- }
70
-
71
- /** @type {AD_NETWORK[]} */
72
- /** @type {AD_NETWORK[]} */
73
- const zipOutputNetworks = [
74
- 'google',
75
- 'pangle',
76
- 'tiktok',
77
- 'vungle',
78
- 'mytarget',
79
- 'mintegral',
80
- 'adikteev',
81
- 'bigabid',
82
- 'inmobi', // InMobi 支持 ZIP 格式(包含 index.html + 资源文件)
83
- 'snapchat',
84
- 'bigoads',
85
- 'liftoff'
86
- ];
87
- /** @type {AD_NETWORK[]} */
88
- const zipOutputAllowedNetworks = ['facebook', 'moloco'];
89
-
90
- /**
7
+ */class MetaTagOverridePlugin{constructor(adNetwork){this.adNetwork=adNetwork}apply(compiler){compiler.hooks.compilation.tap("MetaTagOverridePlugin",compilation=>{HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tap("MetaTagOverridePlugin",data=>{// charset: 统一小写
8
+ data.html=data.html.replace(/<meta\s+charset=["'][^"']*["']\s*\/?>/i,"<meta charset=\"utf-8\" />");// viewport: Mintegral 需要 minimum-scale,其他渠道通用
9
+ const viewportContent=this.adNetwork==="mintegral"?META.MINTEGRAL_VIEWPORT:META.COMMON_VIEWPORT;data.html=data.html.replace(/<meta\s+name=["']viewport["'][^>]*\/?>/i,`<meta name="viewport" content="${viewportContent}" />`);// font-family: Liftoff 渠道需要指定系统字体
10
+ if(this.adNetwork==="liftoff"){const fontStyle=FontFamily.LIFTOFF;data.html=data.html.replace("</head>",fontStyle+"</head>")}return data})})}}/** @type {AD_NETWORK[]} *//** @type {AD_NETWORK[]} */const zipOutputNetworks=["google","pangle","tiktok","vungle","mytarget","mintegral","adikteev","bigabid","inmobi",// InMobi 支持 ZIP 格式(包含 index.html + 资源文件)
11
+ "snapchat","bigoads","liftoff","facebook",// Facebook 默认 ZIP,包体上限 5MB
12
+ "remerge"// Remerge Rich Media:ZIP + index.html + mraid.js
13
+ ];/** @type {AD_NETWORK[]} */const zipOutputAllowedNetworks=["moloco"];/**
91
14
  * Creates webpack configuration for production build
92
15
  * @param {Partial<import('./index').CLIOptions>} [customOptions] - Custom options to merge with default options
93
16
  * @param {Record<string, any>} [customDefines] - Additional defines for webpack.DefinePlugin
94
17
  * @param {import('webpack').Configuration} [webpackCustomConfig] - Custom webpack config to merge
95
18
  * @returns {import('webpack').Configuration} Final webpack production configuration
96
- */
97
- function makeWebpackBuildConfig(customOptions, customDefines, webpackCustomConfig) {
98
- const buildOptions = mergeOptions(options, customOptions);
99
- logOptions(buildOptions);
100
- customDefines = customDefines || {};
101
- webpackCustomConfig = webpackCustomConfig || {};
102
-
103
- /** @type {AD_NETWORK} */
104
- const adNetwork = buildOptions['network'];
105
-
106
- /** @type {AD_PROTOCOL} */
107
- const adProtocol = buildOptions['protocol'];
108
-
109
- let outDir = buildTemplateString(buildOptions.outDir, buildOptions);
110
-
111
- function getFileName() {
112
- let filename = buildTemplateString(buildOptions.filename, buildOptions);
113
-
114
- if (adNetwork === 'mintegral') return filename.replace(/\s+/g, '').replace(/[^a-zA-Z0-9]/g, '_').replace('_fullhash_6_', '[fullhash:6]');
115
- return filename;
116
- }
117
-
118
- const isZipOutput =
119
- zipOutputNetworks.includes(adNetwork) || (buildOptions.zip && zipOutputAllowedNetworks.includes(adNetwork));
120
-
121
- const { isChannelFold2Zip, isZipOutputFinal } = resolveChannelFold2Zip({
122
- isChannelFold2ZipOption: buildOptions.isChannelFold2Zip,
123
- adNetwork,
124
- isZipOutput
125
- });
126
-
127
- let htmlFileName = '';
128
- if (adNetwork === 'mintegral') htmlFileName = 'index.html'; // 修改为 index.html
129
- else if (isZipOutputFinal) htmlFileName = 'index.html';
130
- else htmlFileName = `${getFileName()}.html`;
131
-
132
- const metaTags = {
133
- viewport: META.COMMON_VIEWPORT,
134
- };
135
-
136
- if (adNetwork === 'mintegral') {
137
- metaTags['viewport'] = META.MINTEGRAL_VIEWPORT;
138
- }
139
-
140
- if (!buildOptions.skipRecommendedMeta) {
141
- metaTags['HandheldFriendly'] = 'True';
142
- metaTags['cleartype'] = { 'http-equiv': 'cleartype', content: 'on' };
143
- metaTags['apple-mobile-web-app-capable'] = 'yes';
144
- metaTags['mobile-web-app-capable'] = 'yes';
145
- metaTags['X-UA-Compatible'] = { 'http-equiv': 'X-UA-Compatible', content: 'IE=10' };
146
- }
147
-
148
- let htmlWebpackPluginConfig = {
149
- template: path.resolve('src/index.html'),
150
- filename: htmlFileName,
151
- title: `${buildOptions.name} - ${buildOptions.app}`,
152
- inlineSource: '.(js|css|png|jpg|webp|svg|xml|atlas|mp3|gif|glb|fbx|obj)$',
153
- meta: metaTags
154
- };
155
-
156
- if (adNetwork === 'adikteev') htmlWebpackPluginConfig = generateAdikteevHtmlWebpackPluginConfig('src/index.html');
157
- else if (adNetwork === 'bigabid') htmlWebpackPluginConfig = generateBigabidHtmlWebpackPluginConfig('src/index.html');
158
- else if (adNetwork === 'inmobi')
159
- htmlWebpackPluginConfig = generateInMobiHtmlWebpackPluginConfig('src/index.html', buildOptions);
160
-
161
- const webpackConfig = merge(
162
- webpackCommonConfig,
163
- {
164
- mode: 'production',
165
- stats: 'errors-only',
166
- optimization: {
167
- usedExports: true,
168
- minimize: (buildOptions.obfuscateLevel !== undefined ? buildOptions.obfuscateLevel : 2) >= 1,
169
- minimizer: [
170
- new TerserPlugin({
171
- extractComments: false,
172
- terserOptions: {
173
- safari10: true,
174
- mangle: {
175
- reserved: ['$'],
176
- // ⚠️ 不要开启 properties: true,会混淆 Phaser 等框架的属性名导致运行时错误
177
- // properties: true,
178
- toplevel: true
179
- },
180
- compress: {
181
- drop_console: true,
182
- arrows: false,
183
- drop_debugger: true,
184
- unused: true,
185
- dead_code: true,
186
- // 🔥 增加优化轮数
187
- passes: 3,
188
- // 🔥 激进压缩选项
189
- inline: 3, // 最大内联
190
- collapse_vars: true, // 折叠变量
191
- reduce_vars: true, // 减少变量
192
- hoist_vars: true, // 提升变量
193
- hoist_funs: true, // 提升函数
194
- sequences: 20, // 更长的序列化
195
- properties: true, // 优化属性访问
196
- conditionals: true, // 优化条件
197
- comparisons: true, // 优化比较
198
- booleans: true, // 优化布尔
199
- loops: true, // 优化循环
200
- if_return: true, // 优化 if-return
201
- join_vars: true, // 合并变量
202
- negate_iife: true, // 否定 IIFE
203
- side_effects: true, // 移除副作用
204
- switches: true, // 优化 switch
205
- typeofs: true, // 优化 typeof
206
- unsafe: false, // 不使用 unsafe(避免破坏框架)
207
- keep_fargs: false, // 移除未使用参数
208
- drop_console: true
209
- },
210
- output: {
211
- comments: false,
212
- quote_style: 3,
213
- beautify: false,
214
- wrap_iife: true,
215
- ecma: 2015
216
- },
217
- toplevel: true,
218
- keep_classnames: false,
219
- keep_fnames: false
220
- }
221
- })
222
- ]
223
- },
224
- plugins: [
225
- new HtmlWebpackPlugin(htmlWebpackPluginConfig),
226
- new MetaTagOverridePlugin(adNetwork),
227
-
228
- new webpack.DefinePlugin({
229
- ...buildDefines(),
230
- ...buildOptions.defines,
231
- ...customDefines
232
- }),
233
-
234
- // For some reason needed for PIXI v8
235
- new webpack.optimize.LimitChunkCountPlugin({
236
- maxChunks: 1
237
- })
238
- ]
239
- },
240
- webpackCustomConfig
241
- );
242
-
243
- webpackConfig.output.path = path.resolve(outDir);
244
-
245
- // 根据混淆等级注入 obfuscator loader
246
- const obfuscateLevel = buildOptions.obfuscateLevel !== undefined ? buildOptions.obfuscateLevel : 2;
247
-
248
- // 获取需要排除压缩的目录列表
249
- const excludeCompressDirs = buildOptions.excludeCompressDirs || [];
250
-
251
- if (obfuscateLevel >= 2) {
252
- // 构建各等级的 obfuscator 配置
253
- const obfuscatorOptions = {
254
- // 通用基础配置
255
- target: 'browser',
256
- sourceMap: false,
257
- selfDefending: false,
258
- renameProperties: false,
259
- disableConsoleOutput: true,
260
- splitStrings: false,
261
- unicodeEscapeSequence: false
262
- };
263
-
264
- if (obfuscateLevel === 2) {
265
- // 等级2:基础混淆(控制流平坦化 + 字符串数组)
266
- Object.assign(obfuscatorOptions, {
267
- controlFlowFlattening: true,
268
- controlFlowFlatteningThreshold: 0.75,
269
- deadCodeInjection: false,
270
- stringArray: true,
271
- stringArrayThreshold: 0.75,
272
- stringArrayEncoding: ['base64'],
273
- stringArrayIndexShift: true,
274
- stringArrayRotate: true,
275
- stringArrayShuffle: true,
276
- stringArrayWrappersCount: 2,
277
- stringArrayWrappersChainedCalls: true,
278
- stringArrayWrappersType: 'function',
279
- stringArrayCallsTransform: true,
280
- stringArrayCallsTransformThreshold: 0.75,
281
- transformObjectKeys: true,
282
- identifierNamesGenerator: 'hexadecimal'
283
- });
284
- } else if (obfuscateLevel === 3) {
285
- // 等级3:在等级2基础上增加死代码注入
286
- Object.assign(obfuscatorOptions, {
287
- controlFlowFlattening: true,
288
- controlFlowFlatteningThreshold: 0.75,
289
- deadCodeInjection: true,
290
- deadCodeInjectionThreshold: 0.4,
291
- stringArray: true,
292
- stringArrayThreshold: 0.75,
293
- stringArrayEncoding: ['base64'],
294
- stringArrayIndexShift: true,
295
- stringArrayRotate: true,
296
- stringArrayShuffle: true,
297
- stringArrayWrappersCount: 2,
298
- stringArrayWrappersChainedCalls: true,
299
- stringArrayWrappersType: 'function',
300
- stringArrayCallsTransform: true,
301
- stringArrayCallsTransformThreshold: 0.75,
302
- transformObjectKeys: true,
303
- identifierNamesGenerator: 'hexadecimal'
304
- });
305
- } else if (obfuscateLevel === 4) {
306
- // 等级4:最高强度混淆
307
- Object.assign(obfuscatorOptions, {
308
- controlFlowFlattening: true,
309
- controlFlowFlatteningThreshold: 1,
310
- deadCodeInjection: true,
311
- deadCodeInjectionThreshold: 0.5,
312
- stringArray: true,
313
- stringArrayThreshold: 1,
314
- stringArrayEncoding: ['rc4'],
315
- stringArrayIndexShift: true,
316
- stringArrayRotate: true,
317
- stringArrayShuffle: true,
318
- stringArrayWrappersCount: 3,
319
- stringArrayWrappersChainedCalls: true,
320
- stringArrayWrappersType: 'function',
321
- stringArrayCallsTransform: true,
322
- stringArrayCallsTransformThreshold: 1,
323
- transformObjectKeys: true,
324
- identifierNamesGenerator: 'hexadecimal',
325
- splitStrings: true,
326
- splitStringsChunkLength: 5,
327
- unicodeEscapeSequence: true,
328
- });
329
- }
330
-
331
- console.log(`Obfuscation level: ${obfuscateLevel} (${['', 'terser-only', 'basic', 'dead-code', 'maximum'][obfuscateLevel]})`);
332
-
333
- // 构建exclude数组,包含node_modules和用户指定的排除目录
334
- const excludePatterns = [];
335
- if (excludeCompressDirs.length > 0) {
336
- excludeCompressDirs.forEach(dir => {
337
- excludePatterns.push(path.resolve(dir));
338
- });
339
- console.log(`ℹ️ Excluding directories from compression: ${excludeCompressDirs.join(', ')}`);
340
- }
341
-
342
- webpackConfig.module.rules.push({
343
- test: /\.(js|ts)$/,
344
- include: [path.resolve('src')],
345
- exclude: excludePatterns,
346
- enforce: 'post',
347
- use: {
348
- loader: require.resolve('webpack-obfuscator/dist/loader'),
349
- options: obfuscatorOptions
350
- }
351
- });
352
- } else if (obfuscateLevel === 1) {
353
- console.log('Obfuscation level: 1 (terser-only)');
354
- } else {
355
- console.log('Obfuscation level: 0 (no minimize/obfuscate)');
356
- }
357
-
358
- // Adikteev 需要单独提取 CSS 为 style.css,替换默认的 style-loader
359
- if (adNetwork === 'adikteev') {
360
- const cssRuleIndex = webpackConfig.module.rules.findIndex(rule =>
361
- rule.test && rule.test.toString().includes('\\.css')
362
- );
363
-
364
- if (cssRuleIndex !== -1) {
365
- webpackConfig.module.rules[cssRuleIndex] = {
366
- test: /\.css$/,
367
- use: [MiniCssExtractPlugin.loader, 'css-loader']
368
- };
369
- console.log('✅ Adikteev: CSS will be extracted to style.css');
370
- }
371
- }
372
-
373
- // 决定是否内联 JS 到 HTML
374
- // 以下渠道需要分离 JS 文件,不使用 HtmlInlineScriptPlugin:
375
- // - mintegral: 需要独立的 JS 文件
376
- // - adikteev: 需要 creative.js 上传到 CDN
377
- // - bigabid: 需要 main.js 上传到 CDN
378
- // - facebook (ZIP 模式): Facebook ZIP 格式需要分离文件
379
- if (
380
- adNetwork !== 'mintegral' &&
381
- adNetwork !== 'adikteev' &&
382
- adNetwork !== 'bigabid' &&
383
- !(isZipOutputFinal && adNetwork === 'facebook')
384
- )
385
- webpackConfig.plugins.push(new HtmlInlineScriptPlugin());
386
-
387
- // 注入渠道 SDK 插件(公共逻辑)
388
- injectSDKPlugins(webpackConfig, {
389
- network: adNetwork,
390
- protocol: adProtocol,
391
- orientation: buildOptions.orientation
392
- });
393
-
394
- if (isZipOutputFinal) {
395
- if (adNetwork === 'tiktok') {
396
- webpackConfig.plugins.push(
397
- new CopyWebpackPlugin({
398
- patterns: [{ from: path.join(__dirname, 'resources', 'tiktok-config.json'), to: 'config.json' }]
399
- })
400
- );
401
- } else if (adNetwork === 'snapchat') {
402
- const tmpConfigPath = path.join(__dirname, 'resources', 'snapchat-config.json');
403
-
404
- webpackConfig.plugins.push(
405
- new CopyWebpackPlugin({
406
- patterns: [{ from: tmpConfigPath, to: 'config.json' }]
407
- })
408
- );
409
- } else if (adNetwork === 'bigoads') {
410
- // BigoAds 要求输出 ZIP 包,包含 index.html 和 config.json
411
- // SDK 注入已在 injectSDKPlugins 中处理
412
- webpackConfig.plugins.push(
413
- new CopyWebpackPlugin({
414
- patterns: [{ from: path.join(__dirname, 'resources', 'bigoads-config.json'), to: 'config.json' }]
415
- })
416
- );
417
- }
418
-
419
- webpackConfig.plugins.push(
420
- new ZipPlugin({
421
- filename: isChannelFold2Zip ? adNetwork : getFileName(),
422
- path: path.resolve(outDir),
423
- cleanTempFolder: true // 🗑️ 生成 zip 后删除临时文件夹
424
- })
425
- );
426
-
427
- webpackConfig.output.path = path.resolve(outDir, adNetwork);
428
- if (adNetwork === 'adikteev') {
429
- webpackConfig.output.filename = 'creative.js';
430
- // Adikteev 需要将 CSS 单独提取为 style.css 文件
431
- webpackConfig.plugins.push(
432
- new MiniCssExtractPlugin({
433
- filename: 'style.css'
434
- })
435
- );
436
- } else if (adNetwork === 'bigabid') webpackConfig.output.filename = 'main.js';
437
- else if (adNetwork === 'inmobi') webpackConfig.output.filename = 'main.js';
438
- }
439
-
440
- // 添加 fflate 压缩插件(仅在打正式包时生效)
441
- if (buildOptions.fflateCompression) {
442
- console.log('✅ fflate compression enabled (production build only)');
443
- webpackConfig.plugins.push(
444
- new FflateCompressionPlugin({
445
- enabled: true,
446
- level: 9,
447
- keepOriginal: false,
448
- logStats: true,
449
- googlePlayUrl: buildOptions.googlePlayUrl,
450
- appStoreUrl: buildOptions.appStoreUrl,
451
- })
452
- );
453
- }
454
-
455
- return webpackConfig;
456
- }
457
-
458
- /**
19
+ */function makeWebpackBuildConfig(customOptions,customDefines,webpackCustomConfig){const buildOptions=mergeOptions(options,customOptions);logOptions(buildOptions);customDefines=customDefines||{};webpackCustomConfig=webpackCustomConfig||{};/** @type {AD_NETWORK} */const adNetwork=buildOptions["network"];/** @type {AD_PROTOCOL} */const adProtocol=buildOptions["protocol"];/** @type {'both'|'landscape'|'portrait'} 当前单次构建实际使用的横竖屏方向版本,默认 'both' */const playcraftOrientationValue=buildOptions.playcraftOrientationValue||"both";/** @type {string} 方向版本对应的命名后缀:landscape→'_L',portrait→'_P',both→'' */const orientationSuffix=getPlaycraftOrientationSuffix(playcraftOrientationValue);/** @type {string} 渠道 + 方向后缀组成的产物标识,如 'google_L' */const outputId=`${adNetwork}${orientationSuffix}`;let outDir=buildTemplateString(buildOptions.outDir,buildOptions);function getFileName(){let filename=buildTemplateString(buildOptions.filename,buildOptions);if(adNetwork==="mintegral")return filename.replace(/\s+/g,"").replace(/[^a-zA-Z0-9]/g,"_").replace("_fullhash_6_","[fullhash:6]");return filename}const isZipOutput=zipOutputNetworks.includes(adNetwork)||buildOptions.zip&&zipOutputAllowedNetworks.includes(adNetwork);const{isChannelFold2Zip,isZipOutputFinal}=resolveChannelFold2Zip({isChannelFold2ZipOption:buildOptions.isChannelFold2Zip,adNetwork,isZipOutput});let htmlFileName="";if(adNetwork==="mintegral")htmlFileName="index.html";// 修改为 index.html
20
+ else if(isZipOutputFinal)htmlFileName="index.html";else htmlFileName=`${getFileName()}.html`;const metaTags={viewport:META.COMMON_VIEWPORT};if(adNetwork==="mintegral"){metaTags["viewport"]=META.MINTEGRAL_VIEWPORT}if(!buildOptions.skipRecommendedMeta){metaTags["HandheldFriendly"]="True";metaTags["cleartype"]={"http-equiv":"cleartype",content:"on"};metaTags["apple-mobile-web-app-capable"]="yes";metaTags["mobile-web-app-capable"]="yes";metaTags["X-UA-Compatible"]={"http-equiv":"X-UA-Compatible",content:"IE=10"}}let htmlWebpackPluginConfig={template:path.resolve("src/index.html"),filename:htmlFileName,title:`${buildOptions.name} - ${buildOptions.app}`,inlineSource:".(js|css|png|jpg|webp|svg|xml|atlas|mp3|gif|glb|fbx|obj)$",meta:metaTags};if(adNetwork==="adikteev")htmlWebpackPluginConfig=generateAdikteevHtmlWebpackPluginConfig("src/index.html");else if(adNetwork==="bigabid")htmlWebpackPluginConfig=generateBigabidHtmlWebpackPluginConfig("src/index.html");else if(adNetwork==="inmobi")htmlWebpackPluginConfig=generateInMobiHtmlWebpackPluginConfig("src/index.html",buildOptions);const webpackConfig=merge(webpackCommonConfig,{mode:"production",stats:"errors-only",optimization:{usedExports:true,minimize:(buildOptions.obfuscateLevel!==undefined?buildOptions.obfuscateLevel:2)>=1,minimizer:[new TerserPlugin({extractComments:false,terserOptions:{safari10:true,mangle:{reserved:["$"],// ⚠️ 不要开启 properties: true,会混淆 Phaser 等框架的属性名导致运行时错误
21
+ // properties: true,
22
+ toplevel:true},compress:{drop_console:true,arrows:false,drop_debugger:true,unused:true,dead_code:true,// 🔥 增加优化轮数
23
+ passes:3,// 🔥 激进压缩选项
24
+ inline:3,// 最大内联
25
+ collapse_vars:true,// 折叠变量
26
+ reduce_vars:true,// 减少变量
27
+ hoist_vars:true,// 提升变量
28
+ hoist_funs:true,// 提升函数
29
+ sequences:20,// 更长的序列化
30
+ properties:true,// 优化属性访问
31
+ conditionals:true,// 优化条件
32
+ comparisons:true,// 优化比较
33
+ booleans:true,// 优化布尔
34
+ loops:true,// 优化循环
35
+ if_return:true,// 优化 if-return
36
+ join_vars:true,// 合并变量
37
+ negate_iife:true,// 否定 IIFE
38
+ side_effects:true,// 移除副作用
39
+ switches:true,// 优化 switch
40
+ typeofs:true,// 优化 typeof
41
+ unsafe:false,// 不使用 unsafe(避免破坏框架)
42
+ keep_fargs:false,// 移除未使用参数
43
+ drop_console:true},output:{comments:false,quote_style:3,beautify:false,wrap_iife:true,ecma:2015},toplevel:true,keep_classnames:false,keep_fnames:false}})]},plugins:[new HtmlWebpackPlugin(htmlWebpackPluginConfig),new MetaTagOverridePlugin(adNetwork),// 注入 window.playcraftOrientation 全局变量,标识当前构建产物对应的横竖屏方向版本
44
+ new PlaycraftOrientationInjectorPlugin(playcraftOrientationValue),new webpack.DefinePlugin({...buildDefines(buildOptions),...buildOptions.defines,...customDefines}),// For some reason needed for PIXI v8
45
+ new webpack.optimize.LimitChunkCountPlugin({maxChunks:1})]},webpackCustomConfig);webpackConfig.output.path=path.resolve(outDir);// 根据混淆等级注入 obfuscator loader
46
+ const obfuscateLevel=buildOptions.obfuscateLevel!==undefined?buildOptions.obfuscateLevel:2;// 获取需要排除压缩的目录列表
47
+ const excludeCompressDirs=buildOptions.excludeCompressDirs||[];if(obfuscateLevel>=2){// 构建各等级的 obfuscator 配置
48
+ const obfuscatorOptions={// 通用基础配置
49
+ target:"browser",sourceMap:false,selfDefending:false,renameProperties:false,disableConsoleOutput:true,splitStrings:false,unicodeEscapeSequence:false};if(obfuscateLevel===2){// 等级2:基础混淆(控制流平坦化 + 字符串数组)
50
+ Object.assign(obfuscatorOptions,{controlFlowFlattening:true,controlFlowFlatteningThreshold:0.75,deadCodeInjection:false,stringArray:true,stringArrayThreshold:0.75,stringArrayEncoding:["base64"],stringArrayIndexShift:true,stringArrayRotate:true,stringArrayShuffle:true,stringArrayWrappersCount:2,stringArrayWrappersChainedCalls:true,stringArrayWrappersType:"function",stringArrayCallsTransform:true,stringArrayCallsTransformThreshold:0.75,transformObjectKeys:true,identifierNamesGenerator:"hexadecimal"})}else if(obfuscateLevel===3){// 等级3:在等级2基础上增加死代码注入
51
+ Object.assign(obfuscatorOptions,{controlFlowFlattening:true,controlFlowFlatteningThreshold:0.75,deadCodeInjection:true,deadCodeInjectionThreshold:0.4,stringArray:true,stringArrayThreshold:0.75,stringArrayEncoding:["base64"],stringArrayIndexShift:true,stringArrayRotate:true,stringArrayShuffle:true,stringArrayWrappersCount:2,stringArrayWrappersChainedCalls:true,stringArrayWrappersType:"function",stringArrayCallsTransform:true,stringArrayCallsTransformThreshold:0.75,transformObjectKeys:true,identifierNamesGenerator:"hexadecimal"})}else if(obfuscateLevel===4){// 等级4:最高强度混淆
52
+ Object.assign(obfuscatorOptions,{controlFlowFlattening:true,controlFlowFlatteningThreshold:1,deadCodeInjection:true,deadCodeInjectionThreshold:0.5,stringArray:true,stringArrayThreshold:1,stringArrayEncoding:["rc4"],stringArrayIndexShift:true,stringArrayRotate:true,stringArrayShuffle:true,stringArrayWrappersCount:3,stringArrayWrappersChainedCalls:true,stringArrayWrappersType:"function",stringArrayCallsTransform:true,stringArrayCallsTransformThreshold:1,transformObjectKeys:true,identifierNamesGenerator:"hexadecimal",splitStrings:true,splitStringsChunkLength:5,unicodeEscapeSequence:true})}console.log(`Obfuscation level: ${obfuscateLevel} (${["","terser-only","basic","dead-code","maximum"][obfuscateLevel]})`);// 构建exclude数组,包含node_modules和用户指定的排除目录
53
+ const excludePatterns=[];if(excludeCompressDirs.length>0){excludeCompressDirs.forEach(dir=>{excludePatterns.push(path.resolve(dir))});console.log(`ℹ️ Excluding directories from compression: ${excludeCompressDirs.join(", ")}`)}webpackConfig.module.rules.push({test:/\.(js|ts)$/,include:[path.resolve("src")],exclude:excludePatterns,enforce:"post",use:{loader:require.resolve("webpack-obfuscator/dist/loader"),options:obfuscatorOptions}})}else if(obfuscateLevel===1){console.log("Obfuscation level: 1 (terser-only)")}else{console.log("Obfuscation level: 0 (no minimize/obfuscate)")}// Adikteev 需要单独提取 CSS 为 style.css,替换默认的 style-loader
54
+ if(adNetwork==="adikteev"){const cssRuleIndex=webpackConfig.module.rules.findIndex(rule=>rule.test&&rule.test.toString().includes("\\.css"));if(cssRuleIndex!==-1){webpackConfig.module.rules[cssRuleIndex]={test:/\.css$/,use:[MiniCssExtractPlugin.loader,"css-loader"]};console.log("\u2705 Adikteev: CSS will be extracted to style.css")}}// 决定是否内联 JS 到 HTML
55
+ // 以下渠道需要分离 JS 文件,不使用 HtmlInlineScriptPlugin:
56
+ // - mintegral: 需要独立的 JS 文件
57
+ // - adikteev: 需要 creative.js 上传到 CDN
58
+ // - bigabid: 需要 main.js 上传到 CDN
59
+ // - facebook: ZIP 格式(index.html + build.js,包体上限 5MB)
60
+ if(adNetwork!=="mintegral"&&adNetwork!=="adikteev"&&adNetwork!=="bigabid"&&!(isZipOutputFinal&&adNetwork==="facebook"))webpackConfig.plugins.push(new HtmlInlineScriptPlugin);// 注入渠道 SDK 插件(公共逻辑)
61
+ injectSDKPlugins(webpackConfig,{network:adNetwork,protocol:adProtocol,playcraftOrientationValue});if(isZipOutputFinal){if(adNetwork==="tiktok"){webpackConfig.plugins.push(new CopyWebpackPlugin({patterns:[{from:path.join(__dirname,"resources","tiktok-config.json"),to:"config.json"}]}))}else if(adNetwork==="snapchat"){const tmpConfigPath=path.join(__dirname,"resources","snapchat-config.json");webpackConfig.plugins.push(new CopyWebpackPlugin({patterns:[{from:tmpConfigPath,to:"config.json"}]}))}else if(adNetwork==="bigoads"){// BigoAds 要求输出 ZIP 包,包含 index.html 和 config.json
62
+ // SDK 注入已在 injectSDKPlugins 中处理
63
+ webpackConfig.plugins.push(new CopyWebpackPlugin({patterns:[{from:path.join(__dirname,"resources","bigoads-config.json"),to:"config.json"}]}))}webpackConfig.plugins.push(new ZipPlugin({filename:isChannelFold2Zip?outputId:getFileName(),path:path.resolve(outDir),cleanTempFolder:true// 🗑️ 生成 zip 后删除临时文件夹
64
+ }));webpackConfig.output.path=path.resolve(outDir,outputId);if(adNetwork==="adikteev"){webpackConfig.output.filename="creative.js";// Adikteev 需要将 CSS 单独提取为 style.css 文件
65
+ webpackConfig.plugins.push(new MiniCssExtractPlugin({filename:"style.css"}))}else if(adNetwork==="bigabid")webpackConfig.output.filename="main.js";else if(adNetwork==="inmobi")webpackConfig.output.filename="main.js"}// 添加 fflate 压缩插件(仅在打正式包时生效)
66
+ if(buildOptions.fflateCompression){console.log("\u2705 fflate compression enabled (production build only)");webpackConfig.plugins.push(new FflateCompressionPlugin({enabled:true,level:9,keepOriginal:false,logStats:true,googlePlayUrl:buildOptions.googlePlayUrl,appStoreUrl:buildOptions.appStoreUrl}))}return webpackConfig}/**
459
67
  * Runs webpack production build
460
68
  * @param {import('webpack').Configuration} [webpackConfig] - Webpack configuration to use, creates default if not provided
461
69
  * @param {Partial<import('./index').CLIOptions>} [customOptions] - Custom options to merge with default options
462
70
  * @param {Record<string, any>} [customDefines] - Additional defines for webpack.DefinePlugin
463
71
  * @param {import('webpack').Configuration} [webpackCustomConfig] - Custom webpack config to merge
464
- */
465
- function runBuild(webpackConfig, customOptions, customDefines, webpackCustomConfig) {
466
- return new Promise((resolve, reject) => {
467
- if (!webpackConfig) webpackConfig = makeWebpackBuildConfig(customOptions, customDefines, webpackCustomConfig);
468
-
469
- const compiler = webpack(webpackConfig);
470
- compiler.run((err, stats) => {
471
- if (err) {
472
- console.error('Build failed:', err.stack || err);
473
- if (err.details) {
474
- console.error('Error details:', err.details);
475
- }
476
- return reject(err);
477
- }
478
-
479
- if (stats.hasErrors()) {
480
- const errors = stats.compilation.errors;
481
- console.error(`\n❌ Build finished with ${errors.length} error(s):\n`);
482
-
483
- // 打印每个错误的详细信息
484
- errors.forEach((error, index) => {
485
- console.error(`\n[Error ${index + 1}/${errors.length}]`);
486
- console.error(error.message || error);
487
- if (error.stack) {
488
- console.error(error.stack);
489
- }
490
- });
491
-
492
- // 拒绝 Promise 时传递格式化的错误消息
493
- const errorMessage = errors.map((e, i) => `[${i + 1}] ${e.message || e}`).join('\n');
494
- reject(new Error(`Webpack build failed with ${errors.length} error(s):\n${errorMessage}`));
495
- } else {
496
- console.log(`Build successful!`);
497
- resolve();
498
- }
499
- });
500
- });
501
- }
502
-
503
- exports.makeWebpackBuildConfig = makeWebpackBuildConfig;
504
- exports.runBuild = runBuild;
72
+ */function runBuild(webpackConfig,customOptions,customDefines,webpackCustomConfig){return new Promise((resolve,reject)=>{if(!webpackConfig)webpackConfig=makeWebpackBuildConfig(customOptions,customDefines,webpackCustomConfig);const compiler=webpack(webpackConfig);// 必须显式调用 compiler.close() 释放本次编译占用的内存(模块图/资源缓存/
73
+ // Terser 与 obfuscator 等插件持有的引用)。webpack 官方要求:若在同一进程内
74
+ // 多次调用 compiler.run(),每次 run 完成后都要 close,否则上一次编译的内存
75
+ // 无法被回收。playcraftOrientationChannel 会在同一进程里串行构建多个方向
76
+ // 版本(多次调用本函数),若不 close,内存会随构建次数线性累加,最终触发
77
+ // "JavaScript heap out of memory"。
78
+ const finalize=error=>{compiler.close(closeErr=>{if(closeErr){console.error("\u5173\u95ED webpack compiler \u65F6\u51FA\u9519:",closeErr)}if(error){reject(error)}else{resolve()}})};compiler.run((err,stats)=>{if(err){console.error("Build failed:",err.stack||err);if(err.details){console.error("Error details:",err.details)}return finalize(err)}if(stats.hasErrors()){const errors=stats.compilation.errors;console.error(`\n❌ Build finished with ${errors.length} error(s):\n`);// 打印每个错误的详细信息
79
+ errors.forEach((error,index)=>{console.error(`\n[Error ${index+1}/${errors.length}]`);console.error(error.message||error);if(error.stack){console.error(error.stack)}});// 拒绝 Promise 时传递格式化的错误消息
80
+ const errorMessage=errors.map((e,i)=>`[${i+1}] ${e.message||e}`).join("\n");finalize(new Error(`Webpack build failed with ${errors.length} error(s):\n${errorMessage}`))}else{console.log(`Build successful!`);finalize(null)}})})}exports.makeWebpackBuildConfig=makeWebpackBuildConfig;exports.runBuild=runBuild;