@plugin-light/shared 0.0.19 → 0.0.22

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 (48) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +13 -4
  3. package/lib/eslint-rules/import-order.d.ts +16 -0
  4. package/lib/eslint-rules/index.d.ts +1 -0
  5. package/lib/gen-version/index.d.ts +2 -0
  6. package/lib/index.d.ts +14 -7
  7. package/lib/index.js +704 -674
  8. package/lib/inject-dynamic-style/index.d.ts +2 -0
  9. package/package.json +13 -12
  10. package/lib/core/gen-version/index.d.ts +0 -2
  11. package/lib/core/index.d.ts +0 -7
  12. package/lib/core/inject-dynamic-style/index.d.ts +0 -2
  13. /package/lib/{black-list.d.ts → black-list/index.d.ts} +0 -0
  14. /package/lib/{bundle-analyze.d.ts → bundle-analyze/index.d.ts} +0 -0
  15. /package/lib/{config.d.ts → config/index.d.ts} +0 -0
  16. /package/lib/{config-project.d.ts → config-project/index.d.ts} +0 -0
  17. /package/lib/{context.d.ts → context/index.d.ts} +0 -0
  18. /package/lib/{core/cross-game-style → cross-game-style}/config.d.ts +0 -0
  19. /package/lib/{core/cross-game-style → cross-game-style}/cross-game-style.d.ts +0 -0
  20. /package/lib/{core/cross-game-style → cross-game-style}/index.d.ts +0 -0
  21. /package/lib/{core/cross-game-style → cross-game-style}/style-name.d.ts +0 -0
  22. /package/lib/{core/cross-game-style → cross-game-style}/types.d.ts +0 -0
  23. /package/lib/{css.d.ts → css/index.d.ts} +0 -0
  24. /package/lib/{deps.d.ts → deps/index.d.ts} +0 -0
  25. /package/lib/{find-dependencies.d.ts → find-dependencies/index.d.ts} +0 -0
  26. /package/lib/{core/gen-version → gen-version}/gen-version.d.ts +0 -0
  27. /package/lib/{core/gen-version → gen-version}/types.d.ts +0 -0
  28. /package/lib/{h5.d.ts → h5/index.d.ts} +0 -0
  29. /package/lib/{helper.d.ts → helper/index.d.ts} +0 -0
  30. /package/lib/{core/ifdef → ifdef}/index.d.ts +0 -0
  31. /package/lib/{core/ifdef → ifdef}/types.d.ts +0 -0
  32. /package/lib/{core/inject-dynamic-style → inject-dynamic-style}/helper.d.ts +0 -0
  33. /package/lib/{core/inject-dynamic-style → inject-dynamic-style}/types.d.ts +0 -0
  34. /package/lib/{loader-file.d.ts → loader-file/index.d.ts} +0 -0
  35. /package/lib/{loader-log.d.ts → loader-log/index.d.ts} +0 -0
  36. /package/lib/{core/node-module-file → node-module-file}/find.d.ts +0 -0
  37. /package/lib/{core/node-module-file → node-module-file}/index.d.ts +0 -0
  38. /package/lib/{platform.d.ts → platform/index.d.ts} +0 -0
  39. /package/lib/{project-name.d.ts → project-name/index.d.ts} +0 -0
  40. /package/lib/{replace-manifest.d.ts → replace-manifest/index.d.ts} +0 -0
  41. /package/lib/{core/replace-vue-directive → replace-vue-directive}/index.d.ts +0 -0
  42. /package/lib/{core/replace-vue-directive → replace-vue-directive}/replace-vue-directive.d.ts +0 -0
  43. /package/lib/{root.d.ts → root/index.d.ts} +0 -0
  44. /package/lib/{sub-project.d.ts → sub-project/index.d.ts} +0 -0
  45. /package/lib/{uni-env.d.ts → uni-env/index.d.ts} +0 -0
  46. /package/lib/{core/v-lazy → v-lazy}/index.d.ts +0 -0
  47. /package/lib/{core/v-lazy → v-lazy}/types.d.ts +0 -0
  48. /package/lib/{core/v-lazy → v-lazy}/v-lazy.d.ts +0 -0
package/lib/index.js CHANGED
@@ -33,763 +33,792 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
33
33
  var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
34
34
  var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
35
35
 
