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