mm_machine 2.9.7 → 2.9.9

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/drive.js CHANGED
@@ -1,394 +1,343 @@
1
- /**
2
- * Drive 驱动类
3
- * 提供 JSON 配置文件加载、JS 脚本文件热重载、模板文件生成等能力
4
- * @class Drive
5
- * @augments Mod
6
- */
7
- var path = require('path');
8
- var { Mod } = require('./mod');
1
+ const prettier = require('@prettier/sync');
2
+ require('mm_tpl');
3
+ let { conf } = require('mm_config');
4
+ const { Mod } = require('./mod');
5
+
6
+ if (!$.prettyCode) {
7
+ $.prettyCode = function (code, options) {
8
+ return prettier.format(code, options);
9
+ };
10
+ }
9
11
 
10
12
  /**
11
- * 静态配置默认值
13
+ * 驱动基础类
14
+ * @class
12
15
  */
13
- var defaultConfig = {
14
- name: '',
15
- title: '',
16
- description: '',
17
- main: '',
18
- func_name: 'main',
19
- scope: 0,
20
- sort: 100,
21
- mode: 3,
22
- state: 1
23
- };
24
-
25
16
  class Drive extends Mod {
17
+ // 配置项
18
+ static config = {
19
+ // 名称, 由中英文和下"_"组成, 用于卸载接口 例如: demo
20
+ name: '',
21
+ // 标题, 介绍作用
22
+ title: '',
23
+ // 描述, 用于描述该有什么用的
24
+ description: '',
25
+ // 文件路径, 当调用函数不存在时,会先从文件中加载
26
+ main: './index.js',
27
+ // 回调函数名 用于决定调用脚本的哪个函数
28
+ func_name: 'main',
29
+ // 作用域(同时作为检索的后缀名)
30
+ scope: $.val && $.val.scope ? $.val.scope : 'server',
31
+ // 排序
32
+ sort: 10,
33
+ // 状态, 0表示未启用, 1表示启用
34
+ state: 1,
35
+ // 显示, 0表示不显示, 1表示显示
36
+ show: 0,
37
+ // 是否结束,可选,默认false
38
+ end: false
39
+ };
40
+
26
41
  /**
27
42
  * 构造函数
28
- * @param {object} config 配置参数
29
- * @param {object} [parent] 父对象
43
+ * @param {object} config 配置项
44
+ * @param {object} parent 父项
45
+ * @class
30
46
  */
31
47
  constructor(config, parent) {
32
- super({ ...defaultConfig, ...config, parent: parent });
33
- this._config = {};
34
- this._script = '';
35
- this.is_loaded = false;
36
- this._main_func = null;
37
- this._watch = null;
38
- this._notify_timer = null;
39
- this._script_keys = null;
48
+ super({ ...Drive.config, ...config }, parent);
49
+ // 当前配置文件路径
40
50
  this.config_file = '';
41
- this.config = { ...defaultConfig, ...config };
42
- this.mode = this.config.mode;
51
+
52
+ // 当前脚本文件路径
53
+ this.script_file = '';
54
+
55
+ // 模式: 1.生产模式 2.热更新模式 3.热重载模式 4.热更新+重载模式 5.重载模式
56
+ this.mode = 1;
43
57
  }
44
58
  }
45
59
 
46
- // ==================== 事件管理 ====================
47
-
48
60
  /**
49
61
  * 获取事件触发器
50
62
  * @returns {object} 事件触发器
51
63
  */
52
64
  Drive.prototype.getEventer = function () {
53
- return typeof $.eventer !== 'undefined' ? $.eventer : this;
65
+ return $.eventer;
54
66
  };
55
67
 
56
68
  /**
57
- * 获取配置
58
- * @returns {object} 配置对象
69
+ * 配置驱动
59
70
  */
