@aiot-toolkit/shared-utils 1.0.20-importfile-dev.2 → 1.0.20

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/lib/index.js CHANGED
@@ -1,2 +1,574 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.logWarn=logWarn,exports.mkdirsSync=mkdirsSync,exports.getIPv4IPAddress=getIPv4IPAddress,exports.getServerIPAndPort=getServerIPAndPort,exports.getDefaultServerHost=getDefaultServerHost,exports.getClientIPAddress=getClientIPAddress,exports.stripPrefixForIPV4MappedIPV6Address=stripPrefixForIPV4MappedIPV6Address,exports.outputQRCodeOnTerminal=outputQRCodeOnTerminal,exports.relateCwd=relateCwd,exports.equals=equals,exports.extend=extend,exports.renderString=renderString,exports.KnownError=KnownError,exports.setCustomConfig=setCustomConfig,exports.getProjectDslName=getProjectDslName,exports.getDeviceInfo=getDeviceInfo,exports.readJson=readJson,exports.getManifest=getManifest,exports.getUxExtensionList=getUxExtensionList,exports.mergeJsonFile=mergeJsonFile,exports.filterContentByTag=filterContentByTag,Object.defineProperty(exports,"getLaunchPage",{enumerable:!0,get:function(){return _util.getLaunchPage}}),exports.colorconsole=exports.logger=void 0;var _os=_interopRequireDefault(require("os")),_fs=_interopRequireDefault(require("fs")),_path=_interopRequireDefault(require("path")),_http=_interopRequireDefault(require("http")),_console=require("console"),_chalk=_interopRequireDefault(require("chalk")),_qrcodeTerminal=_interopRequireDefault(require("qrcode-terminal")),_config=_interopRequireDefault(require("../config")),_parse=_interopRequireDefault(require("parse5")),_index=_interopRequireDefault(require("parse5/lib/serializer/index.js")),_util=require("./buildMode/util");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const logLevelMap={};function prependLevel(e,t){if(!logLevelMap[e]){const t=e.toUpperCase();logLevelMap[e]=t}"string"==typeof t[0]&&t[0].length>1&&"["!==t[0][0]&&(t[0]=`[${logLevelMap[e]}] ${t[0]}`)}const logger={logs:[],add(e){this.logs.push(e)},clear(){this.logs=[]},get(){return this.logs.join("\n")}};exports.logger=logger;let originConsole=global.console,console=_console.Console?new _console.Console(process.stdout,process.stderr):originConsole;const colorconsole={attach(e){e&&_console.Console&&(console=new _console.Console(e,e))},trace(...e){prependLevel("trace",e),console.trace(...e)},log(...e){prependLevel("log",e),console.log(_chalk.default.green(...e))},info(...e){prependLevel("info",e),console.info(_chalk.default.green(...e))},warn(...e){prependLevel("warn",e),console.warn(_chalk.default.yellow.bold(...e))},error(...e){prependLevel("error",e),console.error(_chalk.default.red.bold(...e))},throw(...e){throw new Error(_chalk.default.red.bold(...e))}};function logWarn(e,t,r){t&&t.length&&t.forEach((t=>{const o=t.line&&t.column?"\t@"+t.line+":"+t.column:"";r||(t.reason.startsWith("ERROR")?colorconsole.error(e.resourcePath,t.reason+o):colorconsole.warn(e.resourcePath,t.reason+o))}))}function mkdirsSync(e){return!!_fs.default.existsSync(e)||(mkdirsSync(_path.default.dirname(e))?(_fs.default.mkdirSync(e),!0):void 0)}function getIPv4IPAddress(){const e=_os.default.networkInterfaces();let t;for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(e[r].every((e=>!("IPv4"===e.family&&!e.internal&&"127.0.0.1"!==e.address)||(t=e,!1))),void 0!==t)break}return t&&t.address}function getServerIPAndPort(e){return(getIPv4IPAddress()||"127.0.0.1")+""+(80===e?"":":"+e)}function getDefaultServerHost(){return getServerIPAndPort(_config.default.server.port)}function getClientIPAddress(e){return stripPrefixForIPV4MappedIPV6Address(e.headers["x-forwarded-for"]||e.connection&&e.connection.remoteAddress||e.socket&&e.socket.remoteAddress||e.connection&&e.connection.socket&&e.connection.socket.remoteAddress)}function stripPrefixForIPV4MappedIPV6Address(e){return/^::1$/.test(e)&&(e="127.0.0.1"),/^::.{0,4}:(\d{1,3}\.){3}\d{1,3}/.test(e)&&(e=e.replace(/^.*:/,"")),e}function outputQRCodeOnTerminal(e){console.info(`\nGenerate QR code for HTTP server: ${e}`),_qrcodeTerminal.default.generate(e,{small:!0})}function relateCwd(e){const t=_config.default.projectPath;return _path.default.relative(t,e)}function equals(e,t,r,...o){if(r){if(r(e,t,...o))return!0}const n=Object.prototype.toString.call(e);if(n!==Object.prototype.toString.call(t))return!1;if("[object Null]"===n||"[object Undefined]"===n)return!0;if("[object Object]"!==n&&"[object Array]"!==n)return Object(e).toString()===Object(t).toString();const s={};Object.keys(e).forEach((e=>s[e]=!0)),Object.keys(t).forEach((e=>s[e]=!0));const i=Object.keys(s);for(let o=0;o<i.length;o++){const n=i[o];if(!equals(e[n],t[n],r,n))return!1}return!0}function extend(e,...t){if("function"==typeof Object.assign)Object.assign(e,...t);else{const r=t.shift();for(const t in r)e[t]=r[t];t.length&&extend(e,...t)}return e}function renderString(e,t){return e.replace(/{{(.*?)}}/gm,((e,r)=>(r=r.trim(),void 0!==t[r]?t[r]:r)))}function KnownError(e){const t=new Error(e);return t.name="KnownError",t.__KNOWN=!0,t}function setCustomConfig(e,t){e=_config.default.projectPath=e||_config.default.projectPath;const r=_path.default.join(e,"quickapp.config.js");if(_fs.default.existsSync(r)){let e={};try{e=require(r)}catch(e){colorconsole.error(`Error reading project custom configuration file: ${e.message}`)}const t=Object.assign(_config.default.server,e.server);Object.assign(_config.default,e,{server:t})}t&&(_config.default.server.port=t)}exports.colorconsole=colorconsole;const illegalExtsList=[".css",".less",".scss",".styl",".sass",".log",".json",".js"].map((e=>"app"+e));function getProjectDslName(e){const t=_fs.default.readdirSync(_path.default.join(e,_config.default.sourceRoot)).filter((e=>/^app\..*/.test(e)&&!illegalExtsList.includes(e)));let r;return t&&t[0]?(r=_path.default.extname(t[0]).slice(1),colorconsole.info(`Get the app file suffix: ${r}`)):colorconsole.error("Cannot get the correct app file suffix"),"ux"===r?"xvm":r}function getDeviceInfo(e,t){const r=_http.default.request({path:"/deviceinfo",host:e.ip,port:e.port,timeout:3e3},(e=>{e.on("data",(e=>{t(null,JSON.parse(e))}))})).on("error",(e=>{t(e)})).on("timeout",(function(){r.abort()}));r.end()}function readJson(e){try{return JSON.parse(_fs.default.readFileSync(e).toString())}catch(t){throw t instanceof SyntaxError?new SyntaxError(`Failed to parse ${e}, format error`):t.message.startsWith("ENOENT:")?(t.message=`Failed to read ${e}, the file cannot be found`,t):(t.message=`Failed to read ${e} ${t.message}`,t)}}function getManifest(){try{let e=_path.default.resolve(_config.default.projectPath,"manifest.json");_fs.default.existsSync(e)||(e=_path.default.resolve(_config.default.projectPath,_config.default.sourceRoot,"manifest.json"));return readJson(e)}catch(e){throw e}}function getUxExtensionList(e=!0){const t=["ux","mix","hml"];return e?t.map((e=>`.${e}`)):t}function mergeJsonFile(e,t){if(!_fs.default.existsSync(e)||!_fs.default.existsSync(t))return;const r=_fs.default.readFileSync(e).toString(),o=_fs.default.readFileSync(t).toString();try{const e=JSON.parse(r),n=JSON.parse(o),s=Object.assign({},n,e);_fs.default.writeFileSync(t,JSON.stringify(s,null,2))}catch(e){colorconsole.error(`Parse JSON Error: ${e.message}`)}}function filterContentByTag(e,t){if(!e)return"";const r=_parse.default.parseFragment(e,{treeAdapter:_parse.default.treeAdapters.default,locationInfo:!0}).childNodes;if(!r||!r.length)return"";const o=r.filter((e=>t(e.nodeName))),n=new _index.default({childNodes:o});return n.serialize(),n.html}
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.logWarn = logWarn;
7
+ exports.mkdirsSync = mkdirsSync;
8
+ exports.getIPv4IPAddress = getIPv4IPAddress;
9
+ exports.getServerIPAndPort = getServerIPAndPort;
10
+ exports.getDefaultServerHost = getDefaultServerHost;
11
+ exports.getClientIPAddress = getClientIPAddress;
12
+ exports.stripPrefixForIPV4MappedIPV6Address = stripPrefixForIPV4MappedIPV6Address;
13
+ exports.outputQRCodeOnTerminal = outputQRCodeOnTerminal;
14
+ exports.relateCwd = relateCwd;
15
+ exports.equals = equals;
16
+ exports.extend = extend;
17
+ exports.renderString = renderString;
18
+ exports.KnownError = KnownError;
19
+ exports.setCustomConfig = setCustomConfig;
20
+ exports.getProjectDslName = getProjectDslName;
21
+ exports.getDeviceInfo = getDeviceInfo;
22
+ exports.readJson = readJson;
23
+ exports.getManifest = getManifest;
24
+ exports.getUxExtensionList = getUxExtensionList;
25
+ exports.mergeJsonFile = mergeJsonFile;
26
+ exports.filterContentByTag = filterContentByTag;
27
+ Object.defineProperty(exports, "getLaunchPage", {
28
+ enumerable: true,
29
+ get: function () {
30
+ return _util.getLaunchPage;
31
+ }
32
+ });
33
+ exports.colorconsole = exports.logger = void 0;
34
+
35
+ var _os = _interopRequireDefault(require("os"));
36
+
37
+ var _fs = _interopRequireDefault(require("fs"));
38
+
39
+ var _path = _interopRequireDefault(require("path"));
40
+
41
+ var _http = _interopRequireDefault(require("http"));
42
+
43
+ var _console = require("console");
44
+
45
+ var _chalk = _interopRequireDefault(require("chalk"));
46
+
47
+ var _qrcodeTerminal = _interopRequireDefault(require("qrcode-terminal"));
48
+
49
+ var _config = _interopRequireDefault(require("../config"));
50
+
51
+ var _parse = _interopRequireDefault(require("parse5"));
52
+
53
+ var _index = _interopRequireDefault(require("parse5/lib/serializer/index.js"));
54
+
55
+ var _util = require("./buildMode/util");
56
+
57
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
58
+
59
+ /**
60
+ * Copyright (C) 2017, hapjs.org. All rights reserved.
61
+ */
62
+ const logLevelMap = {};
63
+
64
+ function prependLevel(levelName, args) {
65
+ if (!logLevelMap[levelName]) {
66
+ const logLevel = levelName.toUpperCase();
67
+ logLevelMap[levelName] = logLevel;
68
+ }
69
+
70
+ if (typeof args[0] === 'string' && args[0].length > 1 && args[0][0] !== '[') {
71
+ args[0] = `[${logLevelMap[levelName]}] ${args[0]}`;
72
+ }
73
+ }
74
+
75
+ const logger = {
76
+ logs: [],
77
+
78
+ add(args) {
79
+ this.logs.push(args);
80
+ },
81
+
82
+ clear() {
83
+ this.logs = [];
84
+ },
85
+
86
+ get() {
87
+ return this.logs.join('\n');
88
+ }
89
+
90
+ };
91
+ /**
92
+ * 带颜色的 info, log, warn, error, trace 的打印日志输出流
93
+ */
94
+
95
+ exports.logger = logger;
96
+ let originConsole = global.console;
97
+ let console = _console.Console ? new _console.Console(process.stdout, process.stderr) : originConsole;
98
+ const colorconsole = {
99
+ attach(writable) {
100
+ if (writable && _console.Console) {
101
+ console = new _console.Console(writable, writable);
102
+ }
103
+ },
104
+
105
+ trace(...args) {
106
+ prependLevel(`trace`, args);
107
+ console.trace(...args);
108
+ },
109
+
110
+ log(...args) {
111
+ prependLevel(`log`, args);
112
+ console.log(_chalk.default.green(...args));
113
+ },
114
+
115
+ info(...args) {
116
+ prependLevel(`info`, args);
117
+ console.info(_chalk.default.green(...args));
118
+ },
119
+
120
+ warn(...args) {
121
+ prependLevel(`warn`, args);
122
+ console.warn(_chalk.default.yellow.bold(...args));
123
+ },
124
+
125
+ error(...args) {
126
+ prependLevel(`error`, args);
127
+ console.error(_chalk.default.red.bold(...args));
128
+ },
129
+
130
+ throw(...args) {
131
+ throw new Error(_chalk.default.red.bold(...args));
132
+ }
133
+
134
+ };
135
+ /**
136
+ * 打印日志
137
+ * @param loader
138
+ * @param logs
139
+ * @param suppresslog
140
+ */
141
+
142
+ exports.colorconsole = colorconsole;
143
+
144
+ function logWarn(loader, logs, suppresslog) {
145
+ if (logs && logs.length) {
146
+ logs.forEach(log => {
147
+ const logAddr = log.line && log.column ? '\t@' + log.line + ':' + log.column : '';
148
+ if (suppresslog) return;
149
+
150
+ if (log.reason.startsWith('ERROR')) {
151
+ colorconsole.error(loader.resourcePath, log.reason + logAddr);
152
+ } else {
153
+ colorconsole.warn(loader.resourcePath, log.reason + logAddr);
154
+ }
155
+ });
156
+ }
157
+ }
158
+ /**
159
+ * 创建任意深度的路径的文件夹
160
+ * @param dirname
161
+ * @returns {boolean}
162
+ */
163
+
164
+
165
+ function mkdirsSync(dirname) {
166
+ if (_fs.default.existsSync(dirname)) {
167
+ return true;
168
+ } else {
169
+ if (mkdirsSync(_path.default.dirname(dirname))) {
170
+ _fs.default.mkdirSync(dirname);
171
+
172
+ return true;
173
+ }
174
+ }
175
+ }
176
+ /**
177
+ * 获取服务器端的IP
178
+ */
179
+
180
+
181
+ function getIPv4IPAddress() {
182
+ const ifaces = _os.default.networkInterfaces();
183
+
184
+ let result;
185
+
186
+ for (const prop in ifaces) {
187
+ if (Object.prototype.hasOwnProperty.call(ifaces, prop)) {
188
+ const iface = ifaces[prop];
189
+ iface.every(eachAlias => {
190
+ if (eachAlias.family === 'IPv4' && !eachAlias.internal && eachAlias.address !== '127.0.0.1') {
191
+ result = eachAlias;
192
+ return false;
193
+ }
194
+
195
+ return true;
196
+ });
197
+
198
+ if (result !== void 0) {
199
+ break;
200
+ }
201
+ }
202
+ }
203
+
204
+ return result && result.address;
205
+ }
206
+ /**
207
+ * 取得server端的IP和port
208
+ * @param port {number}
209
+ * @returns {string}
210
+ */
211
+
212
+
213
+ function getServerIPAndPort(port) {
214
+ return (getIPv4IPAddress() || '127.0.0.1') + `${port === 80 ? '' : ':' + port}`;
215
+ }
216
+ /**
217
+ * 获取默认的服务器地址
218
+ */
219
+
220
+
221
+ function getDefaultServerHost() {
222
+ return getServerIPAndPort(_config.default.server.port);
223
+ }
224
+ /**
225
+ * 获取客户端ip
226
+ * @param req node Http IncomingRequest Object
227
+ * @returns {any|*|string}
228
+ */
229
+
230
+
231
+ function getClientIPAddress(req) {
232
+ const ip = req.headers['x-forwarded-for'] || req.connection && req.connection.remoteAddress || req.socket && req.socket.remoteAddress || req.connection && req.connection.socket && req.connection.socket.remoteAddress;
233
+ return stripPrefixForIPV4MappedIPV6Address(ip);
234
+ }
235
+ /**
236
+ * 检测可能是IpV4-mapped IpV6 格式的ip
237
+ * - https://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses
238
+ *
239
+ * @param ip IpV4-mapped IpV6 string
240
+ * @returns {*}
241
+ */
242
+
243
+
244
+ function stripPrefixForIPV4MappedIPV6Address(ip) {
245
+ if (/^::1$/.test(ip)) {
246
+ ip = '127.0.0.1';
247
+ }
248
+
249
+ if (/^::.{0,4}:(\d{1,3}\.){3}\d{1,3}/.test(ip)) {
250
+ ip = ip.replace(/^.*:/, '');
251
+ }
252
+
253
+ return ip;
254
+ }
255
+ /**
256
+ * 命令行输出二维码
257
+ * @param text
258
+ */
259
+
260
+
261
+ function outputQRCodeOnTerminal(text) {
262
+ console.info(`\nGenerate QR code for HTTP server: ${text}`);
263
+
264
+ _qrcodeTerminal.default.generate(text, {
265
+ small: true
266
+ });
267
+ }
268
+ /**
269
+ * 相对工作目录的路径
270
+ *
271
+ * @param {String} filepath - 输入路径
272
+ * @returns {String} - 输出相对路径
273
+ */
274
+
275
+
276
+ function relateCwd(filepath) {
277
+ const CWD = _config.default.projectPath;
278
+ return _path.default.relative(CWD, filepath);
279
+ }
280
+ /**
281
+ * 比较两个对象是否相同
282
+ * @param o1
283
+ * @param o2
284
+ * @param fn {Function} 对比函数
285
+ */
286
+
287
+
288
+ function equals(o1, o2, fn, ...args) {
289
+ if (fn) {
290
+ const fnRet = fn(o1, o2, ...args);
291
+
292
+ if (fnRet) {
293
+ return true;
294
+ }
295
+ }
296
+
297
+ const toStr1 = Object.prototype.toString.call(o1);
298
+ const toStr2 = Object.prototype.toString.call(o2);
299
+
300
+ if (toStr1 !== toStr2) {
301
+ return false;
302
+ }
303
+
304
+ if (toStr1 === '[object Null]' || toStr1 === '[object Undefined]') {
305
+ return true;
306
+ }
307
+
308
+ if (toStr1 !== '[object Object]' && toStr1 !== '[object Array]') {
309
+ return Object(o1).toString() === Object(o2).toString();
310
+ }
311
+
312
+ const keyMap = {};
313
+ Object.keys(o1).forEach(k => keyMap[k] = true);
314
+ Object.keys(o2).forEach(k => keyMap[k] = true);
315
+ const keyList = Object.keys(keyMap);
316
+
317
+ for (let i = 0; i < keyList.length; i++) {
318
+ const keyName = keyList[i];
319
+ const isEqual = equals(o1[keyName], o2[keyName], fn, keyName);
320
+
321
+ if (!isEqual) {
322
+ return false;
323
+ }
324
+ }
325
+
326
+ return true;
327
+ }
328
+ /**
329
+ * 扩展对象属性
330
+ * @param dest
331
+ * @param src
332
+ */
333
+
334
+
335
+ function extend(target, ...src) {
336
+ if (typeof Object.assign === 'function') {
337
+ Object.assign(target, ...src);
338
+ } else {
339
+ const first = src.shift(); // 覆盖旧值
340
+
341
+ for (const key in first) {
342
+ target[key] = first[key];
343
+ }
344
+
345
+ if (src.length) {
346
+ extend(target, ...src);
347
+ }
348
+ }
349
+
350
+ return target;
351
+ }
352
+ /**
353
+ * 简单的模板字符串渲染函数
354
+ *
355
+ * @param {String} tpl - 模板字符串
356
+ * @param {Object} data - 渲染数据
357
+ * @returns {String}
358
+ */
359
+
360
+
361
+ function renderString(tpl, data) {
362
+ return tpl.replace(/{{(.*?)}}/gm, (_, key) => {
363
+ key = key.trim();
364
+ return data[key] !== undefined ? data[key] : key;
365
+ });
366
+ }
367
+
368
+ function KnownError(message) {
369
+ const err = new Error(message);
370
+ err.name = 'KnownError';
371
+ err.__KNOWN = true;
372
+ return err;
373
+ }
374
+ /**
375
+ * 获取并设置自定义配置项
376
+ * @param {String} projectPath - 项目路径
377
+ * @param {String} port - server端口
378
+ */
379
+
380
+
381
+ function setCustomConfig(projectPath, port) {
382
+ projectPath = _config.default.projectPath = projectPath || _config.default.projectPath;
383
+ const defaultConfig = 'quickapp.config.js';
384
+
385
+ const defaultConfigPath = _path.default.join(projectPath, defaultConfig);
386
+
387
+ if (_fs.default.existsSync(defaultConfigPath)) {
388
+ let customConf = {};
389
+
390
+ try {
391
+ customConf = require(defaultConfigPath);
392
+ } catch (err) {
393
+ colorconsole.error(`Error reading project custom configuration file: ${err.message}`);
394
+ } // 保证 customConf server 字段无内容也可保证默认值
395
+
396
+
397
+ const server = Object.assign(_config.default.server, customConf.server);
398
+ Object.assign(_config.default, customConf, {
399
+ server
400
+ });
401
+ }
402
+
403
+ port && (_config.default.server.port = port);
404
+ }
405
+
406
+ const illegalExtsList = ['.css', '.less', '.scss', '.styl', '.sass', '.log', '.json', '.js'].map(e => 'app' + e);
407
+ /**
408
+ * 获取当前项目所使用的DSL
409
+ * @param projectPath
410
+ */
411
+
412
+ function getProjectDslName(projectPath) {
413
+ // 根据项目中src/app的后缀名判断
414
+ const srcFiles = _fs.default.readdirSync(_path.default.join(projectPath, _config.default.sourceRoot));
415
+
416
+ const appFileNames = srcFiles.filter(f => /^app\..*/.test(f) && !illegalExtsList.includes(f));
417
+ let appFileExt;
418
+
419
+ if (appFileNames && appFileNames[0]) {
420
+ appFileExt = _path.default.extname(appFileNames[0]).slice(1);
421
+ colorconsole.info(`Get the app file suffix: ${appFileExt}`);
422
+ } else {
423
+ colorconsole.error(`Cannot get the correct app file suffix`);
424
+ }
425
+
426
+ return appFileExt === 'ux' ? 'xvm' : appFileExt;
427
+ }
428
+ /**
429
+ * 获取手机设备信息(1020新增接口)
430
+ * @param client {{ ip, port }}
431
+ * @param callback
432
+ */
433
+
434
+
435
+ function getDeviceInfo(client, callback) {
436
+ const req = _http.default.request({
437
+ path: '/deviceinfo',
438
+ host: client.ip,
439
+ port: client.port,
440
+ timeout: 3000
441
+ }, res => {
442
+ res.on('data', data => {
443
+ callback(null, JSON.parse(data));
444
+ });
445
+ }).on('error', err => {
446
+ callback(err);
447
+ }).on('timeout', function () {
448
+ // abort方法会触发error事件
449
+ req.abort();
450
+ });
451
+
452
+ req.end();
453
+ }
454
+ /**
455
+ * 读取一份 json 内容
456
+ *
457
+ * @param {String} jsonpath - json 路径
458
+ * @returns {Object} json
459
+ */
460
+
461
+
462
+ function readJson(jsonpath) {
463
+ try {
464
+ return JSON.parse(_fs.default.readFileSync(jsonpath).toString());
465
+ } catch (err) {
466
+ if (err instanceof SyntaxError) {
467
+ throw new SyntaxError(`Failed to parse ${jsonpath}, format error`);
468
+ } else if (err.message.startsWith('ENOENT:')) {
469
+ err.message = `Failed to read ${jsonpath}, the file cannot be found`;
470
+ throw err;
471
+ } else {
472
+ err.message = `Failed to read ${jsonpath} ${err.message}`;
473
+ throw err;
474
+ }
475
+ }
476
+ }
477
+ /**
478
+ * 获取 manifest.json 内容
479
+ *
480
+ * @returns {Object} json
481
+ */
482
+
483
+
484
+ function getManifest() {
485
+ try {
486
+ // 需要特殊处理打包mina-h5时,manifest.json文件在根目录下
487
+ let manifestFile = _path.default.resolve(_config.default.projectPath, 'manifest.json');
488
+
489
+ if (!_fs.default.existsSync(manifestFile)) {
490
+ manifestFile = _path.default.resolve(_config.default.projectPath, _config.default.sourceRoot, 'manifest.json');
491
+ }
492
+
493
+ const manifest = readJson(manifestFile);
494
+ return manifest;
495
+ } catch (err) {
496
+ throw err;
497
+ }
498
+ }
499
+ /**
500
+ * 获取识别为.ux的文件后缀列表
501
+ * @param {*} withDot 扩展名是否包含.
502
+ * @returns string[]
503
+ */
504
+
505
+
506
+ function getUxExtensionList(withDot = true) {
507
+ const result = ['ux', 'mix', 'hml'];
508
+
509
+ if (withDot) {
510
+ return result.map(item => `.${item}`);
511
+ }
512
+
513
+ return result;
514
+ }
515
+ /**
516
+ * 合并json文件的内容,把fromPath的内容合并到toPath
517
+ * @param {*} fromPath
518
+ * @param {*} toPath
519
+ */
520
+
521
+
522
+ function mergeJsonFile(fromPath, toPath) {
523
+ if (!_fs.default.existsSync(fromPath) || !_fs.default.existsSync(toPath)) {
524
+ return;
525
+ } // 读取两个文件的数据-->转换成json-->frompath的json属性覆盖topath的同名属性
526
+
527
+
528
+ const fromStr = _fs.default.readFileSync(fromPath).toString();
529
+
530
+ const toStr = _fs.default.readFileSync(toPath).toString();
531
+
532
+ try {
533
+ const fromObj = JSON.parse(fromStr);
534
+ const toObj = JSON.parse(toStr);
535
+ const result = Object.assign({}, toObj, fromObj);
536
+
537
+ _fs.default.writeFileSync(toPath, JSON.stringify(result, null, 2));
538
+ } catch (error) {
539
+ colorconsole.error(`Parse JSON Error: ${error.message}`);
540
+ }
541
+ }
542
+ /**
543
+ * 通过tag过滤内容
544
+ * @param {string} source 源文本
545
+ * @param {(tagName)=>boolean} includeFun 过滤方法,返回true表示保留
546
+ *
547
+ * @return string
548
+ */
549
+
550
+
551
+ function filterContentByTag(source, includeFun) {
552
+ if (!source) {
553
+ return '';
554
+ }
555
+
556
+ const nodes = _parse.default.parseFragment(source, {
557
+ treeAdapter: _parse.default.treeAdapters.default,
558
+ locationInfo: true
559
+ }).childNodes;
560
+
561
+ if (!nodes || !nodes.length) {
562
+ return '';
563
+ } // 过滤childrenNodes
564
+
565
+
566
+ const effectNodes = nodes.filter(item => includeFun(item.nodeName)); // 生成html
567
+
568
+ const serializer = new _index.default({
569
+ childNodes: effectNodes
570
+ });
571
+ serializer.serialize();
572
+ return serializer.html;
573
+ }
2
574
  //# sourceMappingURL=index.js.map