mm_config 2.8.1 → 2.9.1

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/index.js CHANGED
@@ -1,22 +1,16 @@
1
1
  const { reg } = require('mm_admin');
2
2
  const Config = require('./lib/config.js');
3
+ const ConfigFile = require('./lib/config_file.js');
3
4
  const all = require('./lib/conf.js');
5
+ const { configAdmin } = require('./lib/admin.js');
4
6
 
5
- const admin = reg('config');
7
+ let admin = reg('config');
6
8
  admin.setClass(Config);
7
9
 
8
10
  module.exports = {
9
11
  ...all,
10
12
  Config,
13
+ ConfigFile,
11
14
  admin,
12
- configAdmin(scope, config) {
13
- return admin.get(scope || 'os', config);
14
- }
15
+ configAdmin
15
16
  };
16
-
17
- /* mm-tool-logic-export 工具能力层:其它模块可 require("<pkg>").tools.<name> 直接引用 */
18
- Object.defineProperty(module.exports, 'tools', { enumerable: true, configurable: true,
19
- get: function () { return require('./lib/tools'); } });
20
-
21
- /* S1 能力下沉:业务实现可在模块之间直接引用(不经过工具注册面) */
22
- Object.defineProperty(module.exports, 'runPathLogic', { enumerable: true, value: require('./lib/run_path_logic.js') });
package/lib/admin.js ADDED
@@ -0,0 +1,27 @@
1
+ const { reg } = require('mm_admin');
2
+
3
+ /**
4
+ * mm_admin 注册实例管理(非类文件)
5
+ * configAdmin 获取/创建 mm_admin 'config' 注册池中的配置实例,并在首次创建时恢复持久化状态。
6
+ */
7
+
8
+ /**
9
+ * 获取配置实例(带注册池管理)
10
+ * @param {string} [scope] - 实例名称,缺省为 'os'
11
+ * @param {object} [config] - 配置选项
12
+ * @returns {object} 配置实例
13
+ */
14
+ function configAdmin(scope, config) {
15
+ let admin = reg('config');
16
+ let name = scope || 'os';
17
+ let existed = admin.has(name);
18
+ let instance = admin.get(name, config);
19
+ if (!existed && typeof instance.restore === 'function') {
20
+ instance.restore();
21
+ }
22
+ return instance;
23
+ }
24
+
25
+ module.exports = {
26
+ configAdmin
27
+ };
package/lib/conf.js CHANGED
@@ -1,338 +1,74 @@
1
- const { Base } = require('mm_mod');
2
- const { push, fullname, hasFile, loadJson, saveJson } = require('mm_helper');
1
+ const { fullname, hasFile } = require('mm_files');
2
+ const ConfigFile = require('./config_file.js');
3
+ const { reg } = require('mm_admin');
3
4
 
4
5
  /**
5
- * 配置字典(私有)
6
- * @type {object}
6
+ * 配置文件工厂与缓存管理(非类文件)
7
+ * create / createAsync 创建带落盘代理的配置实例;getDict 缓存按文件路径复用。
7
8
  */
8
- const dict = {};
9
9
 
10
10
  /**
11
- * 配置类
12
- * @class
11
+ * 获取配置缓存字典(可变缓存,存于 mm_vars,键为配置文件全路径)
12
+ * @returns {object} 配置缓存字典
13
13
  */