60
- Drive.prototype.getConfig = function () {
61
- return this.config;
62
- };
63
-
64
- /**
65
- * 获取模板目录
66
- * @returns {string} 模板目录
67
- */
68
- Drive.prototype.getTplDir = function () {
69
- if (!this.getParent) return '';
70
- var parent = this.getParent();
71
- return parent ? parent.getTplDir ? parent.getTplDir() : '' : '';
71
+ Drive.prototype._preset = function () {
72
+ let file = this.config.main;
73
+ if (file) {
74
+ this.script_file = file.fullname(this.getDir());
75
+ }
72
76
  };
73
77
 
74
- // ==================== 目录管理 ====================
75
-
76
78
  /**
77
- * 获取模块目录
78
- * 优先级:脚本文件目录 > 配置文件目录 > 父级目录 > 按名称拼接
79
- * @returns {string} 目录路径
79
+ * 获取配置
80
+ * @param {string} file 配置文件路径
81
+ * @returns {object} 配置项
80
82
  */
81
- Drive.prototype.getDir = function () {
82
- if (this._dir) {
83
- return this._dir;
83
+ Drive.prototype._loadConfig = function (file) {
84
+ if (file) {
85
+ this.config_file = file;
84
86
  }
85
- if (this._script) {
86
- this._dir = path.dirname(this._script);
87
- } else if (this.config_file) {
88
- this._dir = path.dirname(this.config_file);
89
- } else if (this.getParent && this.getParent()) {
90
- var parent_dir = this.getParent().getDir ? this.getParent().getDir() : '';
91
- if (parent_dir && this.config.name) {
92
- this._dir = path.resolve(parent_dir, this.config.name);
93
- }
87
+ // 加载配置
88
+ let config = $.loadJson(this.config_file);
89
+ if (!config) {
90
+ this.newConfig(this.config_file);
91
+ config = $.loadJson(this.config_file);
94
92
  }
95
- return this._dir || '';
93
+ this.setConfig(config);
94
+ return config;
96
95
  };
97
96
 
98
- // ==================== 配置管理 ====================
99
-
100
97
  /**
101
- * 预设处理
102
- * 计算脚本文件路径
103
- * @private
98
+ * 加载配置
99
+ * @param {string} file 配置文件路径
104
100
  */
105
- Drive.prototype._preset = function () {
106
- var main = this.config.main;
107
- if (main && this.config_file) {
108
- this._script = path.resolve(path.dirname(this.config_file), main);
109
- }
101
+ Drive.prototype.loadConfig = function (file) {
102
+ this._loadConfig(file);
110
103
  };
111
104
 
112
105
  /**
113
106
  * 设置配置
114
- * 合并配置并触发变更通知
115
- * @param {object} cfg 配置对象
116
- * @returns {object} 合并后的配置
107
+ * @param {object} config 配置对象
108
+ * @returns {object} 配置项
117
109
  */
118
- Drive.prototype.setConfig = function (cfg) {
119
- if (!cfg) {
120
- return this.config;
121
- }
110
+ Drive.prototype.setConfig = function (config) {
111
+ if (config) {
112
+ // 如果main改变,重置加载状态
113
+ if (config.main !== this.config.main) {
114
+ this._is_loaded = false;
115
+ }
122
116
 
123
- // 如果 main 改变,重置加载状态
124
- if (cfg.main !== undefined && cfg.main !== this.config.main) {
125
- this.is_loaded = false;
117
+ if (this.config_file) {
118
+ // 合并配置并应用配置处理
119
+ this.config = conf(
120
+ {
121
+ ...this.config,
122
+ ...config
123
+ },
124
+ this.config_file
125
+ );
126
+ } else {
127
+ Object.assign(this.config, config);
128
+ }
126
129
  }
127
-
128
- this.config = { ...this.config, ...cfg };
129
130
  this._preset();
130
131
  return this.config;
131
132
  };
132
133
 
133
134
  /**
134
- * 加载配置
135
- * 从 JSON 配置文件读取配置并合并
136
- * @param {string} file 配置文件路径
137
- * @returns {object} 配置对象
135
+ * 获取配置
136
+ * @returns {object} 配置项
138
137
  */
139
- Drive.prototype.loadConfig = function (file) {
140
- if (file) {
141
- this.config_file = file;
142
- }
143
- return this._loadConfig();
138
+ Drive.prototype.getConfig = function () {
139
+ return this.config;
144
140
  };
145
141
 
146
142
  /**
147
- * 内部加载配置
148
- * 支持热更新模式($.loadJson)和普通模式(require)
149
- * @returns {object} 配置对象
150
- * @private
143
+ * 获取当前文件
144
+ * @returns {object} 当前文件对象
151
145
  */
152
- Drive.prototype._loadConfig = function () {
153
- if (!this.config_file) {
154
- return this.config;
155
- }
156
-
157
- try {
158
- var config;
159
- if (this.mode === 2 || this.mode === 3 || this.mode === 4) {
160
- // 热更新模式:使用 $.loadJson
161
- if (typeof $.loadJson === 'function') {
162
- config = $.loadJson(this.config_file, (cg) => {
163
- this.setConfig(cg);
164
- return cg;
165
- });
166
- }
167
- }
168
- if (!config) {
169
- // 普通模式:使用 require 或 readFileSync
170
- try {
171
- config = require(this.config_file);
172
- } catch {
173
- var fs = require('fs');
174
- var content = fs.readFileSync(this.config_file, 'utf8');
175
- config = JSON.parse(content);
146
+ Drive.prototype.getDir = function () {
147
+ let dir = this._dir;
148
+ if (!dir) {
149
+ if (this.script_file) {
150
+ dir = this.script_file.dirname();
151
+ this._dir = dir;
152
+ } else if (this.config_file) {
153
+ dir = this.config_file.dirname();
154
+ this._dir = dir;
155
+ } else if (this.getParent) {
156
+ let parent_dir = this.getParent()?.getDir() || '';
157
+ if (parent_dir) {
158
+ dir = this.config.name.fullname(parent_dir);
176
159
  }
177
160
  }
178
- if (config) {
179
- this.setConfig(config);
180
- }
181
- } catch {
182
- // 配置文件不存在或解析失败,使用默认配置
183
161
  }
184
-
185
- return this.config;
162
+ return dir;
186
163
  };
187
164
 
188
165
  /**
189
- * 加载配置文件
190
- * @param {string} file 文件路径
191
- * @param {string} name 配置项名称
192
- * @returns {object|null} 配置对象
166
+ * 获取模板目录
167
+ * @returns {string} 模板目录
193
168
  */
194
- Drive.prototype.loadFile = function (file, name) {
195
- try {
196
- var fs = require('fs');
197
- var filename = path.resolve(this.getDir(), file);
198
- var text = '';
199
-
200
- try {
201
- text = fs.readFileSync(filename, 'utf8');
202
- } catch {
203
- // 文件不存在,创建新的配置文件
204
- this.newConfig(filename);
205
- try {
206
- text = fs.readFileSync(filename, 'utf8');
207
- } catch {
208
- return null;
209
- }
210
- }
211
-
212
- if (!text) return null;
213
-
214
- var config = this._loadHotReload(filename);
215
- var final_config = this._findConfigByName(config, name);
216
- return final_config;
217
- } catch (err) {
218
- this.log('error', '加载配置文件失败: ', err);
219
- return null;
220
- }
169
+ Drive.prototype._getTplDir = function () {
170
+ return this.getParent()?.getTplDir() || '';
221
171
  };
222
172
 
223
173
  /**
224
- * 根据模式加载配置(支持热更新)
225
- * @param {string} file 完整文件路径
226
- * @returns {object|Array|null} 配置对象
227
- * @private
174
+ * 移除加载的脚本模块
228
175
  */
229
- Drive.prototype._loadHotReload = function (file) {
230
- if (this.mode === 2 || this.mode === 3 || this.mode === 4) {
231
- if (typeof $.loadJson === 'function') {
232
- return $.loadJson(file, this._handleHotReload.bind(this));
233
- }
234
- }
176
+ Drive.prototype._remove = function () {
177
+ let file = this._getScriptFile();
178
+ if (!file) return;
179
+
235
180
  try {
236
- return require(file);
237
- } catch {
238
- var fs = require('fs');
239
- var content = fs.readFileSync(file, 'utf8');
240
- return JSON.parse(content);
181
+ if (this.mode >= 3) {
182
+ $.mod.unload(file);
183
+ } else {
184
+ // 移除模块缓存
185
+ let file_name = require.resolve(file);
186
+ if (require.cache[file_name]) {
187
+ require.cache[file_name] = null;
188
+ delete require.cache[file_name];
189
+ }
190
+ }
191
+ } catch (err) {
192
+ this.log('error', `移除加载的脚本模块失败`, err);
241
193
  }
242
194
  };
243
195
 
244
196
  /**
245
- * 热更新回调处理
246
- * @param {object} config 配置对象
247
- * @private
197
+ * 卸载脚本
248
198
  */
249
- Drive.prototype._handleHotReload = function (config) {
250
- this.setConfig(config);
251
- this._reloadIfNeeded();
252
- return config;
199
+ Drive.prototype.unloadScript = function () {
200
+ this._remove();
201
+ this._script_keys = null;
202
+ this._is_loaded = false;
253
203
  };
254
204
 
255
205
  /**
256
- * 根据名称在配置数组中查找配置项
257
- * @param {object|Array} config 配置对象或数组
258
- * @param {string} name 配置项名称
259
- * @returns {object|null} 匹配的配置项
260
- * @private
206
+ * 重新加载脚本
207
+ * @returns {object | null} 返回加载的模块对象
261
208
  */
262
- Drive.prototype._findConfigByName = function (config, name) {
263
- if (!name || !Array.isArray(config)) return config;
264
- return config.find((item) => item.name === name) || null;
209
+ Drive.prototype.reloadScript = function () {
210
+ this.unloadScript();
211
+ return this.loadScript();
265
212
  };
266
213
 
267
214
  /**
268
- * 根据模式决定是否重新加载脚本
269
- * @private
215
+ * 卸载之后处理
216
+ * @param {boolean} remove 是否删除文件
270
217
  */
271
- Drive.prototype._reloadIfNeeded = function () {
272
- if (this.mode === 3 || this.mode === 4) {
273
- this.reloadScript();
218
+ Drive.prototype.unloadCore = async function (remove) {
219
+ // 删除脚本
220
+ this.unloadScript();
221
+ if (remove) {
222
+ this.delFile();
274
223
  }
275
224
  };
276
225
 
277
- // ==================== 脚本管理 ====================
278
-
279
226
  /**
280
227
  * 获取脚本文件路径
281
- * @returns {string|null} 完整文件路径
282
- * @private
228
+ * @returns {string | null} 完整文件路径
283
229
  */
284
230
  Drive.prototype._getScriptFile = function () {
285
- var main = this.config.main || '';
231
+ let main = this.config.main || '';
286
232
  if (!main) return null;
287
233
 
288
- var filename = path.resolve(this.getDir(), main);
289
- var fs = require('fs');
290
- if (!fs.existsSync(filename)) {
234
+ let filename = main.fullname(this.getDir());
235
+ if (!filename.hasFile()) {
291
236
  this.newScript(filename);
292
237
  }
293
238
  return filename;
294
239
  };
295
240
 
296
241
  /**
297
- * 加载脚本
298
- * 检查 main 配置,require 脚本文件并注册方法
299
- * @returns {boolean} 是否加载成功
300
- * @private
242
+ * 新建脚本文件
243
+ * @param {string} file 目标文件路径
301
244
  */
302
- Drive.prototype._loadScript = function () {
303
- var main = this.config.main;
304
- if (!main) {
305
- // 配置型模块,无脚本
306
- return false;
307
- }
245
+ Drive.prototype.newScript = function (file) {
246
+ this._createScriptFile(file);
247
+ };
308
248
 
309
- var script_path = this._script;
310
- if (!script_path) {
311
- return false;
249
+ /**
250
+ * 创建脚本
251
+ * @param {string} file 文件路径
252
+ * @returns {boolean} 创建是否成功
253
+ */
254
+ Drive.prototype._createScriptFile = function (file) {
255
+ var tpl = this._getScriptTpl();
256
+ var content = $.tpl.render(tpl, this.getModel('script'));
257
+ if (!content) {
258
+ return '';
312
259
  }
260
+ let code = this.prettyCode(content, 'js');
261
+ file.saveText(code);
262
+ return file;
263
+ };
313
264
 
314
- var fs = require('fs');
315
- if (!fs.existsSync(script_path)) {
316
- return false;
265
+ /**
266
+ * 获取脚本模板
267
+ * @returns {string} 脚本模板内容
268
+ */
269
+ Drive.prototype._getScriptTpl = function () {
270
+ var f = './script.tpl.js'.fullname(this._getTplDir());
271
+ if (f.hasFile()) {
272
+ return f.loadText();
273
+ } else {
274
+ return `module.exports = {
275
+ /**
276
+ * 初始化
277
+ */
278
+ async _init() {
279
+ this.log('debug', \`初始化!\`);
280
+ },
281
+ /**
282
+ * 启动
283
+ */
284
+ async _start() {
285
+ this.log('debug', \`启动!\`);
286
+ },
287
+ /**
288
+ * 停止
289
+ */
290
+ async _stop() {
291
+ this.log('debug', \`停止!\`);
292
+ },
293
+ /**
294
+ * 销毁
295
+ */
296
+ async _destroy(...args) {
297
+ this.log('debug', \`销毁!\`);
298
+ },
299
+ /**
300
+ * 主要逻辑
301
+ */
302
+ async main(...args) {
303
+ // 主要代码写在这
317
304
  }
318
-
319
- try {
320
- var exports;
321
- if (this.mode === 3 || this.mode === 4) {
322
- // 开发模式:使用 $.require 进行热重载
323
- if (typeof $.require === 'function') {
324
- exports = $.require(script_path, (mod) => {
325
- this._setMainMethod(mod);
326
- });
327
- } else {
328
- exports = require(script_path);
329
- }
330
- } else {
331
- // 生产模式:清除缓存后 require
332
- try {
333
- var resolved = require.resolve(script_path);
334
- if (require.cache[resolved]) {
335
- delete require.cache[resolved];
336
- }
337
- } catch {
338
- // 模块未缓存,忽略
339
- }
340
- exports = require(script_path);
341
- }
342
-
343
- this._setMainMethod(exports);
344
- this.is_loaded = true;
345
- return true;
346
- } catch {
347
- // 脚本加载失败
348
- this.is_loaded = false;
349
- return false;
305
+ }`;
350
306
  }
351
307
  };
352
308
 
353
309
  /**
354
- * 加载脚本文件(外部接口)
355
- * 在开发模式下使用 $.require 进行热重载,在生产模式下使用标准 require
356
- * @returns {object|null} 加载的模块对象
310
+ * 加载脚本文件,支持热重载模式
311
+ * 在开发模式(mode=3或4)下使用 $.require 进行热重载
312
+ * 在生产模式下使用标准的 require 加载
313
+ * @returns {object | null} 加载的模块对象
357
314
  */
358
315
  Drive.prototype.loadScript = function () {
359
- var file = this._getScriptFile();
316
+ let file = this._getScriptFile();
360
317
  if (!file) return null;
361
-
362
- if (this.mode === 3 || this.mode === 4) {
363
- // 开发模式:使用 $.require 进行热重载
364
- if (typeof $.require === 'function') {
365
- var cs = $.require(file, (mod) => {
366
- this._setMainMethod(mod);
367
- });
368
- this._setMainMethod(cs);
369
- return cs;
370
- }
318
+ if (this.mode >= 3) {
319
+ var cs = $.require(file, (mod) => {
320
+ this._setMainMethod(mod);
321
+ });
322
+ this._setMainMethod(cs);
323
+ return cs;
324
+ } else {
325
+ var cs = require(file);
326
+ this._setMainMethod(cs);
327
+ return cs;
371
328
  }
372
-
373
- var cs = require(file);
374
- this._setMainMethod(cs);
375
- return cs;
376
329
  };
377
330
 
378
331
  /**
379
332
  * 设置主方法
380
- * 从脚本导出对象中注册方法和数据
381
- * @param {object} mod 脚本导出对象
382
- * @private
333
+ * @param {object} mod 模块对象
383
334
  */
384
335
  Drive.prototype._setMainMethod = function (mod) {
385
336
  if (!mod) return;
386
-
387
337
  var name = this.config.func_name || 'main';
388
- if (name && mod[name]) {
389
- this._main_func = mod[name];
338
+ if (name && typeof mod[name] === 'function') {
339
+ this.main = mod[name];
390
340
  }
391
-
392
341
  var new_keys = Object.keys(mod);
393
342
  // 热重载时如果脚本未变化则跳过重建
394
343
  if (this._script_keys && this._script_keys.length === new_keys.length) {
@@ -400,520 +349,376 @@ Drive.prototype._setMainMethod = function (mod) {
400
349
  }
401
350
  }
402
351
  if (same) {
403
- this.is_loaded = true;
352
+ this._is_loaded = true;
404
353
  return;
405
354
  }
406
355
  }
407
-
408
356
  this._script_keys = new_keys;
409
357
  for (var key in mod) {
410
358
  var obj = mod[key];
411
359
  if (typeof obj === 'function') {
412
360
  this.setMethod(key, obj);
413
361
  } else {
414
- try {
415
- // eslint-disable-next-line mm_eslint/function-name
416
- this.setData(key, obj);
417
- } catch {
418
- // 忽略类型错误
419
- }
362
+ this.setData(key, obj);
420
363
  }
421
364
  }
422
- this.is_loaded = true;
365
+ this._is_loaded = true;
423
366
  };
424
367
 
425
368
  /**
426
- * 移除加载的脚本模块
427
- * @private
369
+ * 获取配置文件作用域
370
+ * @param {object} file 文件对象
371
+ * @returns {string} 配置文件作用域
428
372
  */
429
- Drive.prototype._remove = function () {
430
- var file = this._getScriptFile();
431
- if (!file) return;
373
+ Drive.prototype._getScope = function (file) {
374
+ return file.replace(/\\/g, '/').between('app/', '/');
375
+ };
432
376
 
433
- try {
434
- if (this.mode === 3 || this.mode === 4) {
435
- // 移除模块和监听
436
- if (typeof $.unload === 'function') {
437
- $.unload(file);
438
- }
439
- } else {
440
- // 移除模块缓存
441
- try {
442
- var filename = require.resolve(file);
443
- if (require.cache[filename]) {
444
- delete require.cache[filename];
445
- }
446
- } catch {
447
- // 忽略
448
- }
449
- }
450
- } catch (err) {
451
- this.log('error', '移除加载的脚本模块失败: ', err);
377
+ /**
378
+ * 新建配置文件
379
+ * @param {string} file 目标文件路径
380
+ */
381
+ Drive.prototype.newConfig = function (file) {
382
+ if (!this.config.name) {
383
+ this.config.name = this._getName(file);
384
+ this.config.scope = this._getScope(file);
452
385
  }
386
+ this._createConfigFile(file);
453
387
  };
454
388
 
455
389
  /**
456
- * 卸载脚本
457
- * 清除 require.cache,重置加载状态
390
+ * 预试代码
391
+ * @param {string} code 要预试的代码
392
+ * @param {string} type 预试类型,可选"json"或"js"
393
+ * @returns {string} 预试后的代码字符串
458
394
  */
459
- Drive.prototype.unloadScript = function () {
460
- this._remove();
461
- this._script_keys = null;
462
- this.is_loaded = false;
395
+ Drive.prototype.prettyCode = function (code, type = 'json5') {
396
+ let options = {
397
+ tabWidth: 2
398
+ };
399
+ switch (type) {
400
+ case 'json5':
401
+ options.parser = 'json5';
402
+ break;
403
+ case 'js':
404
+ case 'javascript':
405
+ options.parser = 'babel';
406
+ options.semi = true; // 在语句末尾添加分号
407
+ options.singleQuote = true; // 使用单引号
408
+ break;
409
+ default:
410
+ options.parser = 'json';
411
+ break;
412
+ }
413
+ let new_code = $.prettyCode(code, options);
414
+ return new_code;
463
415
  };
464
416
 
465
417
  /**
466
- * 重新加载脚本
467
- * @returns {object|null} 返回加载的模块对象
418
+ * 获取模块模型
419
+ * @param {string} type 模型类型,可选"config"或"script"
420
+ * @returns {object} 模块模型
468
421
  */
469
- Drive.prototype.reloadScript = function () {
470
- this.unloadScript();
471
- return this.loadScript();
422
+ Drive.prototype.getModel = function (type) {
423
+ return this.config;
472
424
  };
473
425
 
474
426
  /**
475
- * 加载前处理
427
+ * 创建配置文件
428
+ * @param {string} file 目标文件路径
429
+ * @param {object} model 模块模型
430
+ * @returns {string} 配置文件内容
476
431
  */
477
- Drive.prototype.loadBefore = function () {
478
- try {
479
- var module = this.loadScript();
480
- if (module) {
481
- this.is_loaded = true;
482
- }
483
- } catch (err) {
484
- this.log('error', '加载前处理失败: ', err);
485
- this.is_loaded = false;
486
- }
432
+ Drive.prototype._createConfigFile = function (file, model) {
433
+ var tpl = this._getConfigTpl();
434
+ var content = $.tpl.render(tpl, model || this.getModel('config'));
435
+ let code = this.prettyCode(content, 'json');
436
+ file.saveText(code);
437
+ return file;
487
438
  };
488
439
 
489
- // ==================== 文件操作 ====================
440
+ /**
441
+ * 创建配置文件
442
+ * @param {string} file 目标文件路径
443
+ * @param {object} model 模块模型
444
+ * @returns {string} 配置文件内容
445
+ */
446
+ Drive.prototype.createConfigFile = function (file, model) {
447
+ file.addDir();
448
+ return this._createConfigFile(file, model);
449
+ };
490
450
 
491
451
  /**
492
- * 保存配置
452
+ * 获取配置模板
453
+ * @returns {string} 配置模板内容
493
454
  */
494
- Drive.prototype.save = function () {
495
- var file = this._script || this.config_file;
496
- if (!file) return;
455
+ Drive.prototype._getConfigTpl = function () {
456
+ var f = './config.tpl.json'.fullname(this._getTplDir());
457
+ if (f.hasFile()) {
458
+ return f.loadText();
459
+ } else {
460
+ return `{
461
+ // 模块名称,必填
462
+ "name": "\${name}",
463
+ // 模块标题,可选,默认"示例标题"
464
+ "title": "\${title || '示例标题'}",
465
+ // 模块描述,可选,默认"示例描述"
466
+ "description": "\${description || '示例描述'}",
467
+ // 主脚本文件路径,可选,默认"./index.js"
468
+ "main": "\${main || './index.js'}",
469
+ // 模块作用域,可选,默认"server"
470
+ "scope": "\${scope || 'server'}",
471
+ // 模块状态,可选,默认1
472
+ "state": \${state || 1},
473
+ // 模块排序,可选,默认100
474
+ "sort": \${sort || 100},
475
+ // 是否结束,可选,默认false
476
+ "end": \${end || false}
477
+ }`;
478
+ }
479
+ };
497
480
 
498
- var fs = require('fs');
481
+ /**
482
+ * 加载配置文件
483
+ * @param {string} file 文件路径
484
+ * @param {string} name 配置项名称
485
+ * @returns {object | null} 配置对象
486
+ */
487
+ Drive.prototype.loadFile = function (file, name) {
499
488
  try {
500
- var text = fs.readFileSync(file, 'utf8');
489
+ let filename = file.fullname(this.getDir());
490
+ let text = filename.loadText();
501
491
 
502
- if (text && text.trim().startsWith('[')) {
503
- // 数组格式配置
504
- var config = JSON.parse(text);
505
- if (Array.isArray(config)) {
506
- var index = config.findIndex((item) => item.name === this.config.name);
507
- if (index !== -1) {
508
- config[index] = this.config;
509
- } else {
510
- config.push(this.config);
511
- }
512
- fs.writeFileSync(file, JSON.stringify(config, null, 2), 'utf8');
513
- return;
514
- }
492
+ // 如果文件不存在,创建新的配置文件
493
+ if (!text) {
494
+ this.newConfig(filename);
495
+ text = filename.loadText();
515
496
  }
516
497
 
517
- // 单对象格式配置,直接保存
518
- fs.writeFileSync(file, JSON.stringify(this.config, null, 2), 'utf8');
498
+ if (!text) return null;
499
+
500
+ let config = this._loadHotReload(filename);
501
+ let final_config = this._findConfigByName(config, name);
502
+ return final_config;
519
503
  } catch (err) {
520
- this.log('error', '保存配置失败: ', err);
504
+ this.log('error', `[${this.config.name}] 加载配置文件失败`, err);
505
+ return null;
521
506
  }
522
507
  };
523
508
 
524
509
  /**
525
- * 删除项目
526
- * @returns {string|null} 删除的目录路径
510
+ * 根据模式加载配置(支持热更新)
511
+ * @param {string} file 完整文件路径
512
+ * @returns {object | Array | null} 配置对象
527
513
  */
528
- Drive.prototype.remove = function () {
529
- var dir = this.getDir();
530
- if (dir) {
531
- var fs = require('fs');
532
- try {
533
- fs.rmdirSync(dir, { recursive: true });
534
- } catch {
535
- // 忽略
536
- }
514
+ Drive.prototype._loadHotReload = function (file) {
515
+ if (this.mode >= 2) {
516
+ return $.loadJson(file, this._handleHotReload.bind(this));
517
+ }
518
+ return file.loadJson();
519
+ };
520
+
521
+ /**
522
+ * 根据名称在配置数组中查找配置项
523
+ * @param {object | Array} config 配置对象或数组
524
+ * @param {string} name 配置项名称
525
+ * @returns {object | null} 匹配的配置项
526
+ */
527
+ Drive.prototype._findConfigByName = function (config, name) {
528
+ if (!name || !Array.isArray(config)) return config;
529
+ return config.find((item) => item.name === name) || null;
530
+ };
531
+
532
+ /**
533
+ * 热更新回调处理
534
+ * @param {object} config 配置对象
535
+ * @returns {object} 配置对象
536
+ * @private
537
+ */
538
+ Drive.prototype._handleHotReload = function (config) {
539
+ this.setConfig(config);
540
+ this._reloadIfNeeded();
541
+ return config;
542
+ };
543
+
544
+ /**
545
+ * 根据模式决定是否重新加载脚本
546
+ */
547
+ Drive.prototype._reloadIfNeeded = function () {
548
+ if (this.mode >= 3) {
549
+ this.reloadScript();
537
550
  }
538
- return dir;
539
551
  };
540
552
 
541
553
  /**
542
554
  * 删除目录
543
555
  */
544
556
  Drive.prototype.delDir = function () {
545
- var dir = this.getDir();
546
- if (dir) {
547
- var fs = require('fs');
548
- try {
549
- fs.rmdirSync(dir, { recursive: true });
550
- } catch {
551
- // 忽略
552
- }
557
+ let main = this.config.main;
558
+ if (main && $.dir && $.dir.del) {
559
+ $.dir.del(this.dir);
553
560
  }
554
561
  };
555
562
 
556
563
  /**
557
564
  * 删除配置和脚本文件
558
- * @returns {string|null} 错误消息,如果没有错误则返回 null
565
+ * @returns {string | null} 错误消息,如果没有错误则返回null
559
566
  */
560
567
  Drive.prototype.delFile = function () {
561
- var fs = require('fs');
562
- var name = this.config.name;
563
- var file = this._script || this.config_file;
568
+ let name = this.config.name;
569
+ let cfg_file = this.config_file;
570
+ let script_file = this.script_file;
564
571
 
572
+ let error_message = null;
565
573
  try {
566
- if (!file) return null;
567
- if (!fs.existsSync(file)) return '文件不存在';
568
-
569
- return this._delConfigFile(file, name);
574
+ // 删除配置文件(JSON)
575
+ if (cfg_file && cfg_file.hasFile && cfg_file.hasFile()) {
576
+ if (cfg_file.loadText()) {
577
+ error_message = this._delConfigFile(cfg_file, name);
578
+ }
579
+ }
580
+ // 删除脚本文件(JS,不尝试 JSON 解析)
581
+ if (script_file && script_file.hasFile && script_file.hasFile()) {
582
+ this._remove();
583
+ script_file.delFile();
584
+ }
570
585
  } catch (err) {
571
- this.log('error', '删除文件失败: ', err);
572
- return '删除失败: ' + (err.message || '');
586
+ this.log('error', `[${this.config.name}] 删除文件失败`, err);
587
+ error_message = error_message || `删除失败: ${err.message}`;
573
588
  }
589
+ return error_message;
574
590
  };
575
591
 
576
592
  /**
577
593
  * 删除配置文件
578
- * @param {string} file 文件路径
594
+ * @param {object} file 文件对象
579
595
  * @param {string} name 配置名称
580
- * @returns {string|null} 错误消息
581
- * @private
596
+ * @returns {string | null} 错误消息
582
597
  */
583
598
  Drive.prototype._delConfigFile = function (file, name) {
584
- var fs = require('fs');
585
- try {
586
- var text = fs.readFileSync(file, 'utf8');
587
- if (!text) {
588
- this.delDir();
589
- return null;
590
- }
591
-
592
- var config = JSON.parse(text);
593
- if (Array.isArray(config)) {
594
- return this._delArray(file, config, name);
595
- }
596
-
597
- this.delDir();
598
- return null;
599
- } catch {
599
+ let text = file.loadText();
600
+ if (!text) {
600
601
  this.delDir();
601
602
  return null;
602
603
  }
604
+
605
+ let config = text.toJson();
606
+ if (Array.isArray(config)) {
607
+ return this._delArray(file, config, name);
608
+ }
609
+
610
+ this.delDir();
611
+ return null;
603
612
  };
604
613
 
605
614
  /**
606
615
  * 从数组配置中删除指定项
607
- * @param {string} file 文件路径
616
+ * @param {object} file 文件对象
608
617
  * @param {Array} config 配置数组
609
618
  * @param {string} name 配置名称
610
- * @returns {string|null} 错误消息
611
- * @private
619
+ * @returns {string | null} 错误消息
612
620
  */
613
621
  Drive.prototype._delArray = function (file, config, name) {
614
- var fs = require('fs');
615
- var index = config.findIndex((item) => item.name === name);
622
+ let index = config.findIndex((item) => item.name === name);
616
623
  if (index === -1) return null;
617
624
 
625
+ this.delDir();
618
626
  config.splice(index, 1);
619
627
 
620
628
  if (config.length > 0) {
621
- fs.writeFileSync(file, JSON.stringify(config, null, 2), 'utf8');
622
- } else {
623
- try {
624
- fs.unlinkSync(file);
625
- } catch {
626
- // 忽略
627
- }
629
+ file.saveText(JSON.stringify(config, null, 2));
630
+ } else if (file.delFile) {
631
+ file.delFile();
628
632
  }
629
633
 
630
- this.delDir();
631
634
  return null;
632
635
  };
633
636
 
634
637
  /**
635
638
  * 获取配置文件名称
636
- * @param {string} file 文件路径
639
+ * @param {object} file 文件对象
637
640
  * @returns {string} 配置文件名称
638
- * @private
639
641
  */
640
642
  Drive.prototype._getName = function (file) {
641
- return path.basename(path.dirname(file));
642
- };
643
-
644
- /**
645
- * 获取配置文件作用域
646
- * @param {string} file 文件路径
647
- * @returns {string} 配置文件作用域
648
- * @private
649
- */
650
- Drive.prototype._getScope = function (file) {
651
- var normalized = file.replace(/\\/g, '/');
652
- var idx = normalized.indexOf('app/');
653
- if (idx === -1) return '';
654
- return normalized.substring(idx + 4, normalized.indexOf('/', idx + 4));
643
+ let name = file.dirname().basename();
644
+ return name;
645
+ // // 提取文件名作为模块名
646
+ // var word = new Word();
647
+ // // 将文件名改为驼峰命名法
648
+ // return word.toCamelCase(name);
655
649
  };
656
650
 
657
- // ==================== 模板/文件创建 ====================
658
-
659
651
  /**
660
- * 获取脚本模板
661
- * @returns {string} 脚本模板内容
662
- * @private
663
- */
664
- Drive.prototype._getScriptTpl = function () {
665
- var fs = require('fs');
666
- var f = path.resolve(this.getTplDir(), 'script.tpl.js');
667
- if (fs.existsSync(f)) {
668
- return fs.readFileSync(f, 'utf8');
669
- }
670
- return 'module.exports = {\n' +
671
- ' /**\n' +
672
- ' * 初始化\n' +
673
- ' */\n' +
674
- ' async _init() {\n' +
675
- " this.log('debug', '初始化!');\n" +
676
- ' },\n' +
677
- ' /**\n' +
678
- ' * 启动\n' +
679
- ' */\n' +
680
- ' async _start() {\n' +
681
- " this.log('debug', '启动!');\n" +
682
- ' },\n' +
683
- ' /**\n' +
684
- ' * 停止\n' +
685
- ' */\n' +
686
- ' async _stop() {\n' +
687
- " this.log('debug', '停止!');\n" +
688
- ' },\n' +
689
- ' /**\n' +
690
- ' * 销毁\n' +
691
- ' */\n' +
692
- ' async _destroy() {\n' +
693
- " this.log('debug', '销毁!');\n" +
694
- ' },\n' +
695
- ' /**\n' +
696
- ' * 主要逻辑\n' +
697
- ' */\n' +
698
- ' async main() {\n' +
699
- ' // 主要代码写在这\n' +
700
- ' }\n' +
701
- '};\n';
702
- };
703
-
704
- /**
705
- * 获取配置模板
706
- * @returns {string} 配置模板内容
707
- * @private
708
- */
709
- Drive.prototype._getConfigTpl = function () {
710
- var fs = require('fs');
711
- var f = path.resolve(this.getTplDir(), 'config.tpl.json');
712
- if (fs.existsSync(f)) {
713
- return fs.readFileSync(f, 'utf8');
714
- }
715
- return '{\n' +
716
- ' "name": "${name}",\n' +
717
- ' "title": "${title || \'示例标题\'}",\n' +
718
- ' "description": "${description || \'示例描述\'}",\n' +
719
- ' "main": "${main || \'./index.js\'}",\n' +
720
- ' "scope": "${scope || \'server\'}",\n' +
721
- ' "state": ${state || 1},\n' +
722
- ' "sort": ${sort || 100}\n' +
723
- '}\n';
724
- };
725
-
726
- /**
727
- * 获取模块模型
728
- * @param {string} type 模型类型,可选 "config" 或 "script"
729
- * @returns {object} 模块模型
730
- */
731
- Drive.prototype.getModel = function (type) {
732
- return this.config;
733
- };
734
-
735
- /**
736
- * 新建配置文件
737
- * @param {string} file 目标文件路径
738
- */
739
- Drive.prototype.newConfig = function (file) {
740
- if (!this.config.name) {
741
- this.config.name = this._getName(file);
742
- this.config.scope = this._getScope(file);
743
- }
744
- this._createConfigFile(file);
745
- };
746
-
747
- /**
748
- * 创建配置文件
749
- * @param {string} file 目标文件路径
750
- * @param {object} model 模块模型
751
- * @returns {string} 文件路径
652
+ * 加载前处理
752
653
  */
753
- Drive.prototype._createConfigFile = function (file, model) {
754
- var fs = require('fs');
755
- var tpl = this._getConfigTpl();
756
- var content = this._renderTpl(tpl, model || this.getModel('config'));
757
- var code = this.prettyCode(content, 'json');
758
- var dir = path.dirname(file);
759
- if (!fs.existsSync(dir)) {
760
- fs.mkdirSync(dir, { recursive: true });
654
+ Drive.prototype.loadBefore = function () {
655
+ try {
656
+ let mod = this.loadScript();
657
+ if (mod) {
658
+ this._is_loaded = true;
659
+ }
660
+ } catch (err) {
661
+ this.log('error', `[${this.config.name}] 加载前处理失败`, err);
662
+ this._is_loaded = false;
761
663
  }
762
- fs.writeFileSync(file, code, 'utf8');
763
- return file;
764
664
  };
765
665
 
766
666
  /**
767
- * 创建配置文件(带目录创建)
768
- * @param {string} file 目标文件路径
769
- * @param {object} model 模块模型
770
- * @returns {string} 文件路径
667
+ * 加载处理
771
668
  */
772
- Drive.prototype.createConfigFile = function (file, model) {
773
- var fs = require('fs');
774
- var dir = path.dirname(file);
775
- if (!fs.existsSync(dir)) {
776
- fs.mkdirSync(dir, { recursive: true });
777
- }
778
- return this._createConfigFile(file, model);
669
+ Drive.prototype._loadCore = function () {
670
+ // this.loadConfig();
671
+ // this.loadScript();
779
672
  };
780
673
 
781
674
  /**
782
- * 新建脚本文件
783
- * @param {string} file 目标文件路径
675
+ * 保存配置
784
676
  */
785
- Drive.prototype.newScript = function (file) {
786
- this._createScriptFile(file);
787
- };
677
+ Drive.prototype.save = function () {
678
+ try {
679
+ if (!this.config_file) return;
788
680
 
789
- /**
790
- * 创建脚本文件
791
- * @param {string} file 文件路径
792
- * @returns {string} 文件路径
793
- * @private
794
- */
795
- Drive.prototype._createScriptFile = function (file) {
796
- var fs = require('fs');
797
- var tpl = this._getScriptTpl();
798
- var content = this._renderTpl(tpl, this.getModel('script'));
799
- var code = this.prettyCode(content, 'js');
800
- var dir = path.dirname(file);
801
- if (!fs.existsSync(dir)) {
802
- fs.mkdirSync(dir, { recursive: true });
803
- }
804
- fs.writeFileSync(file, code, 'utf8');
805
- return file;
806
- };
681
+ let file = this.config_file;
682
+ let text = file.loadText();
807
683
 
808
- /**
809
- * 渲染模板(简单替换 ${key} 占位符)
810
- * @param {string} tpl 模板内容
811
- * @param {object} model 模型数据
812
- * @returns {string} 渲染后的内容
813
- * @private
814
- */
815
- Drive.prototype._renderTpl = function (tpl, model) {
816
- return tpl.replace(/\$\{([^}]+)\}/g, (match, key) => {
817
- // 处理默认值表达式:${key || 'default'}
818
- var parts = key.split('||').map((s) => s.trim());
819
- var var_name = parts[0];
820
- var default_val = '';
821
- if (parts.length > 1) {
822
- default_val = parts[1].replace(/^['"]|['"]$/g, '');
823
- }
824
- var val = model ? model[var_name] : undefined;
825
- return val !== undefined && val !== null ? val : default_val;
826
- });
827
- };
828
-
829
- /**
830
- * 美化代码
831
- * @param {string} code 代码字符串
832
- * @param {string} type 代码类型,可选 "json" 或 "js"
833
- * @returns {string} 美化后的代码
834
- */
835
- Drive.prototype.prettyCode = function (code, type) {
836
- if (typeof $.prettyCode === 'function') {
837
- var options = {
838
- tab_width: 2
839
- };
840
- switch (type) {
841
- case 'json5':
842
- case 'json':
843
- options.parser = 'json5';
844
- break;
845
- case 'js':
846
- case 'javascript':
847
- options.parser = 'babel';
848
- options.semi = true;
849
- options.singleQuote = true;
850
- break;
851
- default:
852
- options.parser = 'json';
853
- break;
684
+ if (text && text.trim().startsWith('[')) {
685
+ // 数组格式配置
686
+ let config = text.toJson();
687
+ if (Array.isArray(config)) {
688
+ // 查找并更新现有配置项
689
+ let index = config.findIndex((Drive) => Drive.name === this.config.name);
690
+ if (index !== -1) {
691
+ config[index] = this.config;
692
+ } else {
693
+ // 如果不存在,添加新配置项
694
+ config.push(this.config);
695
+ }
696
+ file.saveText(JSON.stringify(config, null, 2));
697
+ return;
698
+ }
854
699
  }
855
- return $.prettyCode(code, options);
700
+
701
+ // 单对象格式配置,直接保存
702
+ file.saveText(JSON.stringify(this.config, null, 2));
703
+ } catch (err) {
704
+ this.log('error', `[${this.config.name}] 保存配置失败`, err);
856
705
  }
857
- return code;
858
706
  };
859
707
 
860
- // ==================== 生命周期重写 ====================
861
-
862
708
  /**
863
- * 加载核心
864
- * 加载配置文件和脚本文件
865
- * @returns {Promise<void>}
866
- * @private
867
- * @override
709
+ * 删除项目
868
710
  */
869
- Drive.prototype._loadCore = async function () {
870
- if (this.lifecycle_state !== 'created') {
871
- throw new Error('模块未创建,无法加载');
872
- }
873
-
874
- this.emit('load:before');
875
-
876
- try {
877
- // 加载配置
878
- this._loadConfig();
879
- // 加载脚本
880
- this._loadScript();
881
- this.lifecycle_state = 'loaded';
882
- this.emit('load:success');
883
- } catch (err) {
884
- this.emit('load:error', err);
885
- throw err;
711
+ Drive.prototype.remove = function () {
712
+ let dir = this.getDir();
713
+ if (dir) {
714
+ dir.delDir();
886
715
  }
716
+ return dir;
887
717
  };
888
718
 
889
719
  /**
890
- * 结束核心
891
- * 先调用 _end 钩子,再卸载脚本
892
- * @returns {Promise<void>}
893
- * @private
894
- * @override
720
+ * @module 导出Drive类
895
721
  */
896
- Drive.prototype._endCore = async function () {
897
- if (this.lifecycle_state !== 'started' && this.lifecycle_state !== 'paused') {
898
- throw new Error('模块未启动或暂停,无法结束');
899
- }
900
-
901
- this.emit('end:before');
902
-
903
- try {
904
- var end_hook = this.getMethod('_end');
905
- if (end_hook) {
906
- end_hook(this);
907
- }
908
-
909
- // 卸载脚本
910
- this.unloadScript();
911
- this.lifecycle_state = 'ended';
912
- this.emit('end:success');
913
- } catch (err) {
914
- this.emit('end:error', err);
915
- throw err;
916
- }
722
+ module.exports = {
723
+ Drive
917
724
  };
918
-
919
- module.exports = { Drive };