@spcsn/taro-helper 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.js ADDED
@@ -0,0 +1,697 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.babelKit = exports.fs = exports.getModuleDefaultExport = exports.getAllFilesInFolder = exports.applyArrayedVisitors = exports.mergeVisitors = exports.recursiveMerge = exports.pascalCase = exports.isNodeModule = void 0;
40
+ exports.normalizePath = normalizePath;
41
+ exports.isNpmPkg = isNpmPkg;
42
+ exports.isQuickAppPkg = isQuickAppPkg;
43
+ exports.isAliasPath = isAliasPath;
44
+ exports.replaceAliasPath = replaceAliasPath;
45
+ exports.promoteRelativePath = promoteRelativePath;
46
+ exports.resolveStylePath = resolveStylePath;
47
+ exports.printLog = printLog;
48
+ exports.recursiveFindNodeModules = recursiveFindNodeModules;
49
+ exports.getUserHomeDir = getUserHomeDir;
50
+ exports.getTaroPath = getTaroPath;
51
+ exports.getConfig = getConfig;
52
+ exports.getHash = getHash;
53
+ exports.getSystemUsername = getSystemUsername;
54
+ exports.shouldUseYarn = shouldUseYarn;
55
+ exports.shouldUseCnpm = shouldUseCnpm;
56
+ exports.isEmptyObject = isEmptyObject;
57
+ exports.resolveSync = resolveSync;
58
+ exports.resolveMainFilePath = resolveMainFilePath;
59
+ exports.resolveScriptPath = resolveScriptPath;
60
+ exports.generateEnvList = generateEnvList;
61
+ exports.getNpmPackageAbsolutePath = getNpmPackageAbsolutePath;
62
+ exports.generateConstantsList = generateConstantsList;
63
+ exports.cssImports = cssImports;
64
+ exports.emptyDirectory = emptyDirectory;
65
+ exports.getInstalledNpmPkgPath = getInstalledNpmPkgPath;
66
+ exports.getInstalledNpmPkgVersion = getInstalledNpmPkgVersion;
67
+ exports.readDirWithFileTypes = readDirWithFileTypes;
68
+ exports.extnameExpRegOf = extnameExpRegOf;
69
+ exports.addPlatforms = addPlatforms;
70
+ exports.removeHeadSlash = removeHeadSlash;
71
+ exports.readPageConfig = readPageConfig;
72
+ exports.readConfig = readConfig;
73
+ exports.removePathPrefix = removePathPrefix;
74
+ const child_process = __importStar(require("node:child_process"));
75
+ const node_crypto_1 = require("node:crypto");
76
+ const os = __importStar(require("node:os"));
77
+ const path = __importStar(require("node:path"));
78
+ const babel = __importStar(require("@babel/core"));
79
+ const generator_1 = __importDefault(require("@babel/generator"));
80
+ const babelParser = __importStar(require("@babel/parser"));
81
+ const traverse_1 = __importDefault(require("@babel/traverse"));
82
+ const t = __importStar(require("@babel/types"));
83
+ const fs = __importStar(require("fs-extra"));
84
+ exports.fs = fs;
85
+ const lodash_1 = require("lodash");
86
+ const constants_1 = require("./constants");
87
+ const esbuild_1 = require("./esbuild");
88
+ const terminal_1 = require("./terminal");
89
+ const execSync = child_process.execSync;
90
+ function normalizePath(path) {
91
+ return path.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
92
+ }
93
+ const isNodeModule = (filename) => constants_1.REG_NODE_MODULES.test(filename);
94
+ exports.isNodeModule = isNodeModule;
95
+ function isNpmPkg(name) {
96
+ if (/^(\.|\/)/.test(name)) {
97
+ return false;
98
+ }
99
+ return true;
100
+ }
101
+ function isQuickAppPkg(name) {
102
+ return /^@(system|service)\.[a-zA-Z]{1,}/.test(name);
103
+ }
104
+ function isAliasPath(name, pathAlias = {}) {
105
+ const prefixes = Object.keys(pathAlias);
106
+ if (prefixes.length === 0) {
107
+ return false;
108
+ }
109
+ return prefixes.includes(name) || new RegExp(`^(${prefixes.join('|')})/`).test(name);
110
+ }
111
+ function replaceAliasPath(filePath, name, pathAlias = {}) {
112
+ // 后续的 path.join 在遇到符号链接时将会解析为真实路径,如果
113
+ // 这里的 filePath 没有做同样的处理,可能会导致 import 指向
114
+ // 源代码文件,导致文件被意外修改
115
+ filePath = fs.realpathSync(filePath);
116
+ const prefixes = Object.keys(pathAlias);
117
+ if (prefixes.includes(name)) {
118
+ return promoteRelativePath(path.relative(filePath, fs.realpathSync(resolveScriptPath(pathAlias[name]))));
119
+ }
120
+ const reg = new RegExp(`^(${prefixes.join('|')})/(.*)`);
121
+ name = name.replace(reg, function (_m, $1, $2) {
122
+ return promoteRelativePath(path.relative(filePath, path.join(pathAlias[$1], $2)));
123
+ });
124
+ return name;
125
+ }
126
+ function promoteRelativePath(fPath) {
127
+ const fPathArr = fPath.split(path.sep);
128
+ let dotCount = 0;
129
+ fPathArr.forEach((item) => {
130
+ if (item.indexOf('..') >= 0) {
131
+ dotCount++;
132
+ }
133
+ });
134
+ if (dotCount === 1) {
135
+ fPathArr.splice(0, 1, '.');
136
+ return fPathArr.join('/');
137
+ }
138
+ if (dotCount > 1) {
139
+ fPathArr.splice(0, 1);
140
+ return fPathArr.join('/');
141
+ }
142
+ return normalizePath(fPath);
143
+ }
144
+ function resolveStylePath(p) {
145
+ const realPath = p;
146
+ const removeExtPath = p.replace(path.extname(p), '');
147
+ const taroEnv = process.env.TARO_ENV;
148
+ for (let i = 0; i < constants_1.CSS_EXT.length; i++) {
149
+ const item = constants_1.CSS_EXT[i];
150
+ if (taroEnv) {
151
+ if (fs.existsSync(`${removeExtPath}.${taroEnv}${item}`)) {
152
+ return `${removeExtPath}.${taroEnv}${item}`;
153
+ }
154
+ }
155
+ if (fs.existsSync(`${p}${item}`)) {
156
+ return `${p}${item}`;
157
+ }
158
+ }
159
+ return realPath;
160
+ }
161
+ function printLog(type, tag, filePath) {
162
+ const typeShow = constants_1.processTypeMap[type];
163
+ const tagLen = tag.replace(/[\u0391-\uFFE5]/g, 'aa').length;
164
+ const tagFormatLen = 8;
165
+ if (tagLen < tagFormatLen) {
166
+ const rightPadding = new Array(tagFormatLen - tagLen + 1).join(' ');
167
+ tag += rightPadding;
168
+ }
169
+ const padding = '';
170
+ filePath = filePath || '';
171
+ if (typeof typeShow.color === 'string') {
172
+ console.log(terminal_1.chalk[typeShow.color](typeShow.name), padding, tag, padding, filePath);
173
+ }
174
+ else {
175
+ console.log(typeShow.color(typeShow.name), padding, tag, padding, filePath);
176
+ }
177
+ }
178
+ function recursiveFindNodeModules(filePath, lastFindPath) {
179
+ const findWorkspaceRoot = require('find-yarn-workspace-root');
180
+ if (lastFindPath && normalizePath(filePath) === normalizePath(lastFindPath)) {
181
+ return filePath;
182
+ }
183
+ const dirname = path.dirname(filePath);
184
+ const workspaceRoot = findWorkspaceRoot(dirname);
185
+ const nodeModules = path.join(workspaceRoot || dirname, 'node_modules');
186
+ if (fs.existsSync(nodeModules)) {
187
+ return nodeModules;
188
+ }
189
+ if (dirname.split(path.sep).length <= 1) {
190
+ printLog("error" /* processTypeEnum.ERROR */, `在${dirname}目录下`, '未找到node_modules文件夹,请先安装相关依赖库!');
191
+ return nodeModules;
192
+ }
193
+ return recursiveFindNodeModules(dirname, filePath);
194
+ }
195
+ function getUserHomeDir() {
196
+ function homedir() {
197
+ const env = process.env;
198
+ const home = env.HOME;
199
+ const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
200
+ if (process.platform === 'win32') {
201
+ return env.USERPROFILE || '' + env.HOMEDRIVE + env.HOMEPATH || home || '';
202
+ }
203
+ if (process.platform === 'darwin') {
204
+ return home || (user ? '/Users/' + user : '');
205
+ }
206
+ if (process.platform === 'linux') {
207
+ return home || (process.getuid?.() === 0 ? '/root' : user ? '/home/' + user : '');
208
+ }
209
+ return home || '';
210
+ }
211
+ return typeof os.homedir === 'function' ? os.homedir() : homedir();
212
+ }
213
+ function getTaroPath() {
214
+ const taroPath = path.join(getUserHomeDir(), constants_1.TARO_CONFIG_FOLDER);
215
+ if (!fs.existsSync(taroPath)) {
216
+ fs.ensureDirSync(taroPath);
217
+ }
218
+ return taroPath;
219
+ }
220
+ function getConfig() {
221
+ const configPath = path.join(getTaroPath(), 'config.json');
222
+ if (fs.existsSync(configPath)) {
223
+ return require(configPath);
224
+ }
225
+ return {};
226
+ }
227
+ function getHash(text) {
228
+ return (0, node_crypto_1.createHash)('sha256').update(text).digest('hex').substring(0, 8);
229
+ }
230
+ function getSystemUsername() {
231
+ const userHome = getUserHomeDir();
232
+ const systemUsername = process.env.USER || path.basename(userHome);
233
+ return systemUsername;
234
+ }
235
+ function shouldUseYarn() {
236
+ try {
237
+ execSync('yarn --version', { stdio: 'ignore' });
238
+ return true;
239
+ }
240
+ catch (e) {
241
+ return false;
242
+ }
243
+ }
244
+ function shouldUseCnpm() {
245
+ try {
246
+ execSync('cnpm --version', { stdio: 'ignore' });
247
+ return true;
248
+ }
249
+ catch (e) {
250
+ return false;
251
+ }
252
+ }
253
+ function isEmptyObject(obj) {
254
+ if (obj == null) {
255
+ return true;
256
+ }
257
+ for (const key in obj) {
258
+ if (obj.hasOwnProperty(key)) {
259
+ return false;
260
+ }
261
+ }
262
+ return true;
263
+ }
264
+ function resolveSync(id, opts = {}) {
265
+ try {
266
+ const resolve = require('resolve').sync;
267
+ return resolve(id, {
268
+ ...opts,
269
+ packageFilter(pkg, pkgfile, dir) {
270
+ if (opts.packageFilter) {
271
+ pkg = opts.packageFilter(pkg, pkgfile, dir);
272
+ }
273
+ else if (opts.mainFields?.length) {
274
+ pkg.main = pkg[opts.mainFields.find((field) => pkg[field] && typeof pkg[field] === 'string') || 'main'];
275
+ }
276
+ return pkg;
277
+ },
278
+ });
279
+ }
280
+ catch (error) {
281
+ return null;
282
+ }
283
+ }
284
+ function resolveMainFilePath(p, extArrs = constants_1.SCRIPT_EXT) {
285
+ if (p.startsWith('pages/') || p === 'app.config') {
286
+ return p;
287
+ }
288
+ const realPath = p;
289
+ const taroEnv = process.env.TARO_ENV;
290
+ for (let i = 0; i < extArrs.length; i++) {
291
+ const item = extArrs[i];
292
+ if (taroEnv) {
293
+ if (fs.existsSync(`${p}.${taroEnv}${item}`)) {
294
+ return `${p}.${taroEnv}${item}`;
295
+ }
296
+ if (fs.existsSync(`${p}${path.sep}index.${taroEnv}${item}`)) {
297
+ return `${p}${path.sep}index.${taroEnv}${item}`;
298
+ }
299
+ if (fs.existsSync(`${p.replace(/\/index$/, `.${taroEnv}/index`)}${item}`)) {
300
+ return `${p.replace(/\/index$/, `.${taroEnv}/index`)}${item}`;
301
+ }
302
+ }
303
+ if (fs.existsSync(`${p}${item}`)) {
304
+ return `${p}${item}`;
305
+ }
306
+ if (fs.existsSync(`${p}${path.sep}index${item}`)) {
307
+ return `${p}${path.sep}index${item}`;
308
+ }
309
+ }
310
+ // 存在多端页面但是对应的多端页面配置不存在时,使用该页面默认配置
311
+ if (taroEnv && path.parse(p).base.endsWith(`.${taroEnv}.config`)) {
312
+ const idx = p.lastIndexOf(`.${taroEnv}.config`);
313
+ return resolveMainFilePath(p.slice(0, idx) + '.config');
314
+ }
315
+ return realPath;
316
+ }
317
+ function resolveScriptPath(p) {
318
+ return resolveMainFilePath(p);
319
+ }
320
+ function generateEnvList(env) {
321
+ const res = {};
322
+ if (env && !isEmptyObject(env)) {
323
+ for (const key in env) {
324
+ try {
325
+ res[`process.env.${key}`] = JSON.parse(env[key]);
326
+ }
327
+ catch (err) {
328
+ res[`process.env.${key}`] = env[key];
329
+ }
330
+ }
331
+ }
332
+ return res;
333
+ }
334
+ /**
335
+ * 获取 npm 文件或者依赖的绝对路径
336
+ *
337
+ * @param {string} 参数 1 - 组件路径
338
+ * @param {string} 参数 2 - 文件扩展名
339
+ * @returns {string} npm 文件绝对路径
340
+ */
341
+ function getNpmPackageAbsolutePath(npmPath, defaultFile = 'index') {
342
+ try {
343
+ let packageName = '';
344
+ let componentRelativePath = '';
345
+ const packageParts = npmPath.split(path.sep);
346
+ // 获取 npm 包名和指定的包文件路径
347
+ // taro-loader/path/index => packageName = taro-loader, componentRelativePath = path/index
348
+ // @spcsn/taro-runtime/path/index => packageName = @spcsn/taro-runtime, componentRelativePath = path/index
349
+ if (npmPath.startsWith('@')) {
350
+ packageName = packageParts.slice(0, 2).join(path.sep);
351
+ componentRelativePath = packageParts.slice(2).join(path.sep);
352
+ }
353
+ else {
354
+ packageName = packageParts[0];
355
+ componentRelativePath = packageParts.slice(1).join(path.sep);
356
+ }
357
+ // 没有指定的包文件路径统一使用 defaultFile
358
+ componentRelativePath || (componentRelativePath = defaultFile);
359
+ // require.resolve 解析的路径会包含入口文件路径,通过正则过滤一下
360
+ const match = require.resolve(packageName).match(new RegExp('.*' + packageName));
361
+ if (!match?.length)
362
+ return null;
363
+ const packagePath = match[0];
364
+ return path.join(packagePath, `./${componentRelativePath}`);
365
+ }
366
+ catch (error) {
367
+ return null;
368
+ }
369
+ }
370
+ function generateConstantsList(constants) {
371
+ const res = {};
372
+ if (constants && !isEmptyObject(constants)) {
373
+ for (const key in constants) {
374
+ if ((0, lodash_1.isPlainObject)(constants[key])) {
375
+ res[key] = generateConstantsList(constants[key]);
376
+ }
377
+ else {
378
+ try {
379
+ res[key] = JSON.parse(constants[key]);
380
+ }
381
+ catch (err) {
382
+ res[key] = constants[key];
383
+ }
384
+ }
385
+ }
386
+ }
387
+ return res;
388
+ }
389
+ function cssImports(content) {
390
+ const results = [];
391
+ const cssImportRegx = new RegExp(constants_1.REG_CSS_IMPORT);
392
+ let match;
393
+ content = String(content).replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '');
394
+ while ((match = cssImportRegx.exec(content))) {
395
+ results.push(match[2]);
396
+ }
397
+ return results;
398
+ }
399
+ /*eslint-disable*/
400
+ const retries = process.platform === 'win32' ? 100 : 1;
401
+ function emptyDirectory(dirPath, opts = { excludes: [] }) {
402
+ if (fs.existsSync(dirPath)) {
403
+ fs.readdirSync(dirPath).forEach((file) => {
404
+ const curPath = path.join(dirPath, file);
405
+ if (fs.lstatSync(curPath).isDirectory()) {
406
+ let removed = false;
407
+ let i = 0; // retry counter
408
+ do {
409
+ try {
410
+ const excludes = Array.isArray(opts.excludes) ? opts.excludes : [opts.excludes];
411
+ const canRemove = !excludes.length ||
412
+ !excludes.some((item) => (typeof item === 'string' ? curPath.indexOf(item) >= 0 : item.test(curPath)));
413
+ if (canRemove) {
414
+ emptyDirectory(curPath);
415
+ fs.rmdirSync(curPath);
416
+ }
417
+ removed = true;
418
+ }
419
+ catch (e) {
420
+ }
421
+ finally {
422
+ if (++i < retries) {
423
+ continue;
424
+ }
425
+ }
426
+ } while (!removed);
427
+ }
428
+ else {
429
+ fs.unlinkSync(curPath);
430
+ }
431
+ });
432
+ }
433
+ }
434
+ /* eslint-enable */
435
+ const pascalCase = (str) => str.charAt(0).toUpperCase() + (0, lodash_1.camelCase)(str.substr(1));
436
+ exports.pascalCase = pascalCase;
437
+ function getInstalledNpmPkgPath(pkgName, basedir) {
438
+ try {
439
+ const resolve = require('resolve').sync;
440
+ return resolve(`${pkgName}/package.json`, { basedir });
441
+ }
442
+ catch (err) {
443
+ return null;
444
+ }
445
+ }
446
+ function getInstalledNpmPkgVersion(pkgName, basedir) {
447
+ const pkgPath = getInstalledNpmPkgPath(pkgName, basedir);
448
+ if (!pkgPath) {
449
+ return null;
450
+ }
451
+ return fs.readJSONSync(pkgPath).version;
452
+ }
453
+ const recursiveMerge = (src, ...args) => {
454
+ return (0, lodash_1.mergeWith)(src, ...args, (value, srcValue) => {
455
+ const typeValue = typeof value;
456
+ const typeSrcValue = typeof srcValue;
457
+ if (typeValue !== typeSrcValue)
458
+ return;
459
+ if (Array.isArray(value) && Array.isArray(srcValue)) {
460
+ return value.concat(srcValue);
461
+ }
462
+ if (typeValue === 'object') {
463
+ return (0, exports.recursiveMerge)(value, srcValue);
464
+ }
465
+ });
466
+ };
467
+ exports.recursiveMerge = recursiveMerge;
468
+ const mergeVisitors = (src, ...args) => {
469
+ const validFuncs = ['exit', 'enter'];
470
+ return (0, lodash_1.mergeWith)(src, ...args, (value, srcValue, key, object, srcObject) => {
471
+ if (!object.hasOwnProperty(key) || !srcObject.hasOwnProperty(key)) {
472
+ return undefined;
473
+ }
474
+ const shouldMergeToArray = validFuncs.indexOf(key) > -1;
475
+ if (shouldMergeToArray) {
476
+ return (0, lodash_1.flatMap)([value, srcValue]);
477
+ }
478
+ const [newValue, newSrcValue] = [value, srcValue].map((v) => {
479
+ if (typeof v === 'function') {
480
+ return {
481
+ enter: v,
482
+ };
483
+ }
484
+ else {
485
+ return v;
486
+ }
487
+ });
488
+ return (0, exports.mergeVisitors)(newValue, newSrcValue);
489
+ });
490
+ };
491
+ exports.mergeVisitors = mergeVisitors;
492
+ const applyArrayedVisitors = (obj) => {
493
+ let key;
494
+ for (key in obj) {
495
+ const funcs = obj[key];
496
+ if (Array.isArray(funcs)) {
497
+ obj[key] = (astPath, ...args) => {
498
+ funcs.forEach((func) => {
499
+ func(astPath, ...args);
500
+ });
501
+ };
502
+ }
503
+ else if (typeof funcs === 'object') {
504
+ (0, exports.applyArrayedVisitors)(funcs);
505
+ }
506
+ }
507
+ return obj;
508
+ };
509
+ exports.applyArrayedVisitors = applyArrayedVisitors;
510
+ const getAllFilesInFolder = async (folder, filter = []) => {
511
+ let files = [];
512
+ const list = readDirWithFileTypes(folder);
513
+ await Promise.all(list.map(async (item) => {
514
+ const itemPath = path.join(folder, item.name);
515
+ if (item.isDirectory) {
516
+ const _files = await (0, exports.getAllFilesInFolder)(itemPath, filter);
517
+ files = [...files, ..._files];
518
+ }
519
+ else if (item.isFile) {
520
+ if (!filter.find((rule) => rule === item.name))
521
+ files.push(itemPath);
522
+ }
523
+ }));
524
+ return files;
525
+ };
526
+ exports.getAllFilesInFolder = getAllFilesInFolder;
527
+ function readDirWithFileTypes(folder) {
528
+ const list = fs.readdirSync(folder);
529
+ const res = list.map((name) => {
530
+ const stat = fs.statSync(path.join(folder, name));
531
+ return {
532
+ name,
533
+ isDirectory: stat.isDirectory(),
534
+ isFile: stat.isFile(),
535
+ };
536
+ });
537
+ return res;
538
+ }
539
+ function extnameExpRegOf(filePath) {
540
+ return new RegExp(`${path.extname(filePath)}$`);
541
+ }
542
+ function addPlatforms(platform) {
543
+ const upperPlatform = platform.toLocaleUpperCase();
544
+ if (constants_1.PLATFORMS[upperPlatform])
545
+ return;
546
+ constants_1.PLATFORMS[upperPlatform] = platform;
547
+ }
548
+ const getModuleDefaultExport = (exports) => (exports.__esModule ? exports.default : exports);
549
+ exports.getModuleDefaultExport = getModuleDefaultExport;
550
+ function removeHeadSlash(str) {
551
+ return str.replace(/^(\/|\\)/, '');
552
+ }
553
+ // converts ast nodes to js object
554
+ function exprToObject(node) {
555
+ const types = ['BooleanLiteral', 'StringLiteral', 'NumericLiteral'];
556
+ if (types.includes(node.type)) {
557
+ return node.value;
558
+ }
559
+ if (node.name === 'undefined' && !node.value) {
560
+ return undefined;
561
+ }
562
+ if (node.type === 'NullLiteral') {
563
+ return null;
564
+ }
565
+ if (node.type === 'ObjectExpression') {
566
+ return genProps(node.properties);
567
+ }
568
+ if (node.type === 'ArrayExpression') {
569
+ return node.elements.reduce((acc, el) => [
570
+ ...acc,
571
+ ...(el.type === 'SpreadElement' ? exprToObject(el.argument) : [exprToObject(el)]),
572
+ ], []);
573
+ }
574
+ }
575
+ // converts ObjectExpressions to js object
576
+ function genProps(props) {
577
+ return props.reduce((acc, prop) => {
578
+ if (prop.type === 'SpreadElement') {
579
+ return {
580
+ ...acc,
581
+ ...exprToObject(prop.argument),
582
+ };
583
+ }
584
+ else if (prop.type !== 'ObjectMethod') {
585
+ const v = exprToObject(prop.value);
586
+ if (v !== undefined) {
587
+ return {
588
+ ...acc,
589
+ [prop.key.name || prop.key.value]: v,
590
+ };
591
+ }
592
+ }
593
+ return acc;
594
+ }, {});
595
+ }
596
+ // read page config from a sfc file instead of the regular config file
597
+ function readSFCPageConfig(configPath) {
598
+ if (!fs.existsSync(configPath))
599
+ return {};
600
+ const sfcSource = fs.readFileSync(configPath, 'utf8');
601
+ const dpcReg = /definePageConfig\(\{[\w\W]+?\}\)/g;
602
+ const matches = sfcSource.match(dpcReg);
603
+ let result = {};
604
+ if (matches && matches.length === 1) {
605
+ const callExprHandler = (p) => {
606
+ const { callee } = p.node;
607
+ if (!callee.name)
608
+ return;
609
+ if (callee.name && callee.name !== 'definePageConfig')
610
+ return;
611
+ const configNode = p.node.arguments[0];
612
+ result = exprToObject(configNode);
613
+ p.stop();
614
+ };
615
+ const configSource = matches[0];
616
+ const program = babel.parse(configSource, { filename: '' })?.program;
617
+ program && babel.traverse(program, { CallExpression: callExprHandler });
618
+ }
619
+ return result;
620
+ }
621
+ function readPageConfig(configPath) {
622
+ let result = {};
623
+ const extNames = ['.js', '.jsx', '.ts', '.tsx', '.vue'];
624
+ // check source file extension
625
+ extNames.some((ext) => {
626
+ const tempPath = configPath.replace('.config', ext);
627
+ if (fs.existsSync(tempPath)) {
628
+ try {
629
+ result = readSFCPageConfig(tempPath);
630
+ }
631
+ catch (error) {
632
+ result = {};
633
+ }
634
+ return true;
635
+ }
636
+ });
637
+ return result;
638
+ }
639
+ function readConfig(configPath, options = {}) {
640
+ let result = {};
641
+ if (fs.existsSync(configPath)) {
642
+ if (constants_1.REG_JSON.test(configPath)) {
643
+ result = fs.readJSONSync(configPath);
644
+ }
645
+ else {
646
+ result = (0, esbuild_1.requireWithEsbuild)(configPath, {
647
+ customConfig: {
648
+ alias: options.alias || {},
649
+ define: (0, lodash_1.defaults)({}, options.defineConstants || {}, {
650
+ define: 'define', // Note: 该场景下不支持 AMD 导出,这会导致 esbuild 替换 babel 的 define 方法
651
+ }),
652
+ },
653
+ customSwcConfig: {
654
+ jsc: {
655
+ parser: {
656
+ syntax: 'typescript',
657
+ decorators: true,
658
+ },
659
+ transform: {
660
+ legacyDecorator: true,
661
+ },
662
+ experimental: {
663
+ plugins: [[path.resolve(__dirname, '../swc/swc_plugin_define_config.wasm'), {}]],
664
+ },
665
+ },
666
+ module: {
667
+ type: 'commonjs',
668
+ },
669
+ },
670
+ });
671
+ }
672
+ result = (0, exports.getModuleDefaultExport)(result);
673
+ }
674
+ else {
675
+ result = readPageConfig(configPath);
676
+ }
677
+ return result;
678
+ }
679
+ // 去除路径前缀,比如 /, ./
680
+ function removePathPrefix(filePath = '') {
681
+ const normalizedPath = path.normalize(filePath);
682
+ const parsedPath = path.parse(normalizedPath);
683
+ const { root, dir, base } = parsedPath;
684
+ let result = path.join(dir, base);
685
+ if (result.startsWith(root)) {
686
+ result = result.slice(root.length);
687
+ }
688
+ return result;
689
+ }
690
+ // 集中引入 babel 工具箱,供编译时使用
691
+ exports.babelKit = {
692
+ types: t,
693
+ parse: babelParser.parse,
694
+ generate: generator_1.default,
695
+ traverse: traverse_1.default,
696
+ };
697
+ //# sourceMappingURL=utils.js.map