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