36
- function getRootDir() {
37
- return process.cwd();
36
+ function isInBlackList(filePath, blackList) {
37
+ if (!blackList) {
38
+ return false;
39
+ }
40
+ const found = blackList.find((item) => {
41
+ if (typeof item === 'string') {
42
+ return filePath.includes(item);
43
+ }
44
+ return item.test(filePath);
45
+ });
46
+ return !!found;
38
47
  }
39
48
 
40
- function getAppDir() {
41
- if (process.env.VUE_APP_DIR) {
42
- return process.env.VUE_APP_DIR;
43
- }
44
- if (process.env.UNI_INPUT_DIR) {
45
- return process.env.UNI_INPUT_DIR;
46
- }
47
- const dir = tComm.readEnvVariable('VUE_APP_DIR', path__namespace.join(getRootDir(), '.env.local'));
48
- if (dir) {
49
- return dir;
50
- }
51
- return '';
49
+ function checkBundleAnalyze() {
50
+ return process.argv.includes('--bundleAnalyzer')
51
+ || !!process.env.npm_config_report;
52
52
  }
53
- function getStyleName() {
54
- const configPath = path__namespace.resolve(getRootDir(), 'src', getAppDir(), 'config.js');
55
- let config = { styleName: '' };
56
- if (fs__namespace.existsSync(configPath)) {
57
- // eslint-disable-next-line @typescript-eslint/no-require-imports
58
- config = require(configPath);
59
- }
60
- const { styleName } = config;
61
- return styleName;
53
+ function checkDebugMode() {
54
+ return !!process.env.DEBUG_MODE;
62
55
  }
63
56
 
64
- const TIP_STYLE_NAME = '@TIP_STYLE_NAME';
57
+ const PLATFORM_MAP = {
58
+ MP_WX: 'mp-weixin',
59
+ MP_QQ: 'mp-qq',
60
+ MP_ALIPAY: 'mp-alipay',
61
+ MP_JD: 'mp-jd',
62
+ H5: 'h5',
63
+ };
64
+ const ALL_PLATFORM = 'ALL';
65
+ const PLATFORMS_MP = [
66
+ PLATFORM_MAP.MP_WX,
67
+ PLATFORM_MAP.MP_QQ,
68
+ ];
69
+ const PLATFORMS_ALL = [
70
+ PLATFORM_MAP.MP_WX,
71
+ PLATFORM_MAP.MP_QQ,
72
+ PLATFORM_MAP.H5,
73
+ ];
74
+ const HTML_MAP = {
75
+ MP_WX: '.wxml',
76
+ MP_QQ: '.qml',
77
+ MP_ALIPAY: '.axml',
78
+ MP_JD: '.jxml',
79
+ };
80
+ const CSS_MAP = {
81
+ MP_WX: '.wxss',
82
+ MP_QQ: '.qss',
83
+ MP_ALIPAY: '.acss',
84
+ MP_JD: '.jxss',
85
+ };
86
+ const CSS_POSTFIX_MAP = Object.keys(CSS_MAP)
87
+ .reduce((acc, item) => {
88
+ acc[item] = CSS_MAP[item].slice(1);
89
+ return acc;
90
+ }, {});
91
+ const CDN_MAP = {
92
+ UNI_SIMPLE_ROUTER_BETA4: 'https://image-1251917893.file.myqcloud.com/igame/npm/uni-simple-router/uni-simple-router-2.0.8-beta-4.js',
93
+ UNI_SIMPLE_ROUTER: 'https://image-1251917893.file.myqcloud.com/igame/npm/uni-simple-router/uni-simple-router%402.0.8-beta.4-1.js',
94
+ AEGIS_WEB: 'https://image-1251917893.file.myqcloud.com/igame/npm/aegis-web/aegis.min.js',
95
+ AEGIS_WEB_V2: 'https://image-1251917893.file.myqcloud.com/igame/npm/aegis-web/v2.min.2.3.41.js',
96
+ AXIOS: 'https://image-1251917893.file.myqcloud.com/igame/npm/axios@0.18.0/dist/axios.min.js',
97
+ VUE_LAZY_LOAD: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-lazyload@1.3.3/vue-lazyload.js',
98
+ VUE_V2: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue%402.6.10/dist/vue.runtime.min.js',
99
+ VUE_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue@3.3.6/vue.runtime.global.prod.js',
100
+ VUE_DEMI: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-demi@0.14.6/index.iife.min.js',
101
+ VUE_ROUTER_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-router@3.5.2/dist/vue-router.min.js',
102
+ VUE_ROUTER_V4: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-router@4.2.5/vue-router.global.prod.js',
103
+ VUEX_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vuex@3.0.1/dist/vuex.min.js',
104
+ VUEX_V4: 'https://image-1251917893.cos.ap-guangzhou.myqcloud.com/igame/npm/vuex%404.1.0/vuex.global.prod.js',
105
+ PINIA: 'https://image-1251917893.file.myqcloud.com/igame/npm/pinia@2.1.7/pinia.iife.min.js',
106
+ ELEMENT_PLUS: 'https://image-1251917893.file.myqcloud.com/igame/npm/element-plus/element-plus%402.7.8.js',
107
+ ELEMENT_PLUS_CSS: 'https://image-1251917893.file.myqcloud.com/igame/npm/element-plus/element-plus%402.7.8.css',
108
+ E_MONITOR: 'https://image-1251917893.file.myqcloud.com/igame/common/js/emonitor_custom_46f41566.js',
109
+ };
65
110
 
66
- function tryRemoveImport(source, removeImport = false) {
67
- let res = source;
68
- if (removeImport) {
69
- res = res.replace(`src="${TIP_STYLE_NAME}"`, '').replace(`src='${TIP_STYLE_NAME}'`, '');
111
+ const DEFAULT_TRANSPILE_DEPENDENCIES = [
112
+ 'pmd-merchant-ui',
113
+ 'press-ui',
114
+ 'press-plus',
115
+ 'pmd-aegis',
116
+ 'pmd-app-info',
117
+ 'pmd-config',
118
+ 'pmd-location',
119
+ 'pmd-login',
120
+ 'pmd-network',
121
+ 'pmd-report',
122
+ 'pmd-tools',
123
+ 'pmd-types',
124
+ 'pmd-widget',
125
+ 'pmd-vue',
126
+ 'pmd-jsapi',
127
+ 'pmd-component',
128
+ 'pmd-business',
129
+ 'pmd-api',
130
+ '@zebra-ui/swiper',
131
+ ];
132
+ const DEFAULT_ADAPTER_DIRS = [
133
+ 'comm',
134
+ 'common',
135
+ 'component',
136
+ 'live-component',
137
+ 'logic',
138
+ 'local-logic',
139
+ 'local-component',
140
+ 'login',
141
+ 'pages',
142
+ 'static',
143
+ 'node-modules',
144
+ ];
145
+ const AEGIS_EXTERNAL_SCRIPT_LINK = CDN_MAP.AEGIS_WEB;
146
+ const UNI_SIMPLE_ROUTER_SCRIPT_LINK = CDN_MAP.UNI_SIMPLE_ROUTER_BETA4;
147
+ const EXTERNAL_LINK_MAP = {
148
+ AXIOS: CDN_MAP.AXIOS,
149
+ VUE_LAZY_LOAD: CDN_MAP.VUE_LAZY_LOAD,
150
+ AEGIS_WEB: CDN_MAP.AEGIS_WEB,
151
+ UNI_SIMPLE_ROUTER: UNI_SIMPLE_ROUTER_SCRIPT_LINK,
152
+ };
153
+
154
+ /* eslint-disable @typescript-eslint/no-require-imports */
155
+ const ROOT_NAME = 'MAIN';
156
+ function saveJsonToLog(content, file, needLog = true) {
157
+ if (!needLog)
158
+ return;
159
+ createLogDir();
160
+ const filePath = `./log/${file}`;
161
+ let beforeContent = [];
162
+ let newContent = [{
163
+ logTime: tComm.timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'),
164
+ data: content,
165
+ }];
166
+ if (fs__namespace.existsSync(filePath)) {
167
+ try {
168
+ beforeContent = tComm.readFileSync(filePath, true).logList || [];
169
+ }
170
+ catch (err) {
171
+ beforeContent = [];
172
+ }
70
173
  }
71
- else {
72
- res = res.replace(TIP_STYLE_NAME, '');
174
+ if (beforeContent && Array.isArray(beforeContent)) {
175
+ newContent.push(...beforeContent);
176
+ }
177
+ newContent = newContent.slice(0, 10);
178
+ try {
179
+ fs__namespace.writeFile(filePath, JSON.stringify({ logList: newContent }, null, 2), {
180
+ encoding: 'utf-8',
181
+ }, () => { });
182
+ }
183
+ catch (err) {
73
184
  }
74
- return res;
75
185
  }
76
- function crossGameStyle({ source, options, dir, removeImport = false, }) {
77
- if (!source.includes(TIP_STYLE_NAME)) {
78
- return source;
186
+ function createLogDir() {
187
+ if (!fs__namespace.existsSync('./log')) {
188
+ fs__namespace.mkdirSync('./log');
79
189
  }
80
- let styleName = '';
81
- // 使用 env.local 的样式 VUE_APP_DIR = module/ingame-nba,即为 nba
82
- if (options?.styleName) {
83
- styleName = options.styleName;
190
+ }
191
+ const normalizePath = (path) => (tComm.isWindows() ? path.replace(/\\/g, '/') : path);
192
+ function updateAssetSource(assets, key, source) {
193
+ assets[key] = {
194
+ source() {
195
+ return source;
196
+ },
197
+ size() {
198
+ return source.length;
199
+ },
200
+ };
201
+ }
202
+ function removeFirstSlash(key) {
203
+ if (key.startsWith('/')) {
204
+ return key.slice(1);
84
205
  }
85
- else if (getStyleName()) {
86
- styleName = getStyleName();
206
+ return key;
207
+ }
208
+ function sortStringList(list) {
209
+ list.sort((a, b) => {
210
+ if (a > b)
211
+ return 1;
212
+ if (a < b)
213
+ return -1;
214
+ return 0;
215
+ });
216
+ return list;
217
+ }
218
+ function parseSetDeps(deps) {
219
+ return Object.keys(deps).reduce((acc, item) => {
220
+ acc[item] = Array.from(deps[item]);
221
+ sortStringList(acc[item]);
222
+ return acc;
223
+ }, {});
224
+ }
225
+ function getRelativePath(filePath) {
226
+ return path__namespace.relative(process.cwd(), path__namespace.resolve(filePath));
227
+ }
228
+
229
+ const DEFAULT_KEYS = [
230
+ 'UNI_APP_X',
231
+ 'APP',
232
+ 'APP_UVUE',
233
+ 'APP_NVUE',
234
+ 'APP_PLUS',
235
+ 'APP_PLUS_NVUE',
236
+ 'APP_VUE',
237
+ 'APP_ANDROID',
238
+ 'APP_IOS',
239
+ 'APP_HARMONY',
240
+ 'H5',
241
+ 'MP',
242
+ 'MP_360',
243
+ 'MP_ALIPAY',
244
+ 'MP_BAIDU',
245
+ 'MP_QQ',
246
+ 'MP_LARK',
247
+ 'MP_TOUTIAO',
248
+ 'MP_WEIXIN',
249
+ 'MP_KUAISHOU',
250
+ 'MP_JD',
251
+ 'QUICKAPP_NATIVE',
252
+ 'QUICKAPP_WEBVIEW',
253
+ 'QUICKAPP_WEBVIEW_HUAWEI',
254
+ 'QUICKAPP_WEBVIEW_UNION',
255
+ 'VUE2',
256
+ 'VUE3',
257
+ 'WEB',
258
+ ];
259
+ const DEFAULT_CONTEXT_OBJECT = DEFAULT_KEYS.reduce((acc, key) => ({
260
+ ...acc,
261
+ [key]: false,
262
+ }), {});
263
+
264
+ const scssLogger = {
265
+ warn(message, options) {
266
+ // Mute "Mixed Declarations" warning
267
+ if (options.deprecation && message.includes('mixed-decls')) {
268
+ return;
269
+ }
270
+ // List all other warnings
271
+ console.warn(`▲ [WARNING]: ${message}`);
272
+ },
273
+ };
274
+
275
+ function getDeps(dir) {
276
+ const data = tComm.readFileSync(path__default["default"].resolve(dir, 'package.json'), true);
277
+ return Object.keys({
278
+ ...data.dependencies,
279
+ });
280
+ }
281
+
282
+ function getImportOrderRule() {
283
+ return {
284
+ 'import/order': [
285
+ 'error',
286
+ {
287
+ groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object', 'type'],
288
+ 'newlines-between': 'always-and-inside-groups',
289
+ alphabetize: {
290
+ order: 'asc',
291
+ caseInsensitive: true,
292
+ },
293
+ pathGroups: [
294
+ {
295
+ pattern: 'vue',
296
+ group: 'external',
297
+ position: 'before',
298
+ },
299
+ {
300
+ pattern: 'vite',
301
+ group: 'external',
302
+ position: 'before',
303
+ },
304
+ ],
305
+ pathGroupsExcludedImportTypes: ['builtin'],
306
+ },
307
+ ],
308
+ };
309
+ }
310
+
311
+ function getParent(path, level) {
312
+ if (!level) {
313
+ return path.parent;
87
314
  }
88
- if (Array.isArray(styleName)) {
89
- if (styleName.length > 1) {
90
- styleName = styleName.filter((item) => {
91
- const cssAbsolutePath = `${dir}/css/${item}.scss`;
92
- return fs__namespace.existsSync(cssAbsolutePath);
93
- });
94
- if (styleName.length > 1) {
95
- const styleTags = styleName
96
- .filter((item) => {
97
- const cssAbsolutePath = `${dir}/css/${item}.scss`;
98
- return removeImport ? fs__namespace.existsSync(cssAbsolutePath) : true;
99
- })
100
- .map(item => `.${item} {@import './css/${item}.scss';}`);
101
- const res = tryRemoveImport(source, removeImport);
102
- return res.replace(/<\/style>/, `</style>${['<style scoped lang="scss">', ...styleTags, '</style>'].join('')}`);
315
+ return getParent(path.parentPath, level - 1);
316
+ }
317
+ function findDependencies(content) {
318
+ const parser = require('@babel/parser');
319
+ const traverse = require('@babel/traverse').default;
320
+ const sourceList = [];
321
+ const ast = parser.parse(content, {
322
+ // 不加这个配置,报错:SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"'
323
+ sourceType: 'module',
324
+ plugins: ['typescript'],
325
+ });
326
+ traverse(ast, {
327
+ CallExpression(path) {
328
+ if (path.node.callee.name === 'require') {
329
+ if (path.node.arguments[0].type === 'StringLiteral') {
330
+ sourceList.push(path.node.arguments[0].value);
331
+ }
332
+ if (getParent(path, 0).type === 'ExpressionStatement'
333
+ && getParent(path, 1).type === 'BlockStatement'
334
+ && getParent(path, 2).type === 'ObjectMethod'
335
+ && getParent(path, 3).type === 'ObjectExpression'
336
+ && getParent(path, 4)?.type === 'ObjectProperty'
337
+ && getParent(path, 4)?.key?.name === 'components'
338
+ && getParent(path, 5)?.type === 'ObjectExpression'
339
+ && getParent(path, 6)?.type === 'ExportDefaultDeclaration'
340
+ && path.node.arguments[0].type === 'ArrayExpression') {
341
+ sourceList.push(path.node.arguments[0].elements[0].value);
342
+ }
103
343
  }
104
- }
105
- styleName = styleName[0] || '';
106
- }
107
- const cssPath = `./css/${styleName}.scss`;
108
- const cssAbsolutePath = `${dir}/css/${styleName}.scss`;
109
- const exist = fs__namespace.existsSync(cssAbsolutePath);
110
- if (exist) {
111
- return source.replace(TIP_STYLE_NAME, cssPath);
112
- }
113
- return tryRemoveImport(source, removeImport);
344
+ },
345
+ ImportDeclaration(path) {
346
+ sourceList.push(path.node.source.value);
347
+ },
348
+ });
349
+ return sourceList;
114
350
  }
115
351
 
116
- function parseQuote(str = '') {
117
- return str.replace(/'/g, '"');
352
+ function checkH5() {
353
+ return process.env.VUE_APP_PLATFORM === 'h5';
118
354
  }
119
- function getVersionCode(versionName) {
120
- let author = '';
121
- let branch = '';
122
- try {
123
- author = tComm.getGitAuthor(false) || '';
124
- branch = tComm.getGitCurBranch() || '';
355
+
356
+ const LOADER_PROD = 'loader.prod.js';
357
+ function getLoaderFile(dir = '', isProd = false) {
358
+ if (isProd) {
359
+ return path__default["default"].resolve(dir, LOADER_PROD);
125
360
  }
126
- catch (err) { }
127
- const versionInfo = {
128
- time: tComm.timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'),
129
- author,
130
- branch,
131
- netEnv: process.env.NET_ENV || '',
132
- };
133
- let code = '';
134
- if (versionName) {
135
- code = `
136
- window.${versionName} = {
137
- time: '${versionInfo.time}',
138
- author: '${versionInfo.author}',
139
- branch: '${versionInfo.branch}',
140
- netEnv: '${versionInfo.netEnv}',
361
+ return path__default["default"].resolve(dir, 'loader.js');
141
362
  }
142
- `;
143
- return code;
144
- }
145
- code = `
146
- console.info('[system]', '');
147
- console.info('[system]', 'Build Time: ${versionInfo.time || ''}');
148
- console.info('[system]', 'Build Author: ${versionInfo.author || ''}');
149
- console.info('[system]', 'Build Branch: ${versionInfo.branch || ''}');
150
- console.info('[system]', 'Build Net Env: ${versionInfo.netEnv || ''}');
151
- `;
152
- return code;
363
+ function getLoaderProdFile(dir = '') {
364
+ return path__default["default"].resolve(dir, LOADER_PROD);
153
365
  }
154
- function getCommitCode(versionName) {
155
- let commitInfo = {};
156
- try {
157
- commitInfo = tComm.getGitCommitInfo();
158
- }
159
- catch (err) { }
160
- if (commitInfo.timeStamp) {
161
- commitInfo.date = tComm.timeStampFormat(commitInfo.timeStamp, 'yyyy-MM-dd hh:mm:ss');
162
- }
163
- let code = '';
164
- if (versionName) {
165
- code = `
166
- window.${versionName} = {
167
- message: '${parseQuote(commitInfo.message)}',
168
- author: '${commitInfo.author}',
169
- date: '${commitInfo.date}',
170
- hash: '${commitInfo.hash}',
366
+
367
+ const LOG_KEY = 'LOADER_LOGS';
368
+ function saveLoaderLog() {
369
+ const loaderLogs = global[LOG_KEY];
370
+ if (!loaderLogs)
371
+ return;
372
+ Object.keys(loaderLogs).forEach((file) => {
373
+ saveJsonToLog(loaderLogs[file], file);
374
+ });
171
375
  }
172
- `;
173
- return code;
376
+ function recordLoaderLog(file, content) {
377
+ if (!global[LOG_KEY]) {
378
+ global[LOG_KEY] = {};
174
379
  }
175
- code = `
176
- console.info('[system]', '');
177
- console.info('[system]', 'Last Commit Message: ${parseQuote(commitInfo.message) || ''}');
178
- console.info('[system]', 'Last Commit Author: ${commitInfo.author || ''}');
179
- console.info('[system]', 'Last Commit Time: ${commitInfo.date || ''}');
180
- console.info('[system]', 'Last Commit Hash: ${commitInfo.hash || ''}');
181
- `;
182
- return code;
380
+ if (!global[LOG_KEY][file]) {
381
+ global[LOG_KEY][file] = [];
382
+ }
383
+ global[LOG_KEY][file].push(content);
183
384
  }
184
- function getMpVersionCode() {
185
- return `
186
- var uni = (typeof wx !== 'undefined' && wx)
187
- || (typeof qq !== 'undefined' && qq)
188
- || (typeof jd !== 'undefined' && jd)
189
- || (typeof my !== 'undefined' && my);
190
385
 
191
- var miniProgram = uni.getAccountInfoSync().miniProgram || {};
192
- var systemInfo = uni.getSystemInfoSync() || {};
193
- var envVersionMap = {
194
- develop: '开发版',
195
- trial: '体验版',
196
- release: '正式版'
386
+ function getWxmlAndWxssPostfix() {
387
+ const map = Object.keys(PLATFORM_MAP).reduce((acc, item) => {
388
+ acc[PLATFORM_MAP[item]] = item;
389
+ return acc;
390
+ }, {});
391
+ const key = map[process.env.UNI_PLATFORM || ''];
392
+ return [
393
+ HTML_MAP[key],
394
+ CSS_MAP[key],
395
+ ];
197
396
  }
198
- var { envVersion = '', version = '' } = miniProgram;
199
- var { brand, model, pixelRatio } = systemInfo;
200
- var versionDesc = \`\${envVersion}(\${envVersionMap[envVersion] || ''})\`;
201
-
202
- console.info('[system]', '');
203
- console.info('[system]', \`Env Version:\${envVersion ? versionDesc : ''}\`);
204
- console.info('[system]', \`Version:\${version}\`);
205
397
 
206
- console.info('[system]', '');
207
- console.info('[system]', \`Brand:\${brand}, \${model}\`);
208
- console.info('[system]', \`PixelRatio:\${pixelRatio}\`);
209
- `;
210
- }
211
- function getMpInsertCode() {
212
- const insertCode = `
213
- try {
214
- setTimeout(() => {
215
- ${getVersionCode()}
216
- ${getCommitCode()}
217
- ${getMpVersionCode()}
218
- }, 2000);
219
- } catch(err) {}
220
- `;
221
- return insertCode;
222
- }
223
- function getGenVersionPluginOptions(options) {
224
- const buildName = options?.buildName || '';
225
- const commitName = options?.commitName || '';
226
- const delay = options?.delay === undefined ? 10 : options?.delay;
227
- return {
228
- buildName,
229
- commitName,
230
- delay,
231
- };
398
+ function getProjectName() {
399
+ let result = '';
400
+ try {
401
+ const json = tComm.readFileSync('package.json', true) || {};
402
+ result = json.name || '';
403
+ }
404
+ catch (err) { }
405
+ return result;
232
406
  }
233
- function getWebInsertCode(options) {
234
- const { buildName, commitName, delay } = getGenVersionPluginOptions(options || {});
235
- return `
236
- <script>
237
- try {
238
- setTimeout(() => {
239
- ${getVersionCode(buildName)}
240
- ${getCommitCode(commitName)}
241
- }, ${delay});
242
- } catch(err) {}
243
- </script>
244
- `;
407
+ function getSubProjectName() {
408
+ const name = process.env.VUE_APP_DIR?.split('/')?.[1] || '';
409
+ return name;
245
410
  }
246
411
 
247
- const BASE_SCSS = 'base.scss';
248
- function getStyleList(dir) {
249
- const cssList = fs__namespace.readdirSync(dir);
250
- const filtered = cssList
251
- .filter(item => item.endsWith('scss') && !item.startsWith(BASE_SCSS))
252
- .map(item => item.replace(/\.scss$/, ''));
253
- return filtered;
412
+ // 读取 manifest.json ,修改后重新写入
413
+ const manifestPath = `${process.env.UNI_INPUT_DIR}/manifest.json`;
414
+ let originManifest = '';
415
+ try {
416
+ originManifest = fs__namespace.readFileSync(manifestPath, { encoding: 'utf-8' });
254
417
  }
255
- function genInjectContent({ styleList, componentName, topElement, dir = '', }) {
256
- const styleStr = styleList.map((item) => `
257
- &--type-${item} {
258
- @import './${dir}${item}.scss';
259
- }`).join('\n');
260
- return `
261
- ${topElement}.${componentName} {
262
- ${styleStr}
418
+ catch (err) {
263
419
  }
264
- `;
420
+ let Manifest = originManifest;
421
+ function replaceManifest(path, value) {
422
+ const arr = path.split('.');
423
+ const len = arr.length;
424
+ const lastItem = arr[len - 1];
425
+ let i = 0;
426
+ const ManifestArr = Manifest.split(/\n/);
427
+ for (let index = 0; index < ManifestArr.length; index++) {
428
+ const item = ManifestArr[index];
429
+ if (new RegExp(`"${arr[i]}"`).test(item))
430
+ i = i + 1;
431
+ if (i === len) {
432
+ const hasComma = /,/.test(item);
433
+ ManifestArr[index] = item.replace(new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`), `"${lastItem}": ${value}${hasComma ? ',' : ''}`);
434
+ break;
435
+ }
436
+ }
437
+ Manifest = ManifestArr.join('\n');
265
438
  }
266
- function getComponentName(dir) {
267
- const tPath = tComm.normalizePath(dir);
268
- const reg = /\/([^/]+)\/css/;
269
- const match = tPath.match(reg);
270
- return match?.[1] || '';
439
+ function updateManifest(path, value) {
440
+ replaceManifest(path, value);
441
+ fs__namespace.writeFileSync(manifestPath, Manifest, {
442
+ flag: 'w',
443
+ });
271
444
  }
272
-
273
- function findNodeModuleFile({ name, target, filePath, root, }) {
274
- const iRoot = root ?? process.cwd();
275
- const NODE_MODULES = 'node_modules';
276
- const PNPM = `${NODE_MODULES}/.pnpm`;
277
- const nodeModulesTargetFile = path__default["default"].resolve(iRoot, NODE_MODULES, name, filePath);
278
- const exist = fs__default["default"].existsSync(nodeModulesTargetFile);
279
- if (exist) {
280
- return [
281
- nodeModulesTargetFile,
282
- ];
283
- }
284
- const pnpmRoot = path__default["default"].resolve(iRoot, PNPM);
285
- if (!fs__default["default"].existsSync(pnpmRoot)) {
286
- return [];
287
- }
288
- const pnpmList = fs__default["default"].readdirSync(pnpmRoot);
289
- const list = pnpmList.filter(item => item.startsWith(target));
290
- const innerFileList = list.map((file) => {
291
- const targetFile = path__default["default"].resolve(`${PNPM}/${file}/node_modules/${name}/${filePath}`);
292
- return targetFile;
293
- }).filter(file => fs__default["default"].existsSync(file));
294
- return innerFileList;
445
+ function revertManifest() {
446
+ fs__namespace.writeFileSync(manifestPath, originManifest, {
447
+ flag: 'w',
448
+ });
295
449
  }
296
450
 
297
- function replaceDirective(source, list) {
298
- if (!list.length)
299
- return source;
300
- const reg = new RegExp(`(?<=<[^<]+)v-${list.join('|')}=?[^\\s]*`, 'g');
301
- const newSource = source.replace(reg, '');
302
- return newSource;
451
+ function getRootDir() {
452
+ return process.cwd();
303
453
  }
304
454
 
305
- const htmlReg = /(?<=<template>)([\s\S]+)(?=<\/template>)/;
306
- const imgReg = /(<img[\s\S]+?)v-lazy=(?:"|')(.*?)(?:"|')([\s\S]*?>)/g;
307
- const sizeReg = /(?<=[\s\n]+(?:data-)?)size=(?:"|')(\d+)(?:"|')/;
308
- const widthReg = /(?<=[\s\n]+(?:data-)?)width=(?:"|')(\d+)(?:"|')/;
309
- const heightReg = /(?<=[\s\n]+(?:data-)?)height=(?:"|')(\d+)(?:"|')/;
310
- function vLazyCore(source, options) {
311
- const { urlHandler } = options || {};
312
- let html = '';
313
- const match = source.match(htmlReg);
314
- if (match?.[1]) {
315
- html = match[1];
455
+ function getSubProjectRoot({ root, appDir, }) {
456
+ let subProjectRoot = `${path__default["default"].resolve(root, `./src/${appDir}`)}/`;
457
+ if (!appDir) {
458
+ subProjectRoot = path__default["default"].resolve(root, './src/');
316
459
  }
317
- if (!html)
318
- return source;
319
- if (!html.match(imgReg))
320
- return source;
321
- const newHtml = handleImg(html, urlHandler);
322
- const newSource = source.replace(htmlReg, () => newHtml);
323
- return newSource;
460
+ return subProjectRoot;
324
461
  }
325
- function getSize(pre, post, reg) {
326
- let size = '';
327
- const preMatch = pre.match(reg);
328
- const postMatch = post.match(reg);
329
- if (preMatch?.[1]) {
330
- size = preMatch[1];
331
- }
332
- else if (postMatch?.[1]) {
333
- size = postMatch[1];
462
+ function getSubProjectConfig(subProjectRoot) {
463
+ let res = {};
464
+ try {
465
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
466
+ res = require(path__default["default"].resolve(subProjectRoot, 'config.js'));
334
467
  }
335
- return size;
468
+ catch (err) { }
469
+ return res;
336
470
  }
337
- function getImgSrc({ urlHandler, src, size, width, height, }) {
338
- let srcStr = src;
339
- if (!urlHandler) {
340
- return src;
341
- }
342
- if (width && height) {
343
- srcStr = `${urlHandler}(${src}, ${width}, ${height})`;
471
+
472
+ const getPlatform = () => process.env.UNI_PLATFORM || '';
473
+ const getUtsPlatform = () => process.env.UNI_UTS_PLATFORM || '';
474
+ const getAppPlatform = () => process.env.UNI_APP_PLATFORM || '';
475
+ const isH5 = () => getPlatform() === 'h5';
476
+ const isApp = () => getPlatform() === 'app';
477
+ const isAppAndroid = () => getAppPlatform() === 'android' || getUtsPlatform() === 'app-android';
478
+ const isAppIOS = () => getAppPlatform() === 'ios' || getUtsPlatform() === 'app-ios';
479
+ const isMp = () => /^mp-/i.test(getPlatform());
480
+ const isMpWeixin = () => getPlatform() === 'mp-weixin';
481
+ const isMpAlipay = () => getPlatform() === 'mp-alipay';
482
+ const isMpBaidu = () => getPlatform() === 'mp-baidu';
483
+ const isMpKuaishou = () => getPlatform() === 'mp-kuaishou';
484
+ const isMpQQ = () => getPlatform() === 'mp-qq';
485
+ const isMpToutiao = () => getPlatform() === 'mp-toutiao';
486
+ const isQuickapp = () => /^quickapp-webview/i.test(getPlatform());
487
+ const isQuickappUnion = () => getPlatform() === 'quickapp-webview-union';
488
+ const isQuickappHuawei = () => getPlatform() === 'quickapp-webview-huawei';
489
+
490
+ const TIP_STYLE_NAME = '@TIP_STYLE_NAME';
491
+
492
+ function getAppDir() {
493
+ if (process.env.VUE_APP_DIR) {
494
+ return process.env.VUE_APP_DIR;
344
495
  }
345
- else if (size) {
346
- srcStr = `${urlHandler}(${src}, ${size}, ${size})`;
496
+ if (process.env.UNI_INPUT_DIR) {
497
+ return process.env.UNI_INPUT_DIR;
347
498
  }
348
- else {
349
- srcStr = `${urlHandler}(${src})`;
499
+ const dir = tComm.readEnvVariable('VUE_APP_DIR', path__namespace.join(getRootDir(), '.env.local'));
500
+ if (dir) {
501
+ return dir;
350
502
  }
351
- return srcStr;
352
- }
353
- function handleImg(str = '', urlHandler = '') {
354
- const res = str.replace(imgReg, (...args) => {
355
- const { 1: pre, 2: src, 3: post } = args;
356
- const size = getSize(pre, post, sizeReg);
357
- const width = getSize(pre, post, widthReg);
358
- const height = getSize(pre, post, heightReg);
359
- const srcStr = getImgSrc({
360
- urlHandler,
361
- src,
362
- size,
363
- width,
364
- height,
365
- });
366
- const innerRes = `${pre} :src="${srcStr}" lazy-load ${post}`;
367
- return innerRes;
368
- });
369
- return res;
503
+ return '';
370
504
  }
371
-
372
- function isInBlackList(filePath, blackList) {
373
- if (!blackList) {
374
- return false;
505
+ function getStyleName() {
506
+ const configPath = path__namespace.resolve(getRootDir(), 'src', getAppDir(), 'config.js');
507
+ let config = { styleName: '' };
508
+ if (fs__namespace.existsSync(configPath)) {
509
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
510
+ config = require(configPath);
375
511
  }
376
- const found = blackList.find((item) => {
377
- if (typeof item === 'string') {
378
- return filePath.includes(item);
379
- }
380
- return item.test(filePath);
381
- });
382
- return !!found;
383
- }
384
-
385
- function checkBundleAnalyze() {
386
- return process.argv.includes('--bundleAnalyzer')
387
- || !!process.env.npm_config_report;
388
- }
389
- function checkDebugMode() {
390
- return !!process.env.DEBUG_MODE;
512
+ const { styleName } = config;
513
+ return styleName;
391
514
  }
392
515
 
393
- const PLATFORM_MAP = {
394
- MP_WX: 'mp-weixin',
395
- MP_QQ: 'mp-qq',
396
- MP_ALIPAY: 'mp-alipay',
397
- MP_JD: 'mp-jd',
398
- H5: 'h5',
399
- };
400
- const ALL_PLATFORM = 'ALL';
401
- const PLATFORMS_MP = [
402
- PLATFORM_MAP.MP_WX,
403
- PLATFORM_MAP.MP_QQ,
404
- ];
405
- const PLATFORMS_ALL = [
406
- PLATFORM_MAP.MP_WX,
407
- PLATFORM_MAP.MP_QQ,
408
- PLATFORM_MAP.H5,
409
- ];
410
- const HTML_MAP = {
411
- MP_WX: '.wxml',
412
- MP_QQ: '.qml',
413
- MP_ALIPAY: '.axml',
414
- MP_JD: '.jxml',
415
- };
416
- const CSS_MAP = {
417
- MP_WX: '.wxss',
418
- MP_QQ: '.qss',
419
- MP_ALIPAY: '.acss',
420
- MP_JD: '.jxss',
421
- };
422
- const CSS_POSTFIX_MAP = Object.keys(CSS_MAP)
423
- .reduce((acc, item) => {
424
- acc[item] = CSS_MAP[item].slice(1);
425
- return acc;
426
- }, {});
427
- const CDN_MAP = {
428
- UNI_SIMPLE_ROUTER_BETA4: 'https://image-1251917893.file.myqcloud.com/igame/npm/uni-simple-router/uni-simple-router-2.0.8-beta-4.js',
429
- UNI_SIMPLE_ROUTER: 'https://image-1251917893.file.myqcloud.com/igame/npm/uni-simple-router/uni-simple-router%402.0.8-beta.4-1.js',
430
- AEGIS_WEB: 'https://image-1251917893.file.myqcloud.com/igame/npm/aegis-web/aegis.min.js',
431
- AEGIS_WEB_V2: 'https://image-1251917893.file.myqcloud.com/igame/npm/aegis-web/v2.min.2.3.41.js',
432
- AXIOS: 'https://image-1251917893.file.myqcloud.com/igame/npm/axios@0.18.0/dist/axios.min.js',
433
- VUE_LAZY_LOAD: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-lazyload@1.3.3/vue-lazyload.js',
434
- VUE_V2: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue%402.6.10/dist/vue.runtime.min.js',
435
- VUE_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue@3.3.6/vue.runtime.global.prod.js',
436
- VUE_DEMI: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-demi@0.14.6/index.iife.min.js',
437
- VUE_ROUTER_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-router@3.5.2/dist/vue-router.min.js',
438
- VUE_ROUTER_V4: 'https://image-1251917893.file.myqcloud.com/igame/npm/vue-router@4.2.5/vue-router.global.prod.js',
439
- VUEX_V3: 'https://image-1251917893.file.myqcloud.com/igame/npm/vuex@3.0.1/dist/vuex.min.js',
440
- VUEX_V4: 'https://image-1251917893.cos.ap-guangzhou.myqcloud.com/igame/npm/vuex%404.1.0/vuex.global.prod.js',
441
- PINIA: 'https://image-1251917893.file.myqcloud.com/igame/npm/pinia@2.1.7/pinia.iife.min.js',
442
- ELEMENT_PLUS: 'https://image-1251917893.file.myqcloud.com/igame/npm/element-plus/element-plus%402.7.8.js',
443
- ELEMENT_PLUS_CSS: 'https://image-1251917893.file.myqcloud.com/igame/npm/element-plus/element-plus%402.7.8.css',
444
- E_MONITOR: 'https://image-1251917893.file.myqcloud.com/igame/common/js/emonitor_custom_46f41566.js',
445
- };
446
-
447
- const DEFAULT_TRANSPILE_DEPENDENCIES = [
448
- 'pmd-merchant-ui',
449
- 'press-ui',
450
- 'press-plus',
451
- 'pmd-aegis',
452
- 'pmd-app-info',
453
- 'pmd-config',
454
- 'pmd-location',
455
- 'pmd-login',
456
- 'pmd-network',
457
- 'pmd-report',
458
- 'pmd-tools',
459
- 'pmd-types',
460
- 'pmd-widget',
461
- 'pmd-vue',
462
- 'pmd-jsapi',
463
- 'pmd-component',
464
- 'pmd-business',
465
- 'pmd-api',
466
- '@zebra-ui/swiper',
467
- ];
468
- const DEFAULT_ADAPTER_DIRS = [
469
- 'comm',
470
- 'common',
471
- 'component',
472
- 'live-component',
473
- 'logic',
474
- 'local-logic',
475
- 'local-component',
476
- 'login',
477
- 'pages',
478
- 'static',
479
- 'node-modules',
480
- ];
481
- const AEGIS_EXTERNAL_SCRIPT_LINK = CDN_MAP.AEGIS_WEB;
482
- const UNI_SIMPLE_ROUTER_SCRIPT_LINK = CDN_MAP.UNI_SIMPLE_ROUTER_BETA4;
483
- const EXTERNAL_LINK_MAP = {
484
- AXIOS: CDN_MAP.AXIOS,
485
- VUE_LAZY_LOAD: CDN_MAP.VUE_LAZY_LOAD,
486
- AEGIS_WEB: CDN_MAP.AEGIS_WEB,
487
- UNI_SIMPLE_ROUTER: UNI_SIMPLE_ROUTER_SCRIPT_LINK,
488
- };
489
-
490
- /* eslint-disable @typescript-eslint/no-require-imports */
491
- const ROOT_NAME = 'MAIN';
492
- function saveJsonToLog(content, file, needLog = true) {
493
- if (!needLog)
494
- return;
495
- createLogDir();
496
- const filePath = `./log/${file}`;
497
- let beforeContent = [];
498
- let newContent = [{
499
- logTime: tComm.timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'),
500
- data: content,
501
- }];
502
- if (fs__namespace.existsSync(filePath)) {
503
- try {
504
- beforeContent = tComm.readFileSync(filePath, true).logList || [];
505
- }
506
- catch (err) {
507
- beforeContent = [];
508
- }
516
+ function tryRemoveImport(source, removeImport = false) {
517
+ let res = source;
518
+ if (removeImport) {
519
+ res = res.replace(`src="${TIP_STYLE_NAME}"`, '').replace(`src='${TIP_STYLE_NAME}'`, '');
509
520
  }
510
- if (beforeContent && Array.isArray(beforeContent)) {
511
- newContent.push(...beforeContent);
521
+ else {
522
+ res = res.replace(TIP_STYLE_NAME, '');
512
523
  }
513
- newContent = newContent.slice(0, 10);
514
- try {
515
- fs__namespace.writeFile(filePath, JSON.stringify({ logList: newContent }, null, 2), {
516
- encoding: 'utf-8',
517
- }, () => { });
524
+ return res;
525
+ }
526
+ function crossGameStyle({ source, options, dir, removeImport = false, }) {
527
+ if (!source.includes(TIP_STYLE_NAME)) {
528
+ return source;
518
529
  }
519
- catch (err) {
530
+ let styleName = '';
531
+ // 使用 env.local 的样式 VUE_APP_DIR = module/ingame-nba,即为 nba
532
+ if (options?.styleName) {
533
+ styleName = options.styleName;
520
534
  }
521
- }
522
- function createLogDir() {
523
- if (!fs__namespace.existsSync('./log')) {
524
- fs__namespace.mkdirSync('./log');
535
+ else if (getStyleName()) {
536
+ styleName = getStyleName();
537
+ }
538
+ if (Array.isArray(styleName)) {
539
+ if (styleName.length > 1) {
540
+ styleName = styleName.filter((item) => {
541
+ const cssAbsolutePath = `${dir}/css/${item}.scss`;
542
+ return fs__namespace.existsSync(cssAbsolutePath);
543
+ });
544
+ if (styleName.length > 1) {
545
+ const styleTags = styleName
546
+ .filter((item) => {
547
+ const cssAbsolutePath = `${dir}/css/${item}.scss`;
548
+ return removeImport ? fs__namespace.existsSync(cssAbsolutePath) : true;
549
+ })
550
+ .map(item => `.${item} {@import './css/${item}.scss';}`);
551
+ const res = tryRemoveImport(source, removeImport);
552
+ return res.replace(/<\/style>/, `</style>${['<style scoped lang="scss">', ...styleTags, '</style>'].join('')}`);
553
+ }
554
+ }
555
+ styleName = styleName[0] || '';
556
+ }
557
+ const cssPath = `./css/${styleName}.scss`;
558
+ const cssAbsolutePath = `${dir}/css/${styleName}.scss`;
559
+ const exist = fs__namespace.existsSync(cssAbsolutePath);
560
+ if (exist) {
561
+ return source.replace(TIP_STYLE_NAME, cssPath);
525
562
  }
563
+ return tryRemoveImport(source, removeImport);
526
564
  }
527
- const normalizePath = (path) => (tComm.isWindows() ? path.replace(/\\/g, '/') : path);
528
- function updateAssetSource(assets, key, source) {
529
- assets[key] = {
530
- source() {
531
- return source;
532
- },
533
- size() {
534
- return source.length;
535
- },
536
- };
565
+
566
+ function parseQuote(str = '') {
567
+ return str.replace(/'/g, '"');
537
568
  }
538
- function removeFirstSlash(key) {
539
- if (key.startsWith('/')) {
540
- return key.slice(1);
569
+ function getVersionCode(versionName) {
570
+ let author = '';
571
+ let branch = '';
572
+ try {
573
+ author = tComm.getGitAuthor(false) || '';
574
+ branch = tComm.getGitCurBranch() || '';
541
575
  }
542
- return key;
576
+ catch (err) { }
577
+ const versionInfo = {
578
+ time: tComm.timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss'),
579
+ author,
580
+ branch,
581
+ netEnv: process.env.NET_ENV || '',
582
+ };
583
+ let code = '';
584
+ if (versionName) {
585
+ code = `
586
+ window.${versionName} = {
587
+ time: '${versionInfo.time}',
588
+ author: '${versionInfo.author}',
589
+ branch: '${versionInfo.branch}',
590
+ netEnv: '${versionInfo.netEnv}',
543
591
  }
544
- function sortStringList(list) {
545
- list.sort((a, b) => {
546
- if (a > b)
547
- return 1;
548
- if (a < b)
549
- return -1;
550
- return 0;
551
- });
552
- return list;
592
+ `;
593
+ return code;
594
+ }
595
+ code = `
596
+ console.info('[system]', '');
597
+ console.info('[system]', 'Build Time: ${versionInfo.time || ''}');
598
+ console.info('[system]', 'Build Author: ${versionInfo.author || ''}');
599
+ console.info('[system]', 'Build Branch: ${versionInfo.branch || ''}');
600
+ console.info('[system]', 'Build Net Env: ${versionInfo.netEnv || ''}');
601
+ `;
602
+ return code;
553
603
  }
554
- function parseSetDeps(deps) {
555
- return Object.keys(deps).reduce((acc, item) => {
556
- acc[item] = Array.from(deps[item]);
557
- sortStringList(acc[item]);
558
- return acc;
559
- }, {});
604
+ function getCommitCode(versionName) {
605
+ let commitInfo = {};
606
+ try {
607
+ commitInfo = tComm.getGitCommitInfo();
608
+ }
609
+ catch (err) { }
610
+ if (commitInfo.timeStamp) {
611
+ commitInfo.date = tComm.timeStampFormat(commitInfo.timeStamp, 'yyyy-MM-dd hh:mm:ss');
612
+ }
613
+ let code = '';
614
+ if (versionName) {
615
+ code = `
616
+ window.${versionName} = {
617
+ message: '${parseQuote(commitInfo.message)}',
618
+ author: '${commitInfo.author}',
619
+ date: '${commitInfo.date}',
620
+ hash: '${commitInfo.hash}',
560
621
  }
561
- function getRelativePath(filePath) {
562
- return path__namespace.relative(process.cwd(), path__namespace.resolve(filePath));
622
+ `;
623
+ return code;
624
+ }
625
+ code = `
626
+ console.info('[system]', '');
627
+ console.info('[system]', 'Last Commit Message: ${parseQuote(commitInfo.message) || ''}');
628
+ console.info('[system]', 'Last Commit Author: ${commitInfo.author || ''}');
629
+ console.info('[system]', 'Last Commit Time: ${commitInfo.date || ''}');
630
+ console.info('[system]', 'Last Commit Hash: ${commitInfo.hash || ''}');
631
+ `;
632
+ return code;
563
633
  }
634
+ function getMpVersionCode() {
635
+ return `
636
+ var uni = (typeof wx !== 'undefined' && wx)
637
+ || (typeof qq !== 'undefined' && qq)
638
+ || (typeof jd !== 'undefined' && jd)
639
+ || (typeof my !== 'undefined' && my);
564
640
 
565
- const DEFAULT_KEYS = [
566
- 'UNI_APP_X',
567
- 'APP',
568
- 'APP_UVUE',
569
- 'APP_NVUE',
570
- 'APP_PLUS',
571
- 'APP_PLUS_NVUE',
572
- 'APP_VUE',
573
- 'APP_ANDROID',
574
- 'APP_IOS',
575
- 'APP_HARMONY',
576
- 'H5',
577
- 'MP',
578
- 'MP_360',
579
- 'MP_ALIPAY',
580
- 'MP_BAIDU',
581
- 'MP_QQ',
582
- 'MP_LARK',
583
- 'MP_TOUTIAO',
584
- 'MP_WEIXIN',
585
- 'MP_KUAISHOU',
586
- 'MP_JD',
587
- 'QUICKAPP_NATIVE',
588
- 'QUICKAPP_WEBVIEW',
589
- 'QUICKAPP_WEBVIEW_HUAWEI',
590
- 'QUICKAPP_WEBVIEW_UNION',
591
- 'VUE2',
592
- 'VUE3',
593
- 'WEB',
594
- ];
595
- const DEFAULT_CONTEXT_OBJECT = DEFAULT_KEYS.reduce((acc, key) => ({
596
- ...acc,
597
- [key]: false,
598
- }), {});
599
-
600
- const scssLogger = {
601
- warn(message, options) {
602
- // Mute "Mixed Declarations" warning
603
- if (options.deprecation && message.includes('mixed-decls')) {
604
- return;
605
- }
606
- // List all other warnings
607
- console.warn(`▲ [WARNING]: ${message}`);
608
- },
609
- };
610
-
611
- function getDeps(dir) {
612
- const data = tComm.readFileSync(path__default["default"].resolve(dir, 'package.json'), true);
613
- return Object.keys({
614
- ...data.dependencies,
615
- });
641
+ var miniProgram = (uni.getAccountInfoSync && uni.getAccountInfoSync().miniProgram) || {};
642
+ var systemInfo = (uni.getSystemInfoSync && uni.getSystemInfoSync()) || {};
643
+ var envVersionMap = {
644
+ develop: '开发版',
645
+ trial: '体验版',
646
+ release: '正式版'
616
647
  }
648
+ var { envVersion = '', version = '' } = miniProgram;
649
+ var { brand, model, pixelRatio } = systemInfo;
650
+ var versionDesc = \`\${envVersion}(\${envVersionMap[envVersion] || ''})\`;
617
651
 
618
- function getParent(path, level) {
619
- if (!level) {
620
- return path.parent;
621
- }
622
- return getParent(path.parentPath, level - 1);
623
- }
624
- function findDependencies(content) {
625
- const parser = require('@babel/parser');
626
- const traverse = require('@babel/traverse').default;
627
- const sourceList = [];
628
- const ast = parser.parse(content, {
629
- // 不加这个配置,报错:SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"'
630
- sourceType: 'module',
631
- plugins: ['typescript'],
632
- });
633
- traverse(ast, {
634
- CallExpression(path) {
635
- if (path.node.callee.name === 'require') {
636
- if (path.node.arguments[0].type === 'StringLiteral') {
637
- sourceList.push(path.node.arguments[0].value);
638
- }
639
- if (getParent(path, 0).type === 'ExpressionStatement'
640
- && getParent(path, 1).type === 'BlockStatement'
641
- && getParent(path, 2).type === 'ObjectMethod'
642
- && getParent(path, 3).type === 'ObjectExpression'
643
- && getParent(path, 4)?.type === 'ObjectProperty'
644
- && getParent(path, 4)?.key?.name === 'components'
645
- && getParent(path, 5)?.type === 'ObjectExpression'
646
- && getParent(path, 6)?.type === 'ExportDefaultDeclaration'
647
- && path.node.arguments[0].type === 'ArrayExpression') {
648
- sourceList.push(path.node.arguments[0].elements[0].value);
649
- }
650
- }
651
- },
652
- ImportDeclaration(path) {
653
- sourceList.push(path.node.source.value);
654
- },
655
- });
656
- return sourceList;
652
+ console.info('[system]', '');
653
+ console.info('[system]', \`Env Version:\${envVersion ? versionDesc : ''}\`);
654
+ console.info('[system]', \`Version:\${version}\`);
655
+
656
+ console.info('[system]', '');
657
+ console.info('[system]', \`Brand:\${brand}, \${model}\`);
658
+ console.info('[system]', \`PixelRatio:\${pixelRatio}\`);
659
+ `;
657
660
  }
658
-
659
- function checkH5() {
660
- return process.env.VUE_APP_PLATFORM === 'h5';
661
+ function getMpInsertCode() {
662
+ const insertCode = `
663
+ try {
664
+ setTimeout(() => {
665
+ ${getVersionCode()}
666
+ ${getCommitCode()}
667
+ ${getMpVersionCode()}
668
+ }, 2000);
669
+ } catch(err) {}
670
+ `;
671
+ return insertCode;
661
672
  }
662
-
663
- const LOADER_PROD = 'loader.prod.js';
664
- function getLoaderFile(dir = '', isProd = false) {
665
- if (isProd) {
666
- return path__default["default"].resolve(dir, LOADER_PROD);
667
- }
668
- return path__default["default"].resolve(dir, 'loader.js');
673
+ function getGenVersionPluginOptions(options) {
674
+ const buildName = options?.buildName || '';
675
+ const commitName = options?.commitName || '';
676
+ const delay = options?.delay === undefined ? 10 : options?.delay;
677
+ return {
678
+ buildName,
679
+ commitName,
680
+ delay,
681
+ };
669
682
  }
670
- function getLoaderProdFile(dir = '') {
671
- return path__default["default"].resolve(dir, LOADER_PROD);
683
+ function getWebInsertCode(options) {
684
+ const { buildName, commitName, delay } = getGenVersionPluginOptions(options || {});
685
+ return `
686
+ <script>
687
+ try {
688
+ setTimeout(() => {
689
+ ${getVersionCode(buildName)}
690
+ ${getCommitCode(commitName)}
691
+ }, ${delay});
692
+ } catch(err) {}
693
+ </script>
694
+ `;
672
695
  }
673
696
 
674
- const LOG_KEY = 'LOADER_LOGS';
675
- function saveLoaderLog() {
676
- const loaderLogs = global[LOG_KEY];
677
- if (!loaderLogs)
678
- return;
679
- Object.keys(loaderLogs).forEach((file) => {
680
- saveJsonToLog(loaderLogs[file], file);
681
- });
697
+ const BASE_SCSS = 'base.scss';
698
+ function getStyleList(dir) {
699
+ const cssList = fs__namespace.readdirSync(dir);
700
+ const filtered = cssList
701
+ .filter(item => item.endsWith('scss') && !item.startsWith(BASE_SCSS))
702
+ .map(item => item.replace(/\.scss$/, ''));
703
+ return filtered;
682
704
  }
683
- function recordLoaderLog(file, content) {
684
- if (!global[LOG_KEY]) {
685
- global[LOG_KEY] = {};
686
- }
687
- if (!global[LOG_KEY][file]) {
688
- global[LOG_KEY][file] = [];
689
- }
690
- global[LOG_KEY][file].push(content);
705
+ function genInjectContent({ styleList, componentName, topElement, dir = '', }) {
706
+ const styleStr = styleList.map((item) => `
707
+ &--type-${item} {
708
+ @import './${dir}${item}.scss';
709
+ }`).join('\n');
710
+ return `
711
+ ${topElement}.${componentName} {
712
+ ${styleStr}
691
713
  }
692
-
693
- function getWxmlAndWxssPostfix() {
694
- const map = Object.keys(PLATFORM_MAP).reduce((acc, item) => {
695
- acc[PLATFORM_MAP[item]] = item;
696
- return acc;
697
- }, {});
698
- const key = map[process.env.UNI_PLATFORM || ''];
699
- return [
700
- HTML_MAP[key],
701
- CSS_MAP[key],
702
- ];
714
+ `;
715
+ }
716
+ function getComponentName(dir) {
717
+ const tPath = tComm.normalizePath(dir);
718
+ const reg = /\/([^/]+)\/css/;
719
+ const match = tPath.match(reg);
720
+ return match?.[1] || '';
703
721
  }
704
722
 
705
- function getProjectName() {
706
- let result = '';
707
- try {
708
- const json = tComm.readFileSync('package.json', true) || {};
709
- result = json.name || '';
723
+ function findNodeModuleFile({ name, target, filePath, root, }) {
724
+ const iRoot = root ?? process.cwd();
725
+ const NODE_MODULES = 'node_modules';
726
+ const PNPM = `${NODE_MODULES}/.pnpm`;
727
+ const nodeModulesTargetFile = path__default["default"].resolve(iRoot, NODE_MODULES, name, filePath);
728
+ const exist = fs__default["default"].existsSync(nodeModulesTargetFile);
729
+ if (exist) {
730
+ return [
731
+ nodeModulesTargetFile,
732
+ ];
710
733
  }
711
- catch (err) { }
712
- return result;
713
- }
714
- function getSubProjectName() {
715
- const name = process.env.VUE_APP_DIR?.split('/')?.[1] || '';
716
- return name;
734
+ const pnpmRoot = path__default["default"].resolve(iRoot, PNPM);
735
+ if (!fs__default["default"].existsSync(pnpmRoot)) {
736
+ return [];
737
+ }
738
+ const pnpmList = fs__default["default"].readdirSync(pnpmRoot);
739
+ const list = pnpmList.filter(item => item.startsWith(target));
740
+ const innerFileList = list.map((file) => {
741
+ const targetFile = path__default["default"].resolve(`${PNPM}/${file}/node_modules/${name}/${filePath}`);
742
+ return targetFile;
743
+ }).filter(file => fs__default["default"].existsSync(file));
744
+ return innerFileList;
717
745
  }
718
746
 
719
- // 读取 manifest.json ,修改后重新写入
720
- const manifestPath = `${process.env.UNI_INPUT_DIR}/manifest.json`;
721
- let originManifest = '';
722
- try {
723
- originManifest = fs__namespace.readFileSync(manifestPath, { encoding: 'utf-8' });
724
- }
725
- catch (err) {
747
+ function replaceDirective(source, list) {
748
+ if (!list.length)
749
+ return source;
750
+ const reg = new RegExp(`(?<=<[^<]+)v-${list.join('|')}=?[^\\s]*`, 'g');
751
+ const newSource = source.replace(reg, '');
752
+ return newSource;
726
753
  }
727
- let Manifest = originManifest;
728
- function replaceManifest(path, value) {
729
- const arr = path.split('.');
730
- const len = arr.length;
731
- const lastItem = arr[len - 1];
732
- let i = 0;
733
- const ManifestArr = Manifest.split(/\n/);
734
- for (let index = 0; index < ManifestArr.length; index++) {
735
- const item = ManifestArr[index];
736
- if (new RegExp(`"${arr[i]}"`).test(item))
737
- i = i + 1;
738
- if (i === len) {
739
- const hasComma = /,/.test(item);
740
- ManifestArr[index] = item.replace(new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`), `"${lastItem}": ${value}${hasComma ? ',' : ''}`);
741
- break;
742
- }
754
+
755
+ const htmlReg = /(?<=<template>)([\s\S]+)(?=<\/template>)/;
756
+ const imgReg = /(<img[\s\S]+?)v-lazy=(?:"|')(.*?)(?:"|')([\s\S]*?>)/g;
757
+ const sizeReg = /(?<=[\s\n]+(?:data-)?)size=(?:"|')(\d+)(?:"|')/;
758
+ const widthReg = /(?<=[\s\n]+(?:data-)?)width=(?:"|')(\d+)(?:"|')/;
759
+ const heightReg = /(?<=[\s\n]+(?:data-)?)height=(?:"|')(\d+)(?:"|')/;
760
+ function vLazyCore(source, options) {
761
+ const { urlHandler } = options || {};
762
+ let html = '';
763
+ const match = source.match(htmlReg);
764
+ if (match?.[1]) {
765
+ html = match[1];
743
766
  }
744
- Manifest = ManifestArr.join('\n');
745
- }
746
- function updateManifest(path, value) {
747
- replaceManifest(path, value);
748
- fs__namespace.writeFileSync(manifestPath, Manifest, {
749
- flag: 'w',
750
- });
751
- }
752
- function revertManifest() {
753
- fs__namespace.writeFileSync(manifestPath, originManifest, {
754
- flag: 'w',
755
- });
767
+ if (!html)
768
+ return source;
769
+ if (!html.match(imgReg))
770
+ return source;
771
+ const newHtml = handleImg(html, urlHandler);
772
+ const newSource = source.replace(htmlReg, () => newHtml);
773
+ return newSource;
756
774
  }
757
-
758
- function getSubProjectRoot({ root, appDir, }) {
759
- let subProjectRoot = `${path__default["default"].resolve(root, `./src/${appDir}`)}/`;
760
- if (!appDir) {
761
- subProjectRoot = path__default["default"].resolve(root, './src/');
775
+ function getSize(pre, post, reg) {
776
+ let size = '';
777
+ const preMatch = pre.match(reg);
778
+ const postMatch = post.match(reg);
779
+ if (preMatch?.[1]) {
780
+ size = preMatch[1];
762
781
  }
763
- return subProjectRoot;
782
+ else if (postMatch?.[1]) {
783
+ size = postMatch[1];
784
+ }
785
+ return size;
764
786
  }
765
- function getSubProjectConfig(subProjectRoot) {
766
- let res = {};
767
- try {
768
- // eslint-disable-next-line @typescript-eslint/no-require-imports
769
- res = require(path__default["default"].resolve(subProjectRoot, 'config.js'));
787
+ function getImgSrc({ urlHandler, src, size, width, height, }) {
788
+ let srcStr = src;
789
+ if (!urlHandler) {
790
+ return src;
770
791
  }
771
- catch (err) { }
792
+ if (width && height) {
793
+ srcStr = `${urlHandler}(${src}, ${width}, ${height})`;
794
+ }
795
+ else if (size) {
796
+ srcStr = `${urlHandler}(${src}, ${size}, ${size})`;
797
+ }
798
+ else {
799
+ srcStr = `${urlHandler}(${src})`;
800
+ }
801
+ return srcStr;
802
+ }
803
+ function handleImg(str = '', urlHandler = '') {
804
+ const res = str.replace(imgReg, (...args) => {
805
+ const { 1: pre, 2: src, 3: post } = args;
806
+ const size = getSize(pre, post, sizeReg);
807
+ const width = getSize(pre, post, widthReg);
808
+ const height = getSize(pre, post, heightReg);
809
+ const srcStr = getImgSrc({
810
+ urlHandler,
811
+ src,
812
+ size,
813
+ width,
814
+ height,
815
+ });
816
+ const innerRes = `${pre} :src="${srcStr}" lazy-load ${post}`;
817
+ return innerRes;
818
+ });
772
819
  return res;
773
820
  }
774
821
 
775
- const getPlatform = () => process.env.UNI_PLATFORM || '';
776
- const getUtsPlatform = () => process.env.UNI_UTS_PLATFORM || '';
777
- const getAppPlatform = () => process.env.UNI_APP_PLATFORM || '';
778
- const isH5 = () => getPlatform() === 'h5';
779
- const isApp = () => getPlatform() === 'app';
780
- const isAppAndroid = () => getAppPlatform() === 'android' || getUtsPlatform() === 'app-android';
781
- const isAppIOS = () => getAppPlatform() === 'ios' || getUtsPlatform() === 'app-ios';
782
- const isMp = () => /^mp-/i.test(getPlatform());
783
- const isMpWeixin = () => getPlatform() === 'mp-weixin';
784
- const isMpAlipay = () => getPlatform() === 'mp-alipay';
785
- const isMpBaidu = () => getPlatform() === 'mp-baidu';
786
- const isMpKuaishou = () => getPlatform() === 'mp-kuaishou';
787
- const isMpQQ = () => getPlatform() === 'mp-qq';
788
- const isMpToutiao = () => getPlatform() === 'mp-toutiao';
789
- const isQuickapp = () => /^quickapp-webview/i.test(getPlatform());
790
- const isQuickappUnion = () => getPlatform() === 'quickapp-webview-union';
791
- const isQuickappHuawei = () => getPlatform() === 'quickapp-webview-huawei';
792
-
793
822
  exports.AEGIS_EXTERNAL_SCRIPT_LINK = AEGIS_EXTERNAL_SCRIPT_LINK;
794
823
  exports.ALL_PLATFORM = ALL_PLATFORM;
795
824
  exports.BASE_SCSS = BASE_SCSS;
@@ -819,6 +848,7 @@ exports.getCommitCode = getCommitCode;
819
848
  exports.getComponentName = getComponentName;
820
849
  exports.getDeps = getDeps;
821
850
  exports.getGenVersionPluginOptions = getGenVersionPluginOptions;
851
+ exports.getImportOrderRule = getImportOrderRule;
822
852
  exports.getLoaderFile = getLoaderFile;
823
853
  exports.getLoaderProdFile = getLoaderProdFile;
824
854
  exports.getMpInsertCode = getMpInsertCode;