aiot-toolkit 1.0.18-aspect-beta.22 → 1.0.18-aspect-beta.23

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.
@@ -1,2 +1,524 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatDate=formatDate,exports.summaryErrors=summaryErrors,exports.summaryWarnings=summaryWarnings,exports.getQuickappDebuggerUrl=getQuickappDebuggerUrl,exports.getQuickappPreviewUrl=getQuickappPreviewUrl,exports.downloadFile=downloadFile,exports.sendReq=sendReq,exports.getClients=getClients,exports.checkQuickappDir=checkQuickappDir,exports.getCardContent=getCardContent,exports.cleanOrCreateDir=cleanOrCreateDir,exports.getAspectEntries=getAspectEntries,exports.copyFiles=copyFiles,exports.getProductionTypes=getProductionTypes,exports.isMirtosDevice=isMirtosDevice,exports.deleteCompressedFiles=deleteCompressedFiles,exports.getAndCopyDeviceAspectResource=getAndCopyDeviceAspectResource;var _fsExtra=_interopRequireDefault(require("fs-extra")),_path=_interopRequireDefault(require("path")),_request=_interopRequireDefault(require("request")),_http=_interopRequireDefault(require("http")),_recordClient=require("@aiot-toolkit/shared-utils/lib/record-client"),_config=require("@aiot-toolkit/shared-utils/config"),_sharedUtils=require("@aiot-toolkit/shared-utils");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,o)}return r}function _objectSpread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(r),!0).forEach((function(t){_defineProperty(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ownKeys(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function _defineProperty(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const fsExtra=require("fs-extra");function formatDate(e,t){let r,o,s,n,i,a,c=e;return(e.indexOf("yyyy")>=0||e.indexOf("YYYYY")>=0)&&(r=t.getFullYear(),c=c.replace(/[yY]{4}/g,r)),e.indexOf("MM")>=0&&(o=t.getMonth()+1,c=c.replace(/MM/g,String(o).length<2?"0"+o:o)),e.indexOf("dd")>=0&&(s=t.getDate(),c=c.replace(/dd/g,String(s).length<2?"0"+s:s)),(e.indexOf("hh")>=0||e.indexOf("HH")>=0)&&(n=t.getHours(),c=c.replace(/[hH]{2}/g,String(n).length<2?"0"+n:n)),e.indexOf("mm")>=0&&(i=t.getMinutes(),c=c.replace(/mm/g,String(i).length<2?"0"+i:i)),(e.indexOf("ss")>=0||e.indexOf("SS")>=0)&&(a=t.getSeconds(),c=c.replace(/[sS]{2}/g,String(a).length<2?"0"+a:a)),c}function summaryErrors(e){const t=[];return e.compilation.errors.forEach((e=>{const r=e.message,o=/Can't resolve '(sass-loader|less-loader|stylus-loader)'/.exec(r);if("ModuleNotFoundError"===e.name&&o){let t=o[1];"less-loader"===t?t=`less ${t}`:"sass-loader"===t?t=`node-sass ${t}`:"stylus-loader"===t&&(t=`stylus ${t}`),e.message=` Missing dependency: ${t}, Please execute npm install -D ${t} to install the corresponding dependencies `}const s=e.module?e.module.resource:"";t.push(`${s}\r\n${e.message}`)})),t.join("\n\n")}function summaryWarnings(e){return e.compilation.warnings.map((e=>e.message)).join("\n\n")}const quickapp_url="https://statres.quickapp.cn/quickapp/quickapptool/release/platform/";function getQuickappDebuggerUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_debugger_${t}.apk`}function getQuickappPreviewUrl(e){let t=e||"v1080";return _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${t}`),`${quickapp_url}quickapp_platform_preview_release_${t}.apk`}function downloadFile(e,t){return _sharedUtils.colorconsole.log(`Start downloading file:${t}, address:${e}`),new Promise((function(r,o){(0,_request.default)(e,(function(s,n,i){if(s||200!==n.statusCode)o(s||new Error(`Download failed, status code:${n.statusCode}`));else{const s=_path.default.join(__dirname,"./apk");_fsExtra.default.ensureDirSync(s);let n=_fsExtra.default.createWriteStream(_path.default.join(s,t));(0,_request.default)(e).pipe(n).on("close",(e=>{e?o(e):r(`Download file ${t} successfully`)}))}}))}))}async function sendReq(e,t,r){return new Promise((o=>{const s=`http://${e.ip}:${e.port}${t}`;let n={host:e.ip,port:e.port,path:t,timeout:3e3};r&&(n=Object.assign({},n,{headers:r}));const i=_http.default.request(n,(e=>{e.on("data",(e=>{_sharedUtils.colorconsole.log(`### App Server ### Request ${s} succeeded`),o(e.toString())}))})).on("error",(e=>{_sharedUtils.colorconsole.error(`### App Server ### Request ${s} error message: ${e.message}`)})).on("timeout",(function(){_sharedUtils.colorconsole.log(`### App Server ### Request ${s} timed out, please try again`),i.abort()}));i.end()}))}async function getClients(){return new Promise((e=>{if(_fsExtra.default.existsSync(_config.clientRecordPath)){const t=(0,_recordClient.getRecords)(_config.clientRecordPath),r=(0,_recordClient.getProjectClients)(t);r.length>0&&e(r)}e(null)}))}function checkQuickappDir(e,t="src"){const r=_path.default.join(e,t,"manifest.json");_fsExtra.default.existsSync(r)||(_sharedUtils.colorconsole.error("Please execute this command under the Quickapp project"),process.exit())}function getCardContent(e){const t=_path.default.join(e,"src","manifest.json"),r=(0,_sharedUtils.readJson)(t).router.widgets||null;return r||_sharedUtils.colorconsole.error("No card configuration in manifest.json"),r}function cleanOrCreateDir(e){try{_fsExtra.default.accessSync(e,_fsExtra.default.constants.F_OK),fsExtra.emptyDirSync(e)}catch(t){_fsExtra.default.mkdirSync(e,{recursive:!0})}}function getAspectEntries(e,t){let r=[],o={},s={},n=_fsExtra.default.readdirSync(e,{encoding:"utf8"});const i=_path.default.join(e,"app","manifest.json"),a=t.router.aspects||null,c=Object.keys(a);return t.router||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router is not exsist, please check`),a||_sharedUtils.colorconsole.error(`Configuration file ${i} error: router.aspect is not exist, please check`),c.forEach((e=>{const t=a[e];let c=[];t.forEach((t=>{n.includes(t.path)&&!r.includes(t.path)?r.push(t.path):_sharedUtils.colorconsole.throw(`Configuration file ${i} error: ${t.path} is not exist in root directory`);let a=t.devices?t.devices:["phone"];for(let r=0;r<a.length;r++){let n=[a[r],t.rule?t.rule:""].join(" ");c.includes(n)?_sharedUtils.colorconsole.throw(`Configuration file ${i} error, devices or devices rule: ${n} is repeat in router ${e}`):c.push(n),s[n]=_objectSpread(_objectSpread({},s[n]),{},{[e]:t}),Object.keys(o).includes(n)?o[n].push(t.path):o[n]=[t.path]}}))})),{entries:r,deviceAspects:o,routerObj:s}}function copyFiles(e,t){_fsExtra.default.existsSync(e)||_sharedUtils.colorconsole.throw(`Resource copy error, the path ${e} not exist.`),_fsExtra.default.existsSync(t)||_fsExtra.default.mkdirSync(t,{recursive:!0});_fsExtra.default.readdirSync(e).forEach((r=>{const o=_path.default.join(e,r),s=_path.default.join(t,r);_fsExtra.default.statSync(o).isDirectory()?copyFiles(o,s):_fsExtra.default.copyFileSync(o,s)}))}const mirtosDeviceConfig=["watch"],androidDeviceConfig=[""];function getProductionTypes(e){const t={enableMirtos:!1,enableAndroid:!1};return 0===e.length?t.enableAndroid=!0:e.map((e=>{mirtosDeviceConfig.indexOf(e)>-1?t.enableMirtos=!0:t.enableAndroid=!0})),t}function isMirtosDevice(e){return mirtosDeviceConfig.some((t=>e.includes(t)))}function deleteCompressedFiles(e){const t=[".base",".aspc"];_fsExtra.default.readdirSync(e).forEach((r=>{const o=_path.default.join(e,r);_fsExtra.default.statSync(o).isFile()&&t.includes(_path.default.extname(o).toLowerCase())&&_fsExtra.default.unlinkSync(o)}))}function getAndCopyDeviceAspectResource(e,t,r,o){const s=_path.default.dirname(t);return e.map((e=>{let n=o?`${e}.lite`:e;return copyFiles(_path.default.join(t,n),_path.default.join(s,r,e)),{name:e,targetFile:"app"===e?n+".base":n+".aspc",otherName:"app"===e?e+".base":e+".aspc"}}))}
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.formatDate = formatDate;
7
+ exports.summaryErrors = summaryErrors;
8
+ exports.summaryWarnings = summaryWarnings;
9
+ exports.getQuickappDebuggerUrl = getQuickappDebuggerUrl;
10
+ exports.getQuickappPreviewUrl = getQuickappPreviewUrl;
11
+ exports.downloadFile = downloadFile;
12
+ exports.sendReq = sendReq;
13
+ exports.getClients = getClients;
14
+ exports.checkQuickappDir = checkQuickappDir;
15
+ exports.getCardContent = getCardContent;
16
+ exports.cleanOrCreateDir = cleanOrCreateDir;
17
+ exports.getAspectEntries = getAspectEntries;
18
+ exports.copyFiles = copyFiles;
19
+ exports.getProductionTypes = getProductionTypes;
20
+ exports.isMirtosDevice = isMirtosDevice;
21
+ exports.deleteCompressedFiles = deleteCompressedFiles;
22
+ exports.getAndCopyDeviceAspectResource = getAndCopyDeviceAspectResource;
23
+
24
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
25
+
26
+ var _path = _interopRequireDefault(require("path"));
27
+
28
+ var _request = _interopRequireDefault(require("request"));
29
+
30
+ var _http = _interopRequireDefault(require("http"));
31
+
32
+ var _recordClient = require("@aiot-toolkit/shared-utils/lib/record-client");
33
+
34
+ var _config = require("@aiot-toolkit/shared-utils/config");
35
+
36
+ var _sharedUtils = require("@aiot-toolkit/shared-utils");
37
+
38
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39
+
40
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
41
+
42
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
43
+
44
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
45
+
46
+ const fsExtra = require('fs-extra');
47
+ /**
48
+ * 接受用户指定的输出时间戳格式,输出时间时间戳
49
+ * usage sample:
50
+ * formatDate('yyyy年MM月dd日', new Date() );
51
+ * formatDate('yyyy-MM-dd hh:mm:ss', new Date() );
52
+ * formatDate('这是自定义的yyyy年, 自定义的MM月', new Date())
53
+ *
54
+ * @param {[type]} format 用户指定的时间戳格式, 见上面示例;
55
+ * @param {[type]} date Date实例
56
+ */
57
+
58
+
59
+ function formatDate(format, date) {
60
+ let result = format;
61
+ let year, month, day;
62
+ let hour, min, sec;
63
+
64
+ if (format.indexOf('yyyy') >= 0 || format.indexOf('YYYYY') >= 0) {
65
+ year = date.getFullYear();
66
+ result = result.replace(/[yY]{4}/g, year);
67
+ }
68
+
69
+ if (format.indexOf('MM') >= 0) {
70
+ month = date.getMonth() + 1;
71
+ result = result.replace(/MM/g, String(month).length < 2 ? '0' + month : month);
72
+ }
73
+
74
+ if (format.indexOf('dd') >= 0) {
75
+ day = date.getDate();
76
+ result = result.replace(/dd/g, String(day).length < 2 ? '0' + day : day);
77
+ }
78
+
79
+ if (format.indexOf('hh') >= 0 || format.indexOf('HH') >= 0) {
80
+ hour = date.getHours();
81
+ result = result.replace(/[hH]{2}/g, String(hour).length < 2 ? '0' + hour : hour);
82
+ }
83
+
84
+ if (format.indexOf('mm') >= 0) {
85
+ min = date.getMinutes();
86
+ result = result.replace(/mm/g, String(min).length < 2 ? '0' + min : min);
87
+ }
88
+
89
+ if (format.indexOf('ss') >= 0 || format.indexOf('SS') >= 0) {
90
+ sec = date.getSeconds();
91
+ result = result.replace(/[sS]{2}/g, String(sec).length < 2 ? '0' + sec : sec);
92
+ }
93
+
94
+ return result;
95
+ }
96
+ /**
97
+ * 整理错误
98
+ *
99
+ * @param {Object} stats
100
+ * @returns {String}
101
+ */
102
+
103
+
104
+ function summaryErrors(stats) {
105
+ const errors = [];
106
+ stats.compilation.errors.forEach(error => {
107
+ const message = error.message; // 如果错误信息显示缺少某些loader,则提示安装
108
+
109
+ const reg = /Can't resolve '(sass-loader|less-loader|stylus-loader)'/;
110
+ const result = reg.exec(message);
111
+
112
+ if (error.name === 'ModuleNotFoundError' && result) {
113
+ let moduleName = result[1];
114
+
115
+ if (moduleName === 'less-loader') {
116
+ moduleName = `less ${moduleName}`;
117
+ } else if (moduleName === 'sass-loader') {
118
+ moduleName = `node-sass ${moduleName}`;
119
+ } else if (moduleName === 'stylus-loader') {
120
+ moduleName = `stylus ${moduleName}`;
121
+ }
122
+
123
+ error.message = ` Missing dependency: ${moduleName}, Please execute npm install -D ${moduleName} to install the corresponding dependencies `;
124
+ }
125
+
126
+ const resourceName = error.module ? error.module.resource : '';
127
+ errors.push(`${resourceName}\r\n${error.message}`);
128
+ }); // 使用 stats.toString,webpack会在前面加上 ERROR 标志,与 colorconsole.error 重复
129
+
130
+ return errors.join('\n\n');
131
+ }
132
+ /**
133
+ * 提取警告信息
134
+ * @param {*} stats
135
+ * @returns
136
+ */
137
+
138
+
139
+ function summaryWarnings(stats) {
140
+ return stats.compilation.warnings.map(warn => warn.message).join('\n\n');
141
+ }
142
+
143
+ const quickapp_url = 'https://statres.quickapp.cn/quickapp/quickapptool/release/platform/';
144
+ /**
145
+ * 快应用调试器地址
146
+ * @param version 版本号
147
+ */
148
+
149
+ function getQuickappDebuggerUrl(version) {
150
+ let newVersion = version || 'v1080';
151
+
152
+ _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${newVersion}`);
153
+
154
+ return `${quickapp_url}quickapp_debugger_${newVersion}.apk`;
155
+ }
156
+ /**
157
+ * 快应用预览版地址
158
+ * @param version 版本号
159
+ */
160
+
161
+
162
+ function getQuickappPreviewUrl(version) {
163
+ let newVersion = version || 'v1080';
164
+
165
+ _sharedUtils.colorconsole.log(`The version of the Quickapp debugger that started to download is: ${newVersion}`);
166
+
167
+ return `${quickapp_url}quickapp_platform_preview_release_${newVersion}.apk`;
168
+ }
169
+ /**
170
+ * 下载文件
171
+ * @param url 网络文件地址
172
+ * @param fileName 文件名
173
+ */
174
+
175
+
176
+ function downloadFile(url, fileName) {
177
+ _sharedUtils.colorconsole.log(`Start downloading file:${fileName}, address:${url}`);
178
+
179
+ return new Promise(function (resolve, reject) {
180
+ (0, _request.default)(url, function (error, response, body) {
181
+ if (!error && response.statusCode === 200) {
182
+ const targetDir = _path.default.join(__dirname, './apk');
183
+
184
+ _fsExtra.default.ensureDirSync(targetDir);
185
+
186
+ let stream = _fsExtra.default.createWriteStream(_path.default.join(targetDir, fileName));
187
+
188
+ (0, _request.default)(url).pipe(stream).on('close', err => {
189
+ if (err) {
190
+ reject(err);
191
+ } else {
192
+ resolve(`Download file ${fileName} successfully`);
193
+ }
194
+ });
195
+ } else {
196
+ if (error) {
197
+ reject(error);
198
+ } else {
199
+ reject(new Error(`Download failed, status code:${response.statusCode}`));
200
+ }
201
+ }
202
+ });
203
+ });
204
+ }
205
+ /**
206
+ * 向手机设备发送请求
207
+ * @param client {{ ip, port }}
208
+ */
209
+
210
+
211
+ async function sendReq(client, api, params) {
212
+ return new Promise(resolve => {
213
+ const requrl = `http://${client.ip}:${client.port}${api}`; // 发送请求
214
+
215
+ let options = {
216
+ host: client.ip,
217
+ port: client.port,
218
+ path: api,
219
+ timeout: 3000
220
+ };
221
+
222
+ if (params) {
223
+ options = Object.assign({}, options, {
224
+ headers: params
225
+ });
226
+ }
227
+
228
+ const req = _http.default.request(options, res => {
229
+ res.on('data', data => {
230
+ _sharedUtils.colorconsole.log(`### App Server ### Request ${requrl} succeeded`);
231
+
232
+ resolve(data.toString());
233
+ });
234
+ }).on('error', err => {
235
+ _sharedUtils.colorconsole.error(`### App Server ### Request ${requrl} error message: ${err.message}`);
236
+ }).on('timeout', function () {
237
+ _sharedUtils.colorconsole.log(`### App Server ### Request ${requrl} timed out, please try again`);
238
+
239
+ req.abort();
240
+ });
241
+
242
+ req.end();
243
+ });
244
+ }
245
+ /**
246
+ * 获取已连接的设备信息
247
+ */
248
+
249
+
250
+ async function getClients() {
251
+ return new Promise(resolve => {
252
+ if (_fsExtra.default.existsSync(_config.clientRecordPath)) {
253
+ const recordData = (0, _recordClient.getRecords)(_config.clientRecordPath);
254
+ const clients = (0, _recordClient.getProjectClients)(recordData);
255
+
256
+ if (clients.length > 0) {
257
+ resolve(clients);
258
+ }
259
+ }
260
+
261
+ resolve(null);
262
+ });
263
+ }
264
+ /**
265
+ * 判断是否在快应用的目录下
266
+ * @param {String} curDir - 当前命令的执行目录
267
+ */
268
+
269
+
270
+ function checkQuickappDir(curDir, srcDir = 'src') {
271
+ const curpkgPath = _path.default.join(curDir, srcDir, 'manifest.json');
272
+
273
+ if (!_fsExtra.default.existsSync(curpkgPath)) {
274
+ _sharedUtils.colorconsole.error(`Please execute this command under the Quickapp project`);
275
+
276
+ process.exit();
277
+ }
278
+ }
279
+ /**
280
+ * 获取卡片内容
281
+ * @param {String} curDir - 当前命令的执行目录
282
+ */
283
+
284
+
285
+ function getCardContent(curDir) {
286
+ const curpkgPath = _path.default.join(curDir, 'src', 'manifest.json');
287
+
288
+ const widgetsContent = (0, _sharedUtils.readJson)(curpkgPath).router.widgets || null;
289
+
290
+ if (!widgetsContent) {
291
+ _sharedUtils.colorconsole.error(`No card configuration in manifest.json`);
292
+ }
293
+
294
+ return widgetsContent;
295
+ }
296
+ /**
297
+ * 清空或创建目标文件夹
298
+ * @param {*} dest
299
+ */
300
+
301
+
302
+ function cleanOrCreateDir(dest) {
303
+ try {
304
+ _fsExtra.default.accessSync(dest, _fsExtra.default.constants.F_OK);
305
+
306
+ fsExtra.emptyDirSync(dest);
307
+ } catch (err) {
308
+ _fsExtra.default.mkdirSync(dest, {
309
+ recursive: true
310
+ });
311
+ }
312
+ }
313
+ /**
314
+ * 获取项目入口
315
+ * @param {string} cwd 项目根目录
316
+ * @param {string} appManifest manifest对象
317
+ * @returns 返回所有项目入口
318
+ */
319
+
320
+
321
+ function getAspectEntries(cwd, appManifest) {
322
+ let entries = [];
323
+ let deviceAspects = {};
324
+ let routerObj = {};
325
+
326
+ let dirs = _fsExtra.default.readdirSync(cwd, {
327
+ encoding: 'utf8'
328
+ });
329
+
330
+ const manifestPath = _path.default.join(cwd, 'app', 'manifest.json');
331
+
332
+ const aspects = appManifest.router.aspects || null;
333
+ const keys = Object.keys(aspects);
334
+
335
+ if (!appManifest.router) {
336
+ _sharedUtils.colorconsole.error(`Configuration file ${manifestPath} error: router is not exsist, please check`);
337
+ }
338
+
339
+ if (!aspects) {
340
+ _sharedUtils.colorconsole.error(`Configuration file ${manifestPath} error: router.aspect is not exist, please check`);
341
+ }
342
+
343
+ keys.forEach(item => {
344
+ const values = aspects[item];
345
+ let devices = [];
346
+ values.forEach(entry => {
347
+ if (dirs.includes(entry.path) && !entries.includes(entry.path)) {
348
+ entries.push(entry.path);
349
+ } else {
350
+ _sharedUtils.colorconsole.throw(`Configuration file ${manifestPath} error: ${entry.path} is not exist in root directory`);
351
+ }
352
+
353
+ let entryDevice = entry.devices ? entry.devices : ['phone'];
354
+
355
+ for (let i = 0; i < entryDevice.length; i++) {
356
+ let str = [entryDevice[i], entry.rule ? entry.rule : ''].join(' '); // 同一router下的device和rule的组合不能重复,重复则报错
357
+
358
+ if (devices.includes(str)) {
359
+ _sharedUtils.colorconsole.throw(`Configuration file ${manifestPath} error, devices or devices rule: ${str} is repeat in router ${item}`);
360
+ } else {
361
+ devices.push(str);
362
+ } // 根据设备保存对应的manifest路由
363
+
364
+
365
+ routerObj[str] = _objectSpread(_objectSpread({}, routerObj[str]), {}, {
366
+ [item]: entry
367
+ });
368
+
369
+ if (!Object.keys(deviceAspects).includes(str)) {
370
+ // 根据设备-rule规则找到路径
371
+ deviceAspects[str] = [entry.path];
372
+ } else {
373
+ deviceAspects[str].push(entry.path);
374
+ }
375
+ }
376
+ });
377
+ });
378
+ return {
379
+ entries,
380
+ deviceAspects,
381
+ routerObj
382
+ };
383
+ }
384
+ /**
385
+ * 将源文件夹拷贝到目标文件夹
386
+ * @param {String} source - 源文件夹
387
+ * @param {String} target - 目标文件夹
388
+ */
389
+
390
+
391
+ function copyFiles(source, target) {
392
+ if (!_fsExtra.default.existsSync(source)) {
393
+ _sharedUtils.colorconsole.throw(`Resource copy error, the path ${source} not exist.`);
394
+ } // 如果目标路径不存在,则创建目标路径
395
+
396
+
397
+ if (!_fsExtra.default.existsSync(target)) {
398
+ _fsExtra.default.mkdirSync(target, {
399
+ recursive: true
400
+ });
401
+ } // 获取源路径下的所有文件和文件夹的名称列表
402
+
403
+
404
+ const files = _fsExtra.default.readdirSync(source); // 遍历每个文件和文件夹
405
+
406
+
407
+ files.forEach(file => {
408
+ const sourcePath = _path.default.join(source, file);
409
+
410
+ const targetPath = _path.default.join(target, file); // 如果是文件夹,则递归复制子目录和文件
411
+
412
+
413
+ if (_fsExtra.default.statSync(sourcePath).isDirectory()) {
414
+ copyFiles(sourcePath, targetPath);
415
+ } else {
416
+ // 如果是文件,则直接复制
417
+ _fsExtra.default.copyFileSync(sourcePath, targetPath);
418
+ }
419
+ });
420
+ }
421
+
422
+ const mirtosDeviceConfig = ['watch']; // TODO:生成产物有多种时,需要配置不同产物对应的设备类型
423
+
424
+ const androidDeviceConfig = [''];
425
+ /**
426
+ * 根据设备类型配置打包产物类型
427
+ * @param {*} deviceTypeList
428
+ * @returns
429
+ */
430
+
431
+ function getProductionTypes(deviceTypeList) {
432
+ const productionTypes = {
433
+ // 是否生成vela产物
434
+ enableMirtos: false,
435
+ // 是否生成android产物
436
+ enableAndroid: false
437
+ };
438
+
439
+ if (deviceTypeList.length === 0) {
440
+ productionTypes.enableAndroid = true;
441
+ } else {
442
+ deviceTypeList.map(device => {
443
+ if (mirtosDeviceConfig.indexOf(device) > -1) {
444
+ productionTypes.enableMirtos = true;
445
+ } else {
446
+ productionTypes.enableAndroid = true;
447
+ }
448
+ });
449
+ }
450
+
451
+ return productionTypes;
452
+ }
453
+ /**
454
+ * 判断设备的产物类型是否为vela
455
+ * @param {*} deviceName 设备名,由device rule组成
456
+ * @returns
457
+ */
458
+
459
+
460
+ function isMirtosDevice(deviceName) {
461
+ return mirtosDeviceConfig.some(device => deviceName.includes(device));
462
+ }
463
+ /**
464
+ * 删除指定文件夹下的指定扩展名的文件
465
+ * @param {*} sourcePath 指定文件夹路径
466
+ */
467
+
468
+
469
+ function deleteCompressedFiles(sourcePath, isOutputRpk = false, distPath = '') {
470
+ const extensions = ['.base', '.aspc'];
471
+
472
+ const files = _fsExtra.default.readdirSync(sourcePath);
473
+
474
+ files.forEach(file => {
475
+ const {
476
+ name,
477
+ ext
478
+ } = _path.default.parse(file);
479
+
480
+ const filePath = _path.default.join(sourcePath, file);
481
+
482
+ const fileStat = _fsExtra.default.statSync(filePath);
483
+
484
+ if (fileStat.isFile() && extensions.includes(ext.toLowerCase())) {
485
+ if (isOutputRpk) {
486
+ const targetFilePath = _path.default.join(distPath, `${name}.rpk`);
487
+
488
+ _fsExtra.default.renameSync(filePath, targetFilePath);
489
+ } else {
490
+ _fsExtra.default.unlinkSync(filePath);
491
+ }
492
+ }
493
+ });
494
+ }
495
+ /**
496
+ * 获取设备包中的aspect列表(包含后缀),将对应的aspect产物复制到build目录下的设备包目录中
497
+ * @param {*} deviceAspects
498
+ * @param {*} resourcePath
499
+ * @param {*} devicePackageName
500
+ * @param {*} velaProduction
501
+ * @returns
502
+ */
503
+
504
+
505
+ function getAndCopyDeviceAspectResource(deviceAspects, resourcePath, devicePackageName, velaProduction) {
506
+ const destDirPath = _path.default.dirname(resourcePath);
507
+
508
+ const deviceAspectsArr = deviceAspects.map(aspectItem => {
509
+ let tempItem = velaProduction ? `${aspectItem}.lite` : aspectItem;
510
+
511
+ const sourceBuildPath = _path.default.join(resourcePath, tempItem);
512
+
513
+ const destBuildPath = _path.default.join(destDirPath, devicePackageName, aspectItem);
514
+
515
+ copyFiles(sourceBuildPath, destBuildPath);
516
+ return {
517
+ name: aspectItem,
518
+ targetFile: aspectItem === 'app' ? tempItem + '.base' : tempItem + '.aspc',
519
+ otherName: aspectItem === 'app' ? aspectItem + '.base' : aspectItem + '.aspc'
520
+ };
521
+ });
522
+ return deviceAspectsArr;
523
+ }
2
524
  //# sourceMappingURL=utils.js.map
package/lib/index.js CHANGED
@@ -1,2 +1,86 @@
1
- "use strict";const BuildModeManager=require("@aiot-toolkit/shared-utils/lib/buildMode/BuildModeManager"),{launchServer:launchServer,stopServer:stopServer}=require("@aiot-toolkit/server"),{compile:compile,stopWatch:stopWatch}=require("./commands/compile");function stopAll(){return Promise.all([stopServer(),stopWatch()]).then((([r,e])=>{const o=Object.assign({},r,e);return o.error=!(!r.stopServerError&&!e.stopWatchError),o}))}function launchWithWatch(r){const{cwd:e,log:o,onerror:t}=r;return Promise.all([launchServer(r),compile("native","dev",!0,{cwd:e,log:o,onerror:t})]).then((([r,e])=>{const o=Object.assign({},r,e);return o.error=!(!r.launchError&&!e.compileError),o}))}module.exports={compile:compile,stopWatch:stopWatch,launchServer:launchServer,stopServer:stopServer,launchWithWatch:launchWithWatch,stopAll:stopAll,BuildModeManager:BuildModeManager};
1
+ "use strict";
2
+
3
+ /**
4
+ * Copyright (C) 2017, hapjs.org. All rights reserved.
5
+ */
6
+ const BuildModeManager = require('@aiot-toolkit/shared-utils/lib/buildMode/BuildModeManager');
7
+
8
+ const {
9
+ launchServer,
10
+ stopServer
11
+ } = require('@aiot-toolkit/server');
12
+
13
+ const {
14
+ compile,
15
+ stopWatch
16
+ } = require('./commands/compile');
17
+ /**
18
+ * 关闭开发服务及停止webpack watching
19
+ *
20
+ * @module stopAll
21
+ * @returns {Promise} - 返回成功与否的信息
22
+ */
23
+
24
+
25
+ function stopAll() {
26
+ return Promise.all([stopServer(), stopWatch()]).then(([stopServerData, stopWatchData]) => {
27
+ const data = Object.assign({}, stopServerData, stopWatchData); // 得出布尔值
28
+
29
+ data.error = !!(stopServerData.stopServerError || stopWatchData.stopWatchError);
30
+ return data;
31
+ });
32
+ }
33
+ /**
34
+ * 启动开发服务及开启webpack watching
35
+ *
36
+ * @module launchWithWatch
37
+ * @param {Object} options - 参数配置项
38
+ * @param {String|Number} [options.port] - 服务端口
39
+ * @param {Array<debugger|packager>} [options.modules] - 加载其他模块
40
+ * @param {String} [options.chromePath] - 指定 chrome 的启动路径
41
+ * @param {String} [options.disableADB] - 是否禁止启用adb
42
+ * @param {String} [options.cwd] - 要运行的项目路径
43
+ * @param {String} [options.openDebugger] - 是否打开调试窗口
44
+ * @param {String} [options.webVersion] - 启用预览的 web.js 版本
45
+ * @param {Writable} [options.log] - 日志输出流
46
+ * @param {Function} [options.onerror] - compile 的错误回调函数
47
+ * @param {requestCallback} [options.callback] - 回调函数,用以传递回一些数据给调用方
48
+ * @returns {Promise} - 返回成功与否的信息
49
+ */
50
+
51
+ /**
52
+ * launchWithWatch 传进来的回调函数
53
+ * @callback requestCallback
54
+ * @param {string} action - toolkit进行到的操作
55
+ * @param {string} url - 调试页面的地址
56
+ */
57
+
58
+
59
+ function launchWithWatch(options) {
60
+ const {
61
+ cwd,
62
+ log,
63
+ onerror
64
+ } = options;
65
+ return Promise.all([launchServer(options), compile('native', 'dev', true, {
66
+ cwd,
67
+ log,
68
+ onerror
69
+ })]).then(([launchData, compileData]) => {
70
+ const data = Object.assign({}, launchData, compileData); // 得出布尔值
71
+
72
+ data.error = !!(launchData.launchError || compileData.compileError);
73
+ return data;
74
+ });
75
+ }
76
+
77
+ module.exports = {
78
+ compile,
79
+ stopWatch,
80
+ launchServer,
81
+ stopServer,
82
+ launchWithWatch,
83
+ stopAll,
84
+ BuildModeManager
85
+ };
2
86
  //# sourceMappingURL=index.js.map