14
- class Config extends Base {
15
- /**
16
- * 配置选项
17
- * @type {object}
18
- */
19
- static config = {
20
- debounce_time: 0, // 默认不防抖
21
- pretty: true,
22
- format: 'json',
23
- file: ''
24
- };
25
-
26
- /**
27
- * 预设选项
28
- * @type {object}
29
- */
30
- static options = {
31
-
32
- };
33
-
34
- /**
35
- * 创建配置实例
36
- * @param {object} config - 配置选项
37
- * @param {number} config.debounce_time - 防抖时间(ms)
38
- * @param {boolean} config.pretty - 是否美化输出
39
- * @param {string} config.format - 格式(json/json5)
40
- * @param {string} config.file - 配置文件路径
41
- * @param {object} options - 选项
42
- */
43
- constructor(config, options = {}) {
44
- super(config);
45
- this.options = { ...Config.options, ...options };
46
- this._promise = Promise.resolve();
14
+ function getDict() {
15
+ const vars = require('mm_vars').varAdmin('mm_config');
16
+ if (!vars.has('CONF_DICT')) {
17
+ vars.set('CONF_DICT', {});
47
18
  }
19
+ return vars.get('CONF_DICT');
48
20
  }
49
21
 
50
- /**
51
- * 设置配置
52
- * @param {object} options - 配置对象
53
- */
54
- Config.prototype.setOptions = function (options) {
55
- push(this.options, options, true);
56
- };
57
-
58
- /**
59
- * 获取配置
60
- * @returns {object} 配置对象
61
- */
62
- Config.prototype.getOptions = function () {
63
- return this.options;
64
- };
65
-
66
- /**
67
- * 保存配置到文件(同步)
68
- * @returns {boolean} 保存是否成功
69
- */
70
- Config.prototype.saveSync = function () {
71
- if (!this.config.file) return false;
72
- try {
73
- saveJson(this.config.file, this.options);
74
- return true;
75
- } catch (err) {
76
- this.log('error', `Error saving options to ${this.config.file}:`, err.message);
77
- return false;
78
- }
79
- };
80
-
81
- /**
82
- * 保存配置到文件(异步)
83
- * @returns {Promise<boolean>} 保存操作是否成功
84
- */
85
- Config.prototype.saveAsync = async function () {
86
- if (!this.config.file) return Promise.resolve(true);
87
-
88
- // 确保之前的写操作完成
89
- await this._promise;
90
-
91
- this._promise = Promise.resolve()
92
- .then(() => {
93
- saveJson(this.config.file, this.options);
94
- return true;
95
- })
96
- .catch(err => {
97
- this.log('error', `Error saving options to ${this.config.file}:`, err.message);
98
- return false;
99
- });
100
-
101
- return this._promise;
102
- };
103
-
104
- /**
105
- * 获取代理对象
106
- * @returns {Proxy} 配置对象的代理实例
107
- */
108
- Config.prototype.getProxy = function () {
109
- let self = this;
110
-
111
- return new Proxy(this.options, {
112
- set(obj, prop, val) {
113
- obj[prop] = val;
114
-
115
- if (self.config.debounce_time > 0) {
116
- // 防抖处理
117
- if (self._timer) {
118
- clearTimeout(self._timer);
119
- }
120
- self._timer = setTimeout(() => {
121
- self.saveSync();
122
- }, self.config.debounce_time);
123
- } else {
124
- // 无防抖,直接保存
125
- self.saveSync();
126
- }
127
-
128
- return true;
129
- },
130
-
131
- get(obj, prop) {
132
- // 提供一些特殊属性访问
133
- if (prop === '_saveAsync') {
134
- return () => self.saveAsync();
135
- }
136
- if (prop === '_saveSync') {
137
- return () => self.saveSync();
138
- }
139
- if (prop === '_raw') {
140
- return obj;
141
- }
142
-
143
- return obj[prop];
144
- }
145
- });
146
- };
147
-
148
- /**
149
- * 获取异步代理对象
150
- * @returns {Proxy} 异步配置对象的代理实例
151
- */
152
- Config.prototype.getAsyncProxy = function () {
153
- let self = this;
154
-
155
- return new Proxy(this.options, {
156
- set(obj, prop, val) {
157
- obj[prop] = val;
158
-
159
- if (self.config.debounce_time > 0) {
160
- if (self._timer) {
161
- clearTimeout(self._timer);
162
- }
163
- self._timer = setTimeout(() => {
164
- self.saveAsync();
165
- }, self.config.debounce_time);
166
- } else {
167
- self.saveAsync();
168
- }
169
-
170
- return true;
171
- },
172
-
173
- get(obj, prop) {
174
- if (prop === '_saveAsync') {
175
- return () => self.saveAsync();
176
- }
177
- if (prop === '_saveSync') {
178
- return () => self.saveSync();
179
- }
180
- if (prop === '_raw') {
181
- return obj;
182
- }
183
-
184
- return obj[prop];
185
- }
186
- });
187
- };
188
-
189
- /**
190
- * 获取所有配置项
191
- * @returns {object} 所有配置项
192
- */
193
- Config.prototype.all = function () {
194
- return this.options;
195
- };
196
-
197
- /**
198
- * 获取配置值
199
- * @param {string} key - 配置键
200
- * @returns {*} 配置值
201
- */
202
- Config.prototype.get = function (key) {
203
- return this.options[key];
204
- };
205
-
206
- /**
207
- * 获取配置分节
208
- * @param {string} [name] - 分节名称,缺省时返回全部配置
209
- * @returns {object} 配置分节或全部配置
210
- */
211
- Config.prototype.conf = function (name) {
212
- if (name) {
213
- return this.options[name];
214
- }
215
- return this.options;
216
- };
217
-
218
- /**
219
- * 设置配置值
220
- * @param {string} key - 配置键
221
- * @param {*} value - 配置值
222
- */
223
- Config.prototype.set = function (key, value) {
224
- this.options[key] = value;
225
- };
226
-
227
- /**
228
- * 更新配置并保存到文件
229
- * @param {string} [name] - 分节名称,存在时确保该分节存在后保存
230
- * @returns {boolean} 更新是否成功
231
- */
232
- Config.prototype.update = function (name) {
233
- if (name && this.options[name] === undefined) {
234
- this.options[name] = {};
235
- }
236
- return this.saveSync();
237
- };
238
-
239
- /**
240
- * 检查配置是否存在
241
- * @param {string} key - 配置键
242
- * @returns {boolean} 配置项是否存在
243
- */
244
- Config.prototype.has = async function (key) {
245
- return this.options.hasOwnProperty(key);
246
- };
247
-
248
- /**
249
- * 删除配置项
250
- * @param {string} key - 配置键
251
- */
252
- Config.prototype.del = async function (key) {
253
- delete this.options[key];
254
- };
255
-
256
- /**
257
- * 获取所有配置键
258
- * @returns {Array<string>} 配置键列表
259
- */
260
- Config.prototype.keys = async function () {
261
- let keys = [];
262
- let local_keys = Object.keys(this.options);
263
- keys = keys.concat(local_keys);
264
- return keys;
265
- };
266
-
267
- /**
268
- * 销毁
269
- */
270
- Config.prototype.destroy = function () {
271
- delete dict[this.config.file];
272
- };
273
-
274
- /**
275
- * 从配置文件加载配置
276
- * @returns {boolean} 加载是否成功
277
- */
278
- Config.prototype.load = function () {
279
- if (!this.config.file) return false;
280
- this.options = loadJson(this.config.file) || {};
281
- };
282
-
283
22
  /**
284
23
  * 创建配置(同步)
285
24
  * @param {string} file - 配置文件路径
286
- * @param {object} options - 配置对象
287
- * @param {object} config - 配置选项
25
+ * @param {object} [options] - 配置对象
26
+ * @param {object} [config] - 配置选项
288
27
  * @returns {Proxy} 配置代理对象
289
28
  */
290
29
  function create(file, options = {}, config = {}) {
291
30
  let f = fullname(file);
292
- let cfg = new Config({ file: f, ...config }, options);
31
+ let cfg = new ConfigFile({ file: f, ...config }, options);
293
32
  if (!hasFile(file)) {
294
- cfg.saveSync(); // 确保文件存在
33
+ cfg.saveSync();
295
34
  }
296
- // 注册配置字典
297
- dict[f] = cfg;
298
- return dict[f].getProxy();
35
+ getDict()[f] = cfg;
36
+ return cfg.getProxy();
299
37
  }
300
38
 
301
39
  /**
302
40
  * 创建配置(异步)
303
41
  * @param {string} file - 配置文件路径
304
- * @param {object} options - 配置对象
305
- * @param {object} config - 配置选项
42
+ * @param {object} [options] - 配置对象
43
+ * @param {object} [config] - 配置选项
306
44
  * @returns {Promise<Proxy>} 异步配置代理对象
307
45
  */
308
46
  async function createAsync(file, options = {}, config = {}) {
309
47
  let f = fullname(file);
310
- let cfg = new Config({ file: f, ...config }, options);
48
+ let cfg = new ConfigFile({ file: f, ...config }, options);
311
49
  if (!hasFile(file)) {
312
- await cfg.saveAsync(); // 确保文件存在
50
+ await cfg.saveAsync();
313
51
  }
314
- // 注册配置字典
315
- dict[f] = cfg;
316
- return dict[f].getAsyncProxy();
52
+ getDict()[f] = cfg;
53
+ return cfg.getAsyncProxy();
317
54
  }
318
55
 
319
56
  /**
320
57
  * 清理指定文件配置缓存
321
- * @param {string} file - 配置文件路径
58
+ * @param {string} [file] - 配置文件路径,缺省时清理全部
322
59
  * @returns {void}
323
60
  */
324
61
  function clear(file) {
325
62
  if (!file) return clearAll();
326
- let f = fullname(file);
327
- if (dict[f]) {
328
- delete dict[f];
329
- }
63
+ delete getDict()[fullname(file)];
330
64
  }
331
65
 
332
66
  /**
333
67
  * 清理所有配置缓存
68
+ * @returns {void}
334
69
  */
335
70
  function clearAll() {
71
+ let dict = getDict();
336
72
  Object.keys(dict).forEach(key => {
337
73
  delete dict[key];
338
74
  });
@@ -342,7 +78,7 @@ function clearAll() {
342
78
  * 获取配置代理对象
343
79
  * @param {object} options - 配置对象
344
80
  * @param {string} file - 配置文件路径
345
- * @param {object} config - 配置选项
81
+ * @param {object} [config] - 配置选项
346
82
  * @returns {Proxy} 配置代理对象
347
83
  */
348
84
  function conf(options, file, config = {}) {
@@ -350,31 +86,27 @@ function conf(options, file, config = {}) {
350
86
  }
351
87
 
352
88
  /**
353
- * 配置实例单例
354
- * @type {Config|null}
355
- */
356
- let config_instance = null;
357
-
358
- /**
359
- * 获取配置单例
360
- * @param {object} options - 配置对象
361
- * @param {object} config - 配置选项
362
- * @returns {Config} 配置实例
89
+ * 获取配置单例(实例由 mm_admin 实例池管理,避免模块级单例变量)
90
+ * @param {object} [options] - 配置对象
91
+ * @param {object} [config] - 配置选项
92
+ * @returns {ConfigFile} 配置实例
363
93
  */
364
94
  function getConfig(options, config) {
365
- if (!config_instance) {
366
- config_instance = new Config(config, options);
95
+ let admin = reg('config.conf');
96
+ if (!admin.getClass()) {
97
+ admin.setClass(ConfigFile);
98
+ }
99
+ if (!admin.has('default')) {
100
+ admin.set('default', new ConfigFile(config, options));
367
101
  }
368
- return config_instance;
102
+ return admin.get('default');
369
103
  }
370
104
 
371
- // 模块导出
372
105
  module.exports = {
373
- Config,
374
106
  create,
375
107
  createAsync,
376
108
  clear,
377
109
  clearAll,
378
110
  conf,
379
111
  getConfig
380
- };
112
+ };
package/lib/config.js CHANGED
@@ -1,4 +1,88 @@
1
1
  const KvStore = require('mm_kv_store').KvStore;
2
+ require('mm_files');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ /**
7
+ * 判断指定目录是否为 mm_os 项目
8
+ * 模块内部能力:工具不得重复实现,应通过 configAdmin 调用。
9
+ * @param {string} dir_path 待检测目录
10
+ * @returns {boolean} 是否为 mm_os 项目
11
+ */
12
+ function _checkIsMmOs(dir_path) {
13
+ // 检测指标1: index.js中存在 MM_os 或 require('mm_os')
14
+ let index_js_path = path.join(dir_path, 'index.js');
15
+ if (fs.existsSync(index_js_path)) {
16
+ try {
17
+ let content = fs.readFileSync(index_js_path, 'utf-8');
18
+ if (content.includes('MM_os') || content.includes("require('mm_os')") || content.includes('require("mm_os")')) {
19
+ return true;
20
+ }
21
+ } catch {
22
+ // 忽略读取错误
23
+ }
24
+ }
25
+
26
+ // 检测指标2: node_modules/mm_os 存在
27
+ let mm_os_module_path = path.join(dir_path, 'node_modules', 'mm_os');
28
+ if (fs.existsSync(mm_os_module_path)) {
29
+ return true;
30
+ }
31
+
32
+ // 检测指标3: app/ 目录 + config/ 目录同时存在(典型mm_os结构)
33
+ let app_path = path.join(dir_path, 'app');
34
+ let config_path = path.join(dir_path, 'config');
35
+ if (fs.existsSync(app_path) && fs.existsSync(config_path)) {
36
+ // 进一步验证:检查app下是否有多个应用模块目录
37
+ try {
38
+ let apps = fs.readdirSync(app_path);
39
+ let has_app_modules = apps.some(name => {
40
+ let app_dir = path.join(app_path, name);
41
+ return fs.statSync(app_dir).isDirectory() &&
42
+ (fs.existsSync(path.join(app_dir, 'app.json')) || fs.existsSync(path.join(app_dir, 'index.js')));
43
+ });
44
+ if (has_app_modules) {
45
+ return true;
46
+ }
47
+ } catch {
48
+ // 忽略
49
+ }
50
+ }
51
+
52
+ return false;
53
+ }
54
+
55
+ /**
56
+ * 获取 mm_os 版本号
57
+ * @param {string} dir_path 项目根目录
58
+ * @returns {string} mm_os 版本号,取不到时为空串
59
+ */
60
+ function _getMmOsVersion(dir_path) {
61
+ try {
62
+ let pkg_path = path.join(dir_path, 'node_modules', 'mm_os', 'package.json');
63
+ if (fs.existsSync(pkg_path)) {
64
+ let pkg = JSON.parse(fs.readFileSync(pkg_path, 'utf-8'));
65
+ return pkg.version || '';
66
+ }
67
+ } catch {
68
+ // 忽略
69
+ }
70
+ return '';
71
+ }
72
+
73
+ /**
74
+ * 获取 mm_os 项目的关键子目录路径
75
+ * @param {string} dir_path 项目根目录
76
+ * @returns {object} 关键子目录路径表
77
+ */
78
+ function _getProjectPaths(dir_path) {
79
+ return {
80
+ app: path.join(dir_path, 'app'),
81
+ config: path.join(dir_path, 'config'),
82
+ com: path.join(dir_path, 'com'),
83
+ static: path.join(dir_path, 'static')
84
+ };
85
+ }
2
86
 
3
87
  /**
4
88
  * 固定配置存储类,仅允许在系统启动时设置一次,设置后不能修改
@@ -29,6 +113,125 @@ class Config extends KvStore {
29
113
  _isLoadOverwritable() {
30
114
  return false;
31
115
  }
116
+
117
+ /**
118
+ * 获取当前运行根目录及 mm_os 项目信息
119
+ * 工具 get_run_path 通过 configAdmin 调用本方法,自身不重复实现检测逻辑。
120
+ * @param {boolean} check_only 仅返回 is_mm_os 判断,不返回版本与子目录
121
+ * @returns {object} 运行路径信息
122
+ */
123
+ getRunPath(check_only) {
124
+ let run_path = process.cwd() + path.sep;
125
+ let is_mm_os = _checkIsMmOs(run_path);
126
+
127
+ let result = {
128
+ run_path: run_path,
129
+ is_mm_os: is_mm_os,
130
+ code: 0,
131
+ msg: is_mm_os ? '当前为mm_os项目' : '当前不是mm_os项目'
132
+ };
133
+
134
+ if (is_mm_os && !check_only) {
135
+ result.mm_os_version = _getMmOsVersion(run_path);
136
+ result.paths = {};
137
+ for (let [key, dir_path] of Object.entries(_getProjectPaths(run_path))) {
138
+ if (fs.existsSync(dir_path)) {
139
+ result.paths[key] = dir_path;
140
+ }
141
+ }
142
+ }
143
+
144
+ return result;
145
+ }
32
146
  }
33
147
 
34
- module.exports = Config;
148
+ /**
149
+ * 获取配置文件路径(模块内部能力,工具不得重复声明)
150
+ * @param {object} params 步骤参数
151
+ * @param {object} host 调用方宿主(保留工具原有的 this 语义)
152
+ * @returns {string} 配置文件路径
153
+ */
154
+ function _getFilePath(params, host) {
155
+ let opts = (host && host.config && host.config.options) || {};
156
+ let default_path = './config';
157
+ if (
158
+ opts.file_path &&
159
+ typeof opts.file_path === 'object' &&
160
+ opts.file_path.default !== undefined
161
+ ) {
162
+ default_path = opts.file_path.default;
163
+ } else if (opts.file_path) {
164
+ default_path = opts.file_path;
165
+ }
166
+ return params.file_path || default_path;
167
+ }
168
+
169
+ /**
170
+ * 配置读写能力:供 config 工具通过 configAdmin 调用。
171
+ * 工具只负责参数路由,不再在自身文件内声明实现。
172
+ * @param {object} params 步骤参数
173
+ * @param {object} ctx 上下文对象
174
+ * @param {object} host 调用方宿主
175
+ * @returns {object} 操作结果
176
+ */
177
+ Config.prototype.runConfig = function (params, ctx, host) {
178
+ let action = params.action || 'get';
179
+ let key = params.key;
180
+ let value = params.value;
181
+ let scope = params.scope || 'default';
182
+
183
+ let file_path = _getFilePath(params, host);
184
+ // 文件不存在视为首次使用(空配置);存在但解析失败则向上抛错,不吞错降级
185
+ let loaded = {};
186
+ if (fs.existsSync(file_path)) {
187
+ loaded = file_path.loadJson();
188
+ }
189
+ const config = require('./conf.js').create(file_path, loaded);
190
+ let scope_obj = config[scope] || {};
191
+
192
+ switch (action) {
193
+ case 'get':
194
+ ctx.output = { obj: scope_obj[key] };
195
+ break;
196
+ case 'list':
197
+ ctx.output = { list: Object.keys(scope_obj), count: Object.keys(scope_obj).length };
198
+ break;
199
+ case 'values':
200
+ ctx.output = { list: Object.values(scope_obj), count: Object.keys(scope_obj).length };
201
+ break;
202
+ case 'set':
203
+ scope_obj[key] = value;
204
+ config[scope] = scope_obj;
205
+ ctx.output = { msg: '配置设置成功' };
206
+ break;
207
+ case 'update':
208
+ scope_obj[key] = { ...(scope_obj[key] || {}), ...value };
209
+ config[scope] = scope_obj;
210
+ ctx.output = { msg: '配置更新成功' };
211
+ break;
212
+ case 'clear':
213
+ config[scope] = {};
214
+ ctx.output = { msg: '配置清空成功' };
215
+ break;
216
+ case 'del':
217
+ if (key in scope_obj) {
218
+ delete scope_obj[key];
219
+ config[scope] = scope_obj;
220
+ ctx.output = { msg: '配置删除成功' };
221
+ } else {
222
+ ctx.output = { msg: '配置删除失败' };
223
+ }
224
+ break;
225
+ case 'has':
226
+ ctx.output = { obj: key in scope_obj };
227
+ break;
228
+ default:
229
+ ctx.output = {
230
+ error: { code: 'MGR_UNKNOWN_ACTION', message: '不支持的操作: ' + action }
231
+ };
232
+ }
233
+
234
+ return ctx.output;
235
+ };
236
+
237
+ module.exports = Config;