mm_scanner 3.0.0 → 5.0.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/lib/scanner.js CHANGED
@@ -2,512 +2,405 @@
2
2
 
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
- const { watcherAdmin, admin: watcher_admin } = require('mm_watcher');
6
- const { normalizeKey, normalizeExt, buildCacheKey, createItem } = require('./path_util');
7
- const { DEFAULT_CONFIG } = require('./scanner_config');
8
- const { walkDir } = require('./fs_util');
9
- const { diffItems } = require('./diff_util');
10
- const cache_store = require('./cache_store');
11
-
12
- /* 监听事件防抖窗口,与 mm_watcher 默认值一致 */
13
- const WATCH_DEBOUNCE = 100;
5
+ let { normalizeKey, createItem } = require('./path_util');
6
+ let { diffItems } = require('./diff_util');
7
+ let { typeStore, clearTypeStores } = require('./type_store');
14
8
 
15
9
  /**
16
10
  * 目录扫描器
17
- * @description 按扩展名递归扫描目录并缓存文件元信息,支持按 key、扩展名、目录检索,
18
- * 支持通过 watcherAdmin 共享监听器实现文件变化热更新,
19
- * 每个实例自行维护扫描结果并写回共享缓存
11
+ * @description 按 Loader 的资源类型表递归扫描目录,扫描时即完成分类,
12
+ * 并按「一类一个 Store」写入 mm_store(作用域为资源类型名);
13
+ * 支持 apply 接收监听变更做增量更新,目录监听由调用方(mm_loader)负责
20
14
  */
21
15
  class Scanner {
22
16
  /**
23
17
  * 扫描器默认配置
24
18
  */
25
- static config = DEFAULT_CONFIG;
19
+ static config = {
20
+ /** 资源类型表,键为类型名,值为 { ext };扫描结果按类型分别写入 mm_store */
21
+ resources: {},
22
+ /** 忽略的目录 */
23
+ ignore: ['.git', '.svn', '.hg', 'node_modules', '.idea', '.vscode']
24
+ };
26
25
 
27
- /** key(含扩展名) -> { key, absPath, relPath, dir, name, ext } */
28
- #files = new Map();
26
+ /** 扫描根目录绝对路径 */
29
27
  #base_dir = null;
30
28
  #scanned = false;
31
- /** 本次遍历过的目录,用于缓存有效性校验 */
32
- #dirs = [];
33
- /** 本次扫描对应的缓存键 */
34
- #cache_key = null;
35
- /** 本实例使用的共享监听器(watcherAdmin 按缓存键缓存) */
36
- #watcher = null;
37
- /** 本实例注册到监听器上的事件处理器,未监听时为 null */
38
- #handlers = null;
39
- /** 外部变更回调集合(同作用域同目录共用一个实例,允许多方同时订阅) */
40
- #callbacks = new Set();
29
+ /** 配置变化后需重新分类 */
30
+ #stale = false;
41
31
 
42
32
  /**
43
33
  * 创建扫描器实例
44
- * @param {{ extensions?: string[], ignore?: string[], use_scope?: string }} [config] - 扫描器配置
34
+ * @param {{ resources?: object, ignore?: string[] }} [config] - 扫描器配置
45
35
  */
46
36
  constructor(config = {}) {
47
37
  this.config = {
48
- extensions: [...Scanner.config.extensions],
38
+ resources: { ...Scanner.config.resources },
49
39
  ignore: [...Scanner.config.ignore],
50
- use_scope: Scanner.config.use_scope,
51
40
  };
52
41
  this.setConfig(config);
53
42
  }
54
43
 
55
44
  /**
56
45
  * 设置扫描配置
57
- * @description 逐项校验并合并进当前配置:extensions 仅接受非空数组并补点转小写后整体替换,
58
- * ignore 仅接受数组并按并集追加(默认忽略目录始终生效),
59
- * use_scope 仅接受非空字符串;非法或缺省项保留当前配置
60
- * @param {{ extensions?: string[], ignore?: string[], use_scope?: string }} [config] - 扫描器配置
46
+ * @description resources 浅合并(新增类型或后缀变化时标记需重扫),
47
+ * ignore 按并集追加(默认忽略目录始终生效)
48
+ * @param {{ resources?: object, ignore?: string[] }} [config] - 扫描器配置
61
49
  * @returns {void}
62
50
  */
63
51
  setConfig(config = {}) {
64
- if (Array.isArray(config.extensions) && config.extensions.length) {
65
- this.config.extensions = config.extensions.map(normalizeExt);
66
- }
67
- if (Array.isArray(config.ignore)) {
68
- this.config.ignore = [...new Set([...this.config.ignore, ...config.ignore])];
69
- }
70
- if (typeof config.use_scope === 'string' && config.use_scope) {
71
- this.config.use_scope = config.use_scope;
72
- }
52
+ this.#mergeResources(config.resources);
53
+ this.#mergeIgnore(config.ignore);
73
54
  }
74
55
 
75
56
  /* -------- 私有 -------- */
76
57
 
77
58
  /**
78
- * 用缓存条目填充扫描结果
79
- * @param {Array<object>} items 缓存中的条目
80
- * @param {Array<string>} dirs 缓存中的目录列表
59
+ * 合并资源类型表
60
+ * @param {object} [resources] 资源类型表
81
61
  * @returns {void}
62
+ * @private
82
63
  */
83
- #fill(items, dirs) {
84
- this.#files.clear();
85
- for (const item of items) {
86
- this.#files.set(item.key, { ...item });
64
+ #mergeResources(resources) {
65
+ if (!resources || typeof resources !== 'object' || Array.isArray(resources)) return;
66
+ let merged = { ...this.config.resources };
67
+ for (let type of Object.keys(resources)) {
68
+ let ext = resources[type] && resources[type].ext;
69
+ if (typeof ext !== 'string' || !ext) continue;
70
+ merged[type] = { ext: ext.toLowerCase() };
87
71
  }
88
- this.#dirs = [...dirs];
89
- this.#scanned = true;
72
+ if (this.#sameResources(merged)) return;
73
+ this.config.resources = merged;
74
+ if (this.#scanned) this.#stale = true;
90
75
  }
91
76
 
92
77
  /**
93
- * 遍历根目录并填充扫描结果
94
- * @returns {void}
78
+ * 判断资源类型表是否与当前配置等价
79
+ * @param {object} resources 待比较的资源类型表
80
+ * @returns {boolean} 等价返回 true
81
+ * @private
95
82
  */
96
- #walkAndFill() {
97
- this.#files.clear();
98
- this.#dirs = [];
99
- walkDir(this.#base_dir, this.#base_dir, this.config, this.#files, this.#dirs);
100
- this.#scanned = true;
83
+ #sameResources(resources) {
84
+ let current = this.config.resources;
85
+ let keys = Object.keys(resources);
86
+ if (keys.length !== Object.keys(current).length) return false;
87
+ for (let type of keys) {
88
+ if (current[type].ext !== resources[type].ext) return false;
89
+ }
90
+ return true;
101
91
  }
102
92
 
103
93
  /**
104
- * 构造写入缓存的内容
105
- * @returns {{ dir: string, extensions: Array<string>, ignore: Array<string>, items: Array<object>, dirs: Array<string> }} 缓存内容
94
+ * 合并忽略目录
95
+ * @param {string[]} [ignore] 忽略目录列表
96
+ * @returns {void}
97
+ * @private
106
98
  */
107
- #snapshot() {
108
- return {
109
- dir: this.#base_dir,
110
- extensions: this.config.extensions,
111
- ignore: this.config.ignore,
112
- items: [...this.#files.values()],
113
- dirs: this.#dirs,
114
- };
99
+ #mergeIgnore(ignore) {
100
+ if (!Array.isArray(ignore)) return;
101
+ let merged = [...new Set([...this.config.ignore, ...ignore])];
102
+ if (merged.length === this.config.ignore.length) return;
103
+ this.config.ignore = merged;
104
+ if (this.#scanned) this.#stale = true;
115
105
  }
116
106
 
117
- #ensureReady() {
118
- if (!this.#scanned) {
119
- throw new Error('[scanner] 尚未初始化,请先在入口调用 scanner.scan(dir)');
120
- }
121
- }
122
-
123
- /** 宽松解析 key:精确命中 → 按扩展名顺序尝试补全 */
124
- #resolveKey(input) {
125
- const norm = normalizeKey(input);
126
- if (this.#files.has(norm)) return norm;
127
-
128
- for (const ext of this.config.extensions) {
129
- const try_key = norm + ext;
130
- if (this.#files.has(try_key)) return try_key;
107
+ /**
108
+ * 按资源类型表对文件名分类
109
+ * @param {string} name 文件名
110
+ * @returns {string} 资源类型,未命中返回空字符串
111
+ * @private
112
+ */
113
+ #typeOf(name) {
114
+ let file = String(name).toLowerCase();
115
+ let list = this.config.resources;
116
+ for (let type in list) {
117
+ if (file.endsWith(list[type].ext)) return type;
131
118
  }
132
- return null;
119
+ return '';
133
120
  }
134
121
 
135
122
  /**
136
- * 判断文件的相对目录是否命中目标目录
137
- * @param {string} dir_path - 文件所在相对目录
138
- * @param {string} dir_key - 规范化后的目标目录
139
- * @returns {boolean} 命中返回 true,目标目录为空时视为全部命中
123
+ * 遍历根目录并完成分类
124
+ * @returns {Map<string, object>} 文件绝对路径 -> 条目
125
+ * @private
140
126
  */
141
- #matchDir(dir_path, dir_key) {
142
- if (!dir_key) return true;
143
- if (dir_key.includes('/')) {
144
- return dir_path === dir_key || dir_path.endsWith('/' + dir_key);
145
- }
146
- return dir_path.split('/').includes(dir_key);
127
+ #walk() {
128
+ let entries = new Map();
129
+ this.#walkDir(this.#base_dir, entries);
130
+ this.#scanned = true;
131
+ this.#stale = false;
132
+ return entries;
147
133
  }
148
134
 
149
135
  /**
150
- * 写入扫描缓存
151
- * @description 超出缓存上限时先整体清空(含解绑监听),再写入当前键
136
+ * 递归遍历目录并收集命中类型的文件
137
+ * @param {string} dir 当前目录绝对路径
138
+ * @param {Map<string, object>} entries 条目收集容器
152
139
  * @returns {void}
140
+ * @private
153
141
  */
154
- #writeCache() {
155
- if (cache_store.isOverflow(this.#cache_key)) {
156
- Scanner.clearCache();
142
+ #walkDir(dir, entries) {
143
+ let list = fs.readdirSync(dir, { withFileTypes: true });
144
+ for (let entry of list) {
145
+ let full_path = path.join(dir, entry.name);
146
+ if (entry.isDirectory()) {
147
+ if (this.config.ignore.includes(entry.name)) continue;
148
+ this.#walkDir(full_path, entries);
149
+ continue;
150
+ }
151
+ if (!entry.isFile()) continue;
152
+ let type = this.#typeOf(entry.name);
153
+ if (!type) continue;
154
+ let item = createItem(type, this.#base_dir, full_path);
155
+ entries.set(item.file, item);
157
156
  }
158
- cache_store.setCache(this.#cache_key, this.#snapshot());
159
157
  }
160
158
 
161
159
  /**
162
- * 标记缓存进入监听状态并清空时间戳校验记录
160
+ * 把遍历结果按类型同步到 Store
161
+ * @description 同一 Store 可能被多个扫描根目录共用,只同步本 root 的条目;
162
+ * 已存在时跳过,保留 loader 写入的 config
163
+ * @param {Map<string, object>} entries 本次遍历结果
163
164
  * @returns {void}
165
+ * @private
164
166
  */
165
- #markWatched() {
166
- const cache = cache_store.readCache(this.#cache_key);
167
- if (!cache) return;
168
- cache.watched = true;
169
- cache.dir_mtimes = [];
170
- cache.file_mtimes = [];
167
+ #sync(entries) {
168
+ let groups = new Map();
169
+ for (let item of entries.values()) {
170
+ let list = groups.get(item.type);
171
+ if (list) list.push(item);
172
+ else groups.set(item.type, [item]);
173
+ }
174
+ for (let type of Object.keys(this.config.resources)) {
175
+ let store = typeStore(type);
176
+ let list = groups.get(type) || [];
177
+ let keep = new Set(list.map((one) => one.file));
178
+ for (let old of store.list({ root: this.#base_dir })) {
179
+ if (!keep.has(old.file)) store.delById(old.file);
180
+ }
181
+ for (let item of list) {
182
+ if (!store.getById(item.file)) store.add(item);
183
+ }
184
+ }
171
185
  }
172
186
 
173
187
  /**
174
- * 解除缓存监听标记并重建时间戳校验记录
175
- * @returns {void}
188
+ * 读取本实例扫描根下的全部条目
189
+ * @description Store 是唯一数据源,按类型取本 root 切片
190
+ * @returns {Array<object>} 条目数组
191
+ * @private
176
192
  */
177
- #markUnwatched() {
178
- const cache = cache_store.readCache(this.#cache_key);
179
- if (!cache) return;
180
- cache.watched = false;
181
- cache_store.captureMtimes(cache);
193
+ #entries() {
194
+ let list = [];
195
+ for (let type of Object.keys(this.config.resources)) {
196
+ for (let item of typeStore(type).list({ root: this.#base_dir })) list.push(item);
197
+ }
198
+ return list;
182
199
  }
183
200
 
184
- /**
185
- * 摘除本实例注册到监听器上的全部事件处理器
186
- * @returns {void}
187
- */
188
- #detachHandlers() {
189
- if (this.#watcher && this.#handlers) {
190
- this.#watcher.off('add', this.#handlers.add);
191
- this.#watcher.off('set', this.#handlers.set);
192
- this.#watcher.off('del', this.#handlers.del);
193
- this.#watcher.off('reload', this.#handlers.reload);
201
+ #ensureReady() {
202
+ if (!this.#scanned) {
203
+ throw new Error('[scanner] 尚未初始化,请先在入口调用 scanner.scan(dir)');
194
204
  }
195
- this.#handlers = null;
196
- this.#watcher = null;
197
205
  }
198
206
 
199
207
  /**
200
- * 判断相对路径是否为本实例关心的文件
201
- * @description 目录段命中本实例忽略配置或扩展名不在白名单内均视为不关心;
202
- * 共享监听器只按目录监听,配置过滤统一由实例自行完成
208
+ * 取相对路径对应的资源类型
203
209
  * @param {string} rel_path 规范化后的相对路径
204
- * @returns {boolean} 本实例关心返回 true
210
+ * @returns {string} 资源类型,忽略目录下或未命中类型返回空字符串
211
+ * @private
205
212
  */
206
- #isConcerned(rel_path) {
207
- const parts = rel_path.split('/');
213
+ #typeOfRel(rel_path) {
214
+ let parts = rel_path.split('/');
208
215
  for (let i = 0; i < parts.length - 1; i++) {
209
- if (this.config.ignore.includes(parts[i])) return false;
216
+ if (this.config.ignore.includes(parts[i])) return '';
210
217
  }
211
- const ext = path.extname(parts[parts.length - 1]).toLowerCase();
212
- return this.config.extensions.includes(ext);
218
+ return this.#typeOf(parts[parts.length - 1]);
213
219
  }
214
220
 
215
221
  /**
216
- * 处理文件新增或修改事件:更新本实例条目、写回缓存并通知回调
217
- * @description 本实例忽略目录与白名单外的扩展名直接丢弃;
218
- * stat 失败时按删除处理;条目已存在视为 change,否则视为 add
222
+ * 规划文件新增或修改
223
+ * @description 不关心的路径丢弃;stat 失败或不是文件按删除处理;
224
+ * Store 中已有条目视为 change,否则视为 add
219
225
  * @param {string} rel_path 相对路径
220
- * @returns {void}
226
+ * @returns {object|false|null} 变更条目;false 表示需全量重建;null 表示不关心
227
+ * @private
221
228
  */
222
- #onFileEvent(rel_path) {
223
- const key = normalizeKey(rel_path);
224
- if (!this.#isConcerned(key)) return;
225
-
226
- const abs_path = path.join(this.#base_dir, key);
227
- const item = createItem(this.#base_dir, abs_path);
228
-
229
- let stat = null;
230
- try {
231
- stat = fs.statSync(abs_path);
232
- } catch {
233
- stat = null;
234
- }
229
+ #planAdd(rel_path) {
230
+ let key = normalizeKey(rel_path);
231
+ let type = this.#typeOfRel(key);
232
+ if (!type) return null;
233
+
234
+ let abs_path = path.join(this.#base_dir, key);
235
+ let stat = fs.statSync(abs_path, { throwIfNoEntry: false });
235
236
  if (!stat || !stat.isFile()) {
236
- this.#onDelEvent(rel_path);
237
- return;
237
+ return this.#planDel(rel_path);
238
238
  }
239
- const type = this.#files.has(item.key) ? 'change' : 'add';
240
- this.#files.set(item.key, item);
241
- this.#writeCache();
242
- this.#notify([{ type, key: item.key, item }]);
243
- }
244
239
 
245
- /**
246
- * 处理文件删除事件:移除本实例条目、写回缓存并通知回调
247
- * @description 本实例不关心的路径(忽略目录、白名单外扩展名)直接丢弃;
248
- * 关心的路径未命中条目时无法精确增量,退化为全量重建兜底
249
- * @param {string} rel_path 相对路径
250
- * @returns {void}
251
- */
252
- #onDelEvent(rel_path) {
253
- const key = normalizeKey(rel_path);
254
- if (!this.#isConcerned(key)) return;
255
-
256
- const old = this.#files.get(key);
257
- if (!old) {
258
- this.#onReloadEvent();
259
- return;
260
- }
261
- this.#files.delete(key);
262
- this.#writeCache();
263
- this.#notify([{ type: 'unlink', key, item: old }]);
240
+ let item = createItem(type, this.#base_dir, abs_path);
241
+ let old = typeStore(type).getById(item.file);
242
+ return { type: old ? 'change' : 'add', key: item.file, item };
264
243
  }
265
244
 
266
245
  /**
267
- * 处理目录级重载事件:全量重扫本实例并以差异通知回调
268
- * @returns {void}
246
+ * 规划文件删除
247
+ * @description 不关心的路径丢弃;Store 未命中时无法精确增量,需全量重建兜底
248
+ * @param {string} rel_path 相对路径
249
+ * @returns {object|false|null} 变更条目;false 表示需全量重建;null 表示不关心
250
+ * @private
269
251
  */
270
- #onReloadEvent() {
271
- const before = [...this.#files.values()];
272
- this.#walkAndFill();
273
- this.#writeCache();
274
- this.#notify(diffItems(before, this.getAll()));
252
+ #planDel(rel_path) {
253
+ let key = normalizeKey(rel_path);
254
+ let type = this.#typeOfRel(key);
255
+ if (!type) return null;
256
+
257
+ let file = path.join(this.#base_dir, key);
258
+ let old = typeStore(type).getById(file);
259
+ if (!old) return false;
260
+ return { type: 'unlink', key: file, item: old };
275
261
  }
276
262
 
277
263
  /**
278
- * 把变更列表交给外部回调
279
- * @param {Array<{ type: string, key: string, item: object }>} changes 变更列表,type 为 add/change/unlink
264
+ * 提交单条变更到 Store
265
+ * @param {{ type: string, key: string, item: object }} change 变更条目
280
266
  * @returns {void}
267
+ * @private
281
268
  */
282
- #notify(changes) {
283
- if (!this.#callbacks.size || !changes.length) return;
284
- for (const callback of this.#callbacks) {
285
- try {
286
- callback(changes.map((one) => ({ ...one, item: { ...one.item } })));
287
- } catch (error) {
288
- console.error('[scanner] watch 回调执行失败:', error);
289
- }
269
+ #commit(change) {
270
+ let store = typeStore(change.item.type);
271
+ if (change.type === 'unlink') {
272
+ store.delById(change.key);
273
+ } else if (change.type === 'change') {
274
+ store.setById(change.key, change.item);
275
+ } else {
276
+ store.add(change.item);
290
277
  }
291
278
  }
292
279
 
293
- /**
294
- * 判断文件是否命中指定类型
295
- * 只写扩展名('.json' / 'json')按扩展名匹配,写文件名('event.json')按文件名结尾匹配
296
- * @param {{ key: string, ext: string }} file - 文件条目
297
- * @param {string} ext - 扩展名或文件名
298
- * @returns {boolean} 命中返回 true
299
- */
300
- #matchExt(file, ext) {
301
- const norm = String(ext).trim().toLowerCase();
302
- const bare = norm.replace(/^\./, '');
303
- if (!bare.includes('.')) return file.ext === '.' + bare;
304
- return file.key === bare || file.key.endsWith('/' + bare);
305
- }
306
-
307
280
  /* -------- 公开 API -------- */
308
281
 
309
282
  /**
310
283
  * 扫描目录(重复调用只生效一次)
311
- * @description 优先复用其他实例的扫描缓存,命中时不再遍历目录
312
- * @param {string} dir
313
- * @param {{ extensions?: string[], ignore?: string[] }} [options]
284
+ * @description 已扫描时目录不同仅告警;配置变化(resources/ignore)会重新分类
285
+ * @param {string} dir 目录路径
286
+ * @param {{ resources?: object, ignore?: string[] }} [options] 扫描配置
287
+ * @returns {Scanner} 当前实例
314
288
  */
315
- scan = (dir, options = {}) => {
316
- const resolved = path.resolve(dir);
289
+ scan(dir, options = {}) {
290
+ let resolved = path.resolve(dir);
317
291
 
318
292
  if (this.#scanned) {
319
293
  if (this.#base_dir !== resolved) {
320
294
  console.warn(`[scanner] 已使用 ${this.#base_dir} 扫描过,忽略本次 scan(${resolved})`);
295
+ return this;
296
+ }
297
+ this.setConfig(options);
298
+ if (this.#stale) {
299
+ this.#sync(this.#walk());
321
300
  }
322
301
  return this;
323
302
  }
324
303
 
325
- if (!fs.existsSync(resolved)) throw new Error(`[scanner] 目录不存在: ${resolved}`);
326
- if (!fs.statSync(resolved).isDirectory()) throw new Error(`[scanner] 不是目录: ${resolved}`);
304
+ let stat = fs.statSync(resolved, { throwIfNoEntry: false });
305
+ if (!stat) throw new Error(`[scanner] 目录不存在: ${resolved}`);
306
+ if (!stat.isDirectory()) throw new Error(`[scanner] 不是目录: ${resolved}`);
327
307
 
328
308
  this.setConfig(options);
329
-
330
309
  this.#base_dir = resolved;
331
- this.#cache_key = buildCacheKey(resolved, this.config.extensions, this.config.ignore);
332
-
333
- const cache = cache_store.getCache(this.#cache_key);
334
- if (cache) {
335
- this.#fill(cache.items, cache.dirs);
336
- return this;
337
- }
338
-
339
- this.#walkAndFill();
340
- this.#writeCache();
310
+ this.#sync(this.#walk());
341
311
  return this;
342
- };
343
-
344
- /** 拿条目元信息(含 absPath),key 可带可不带扩展名 */
345
- get = (key) => {
346
- this.#ensureReady();
347
- const k = this.#resolveKey(key);
348
- return k ? this.#files.get(k) : undefined;
349
- };
350
-
351
- /** 拿绝对路径(给 Loader 用的最常见接口) */
352
- getPath = (key) => {
353
- const info = this.get(key);
354
- return info ? info.absPath : undefined;
355
- };
356
-
357
- has = (key) => {
358
- this.#ensureReady();
359
- return this.#resolveKey(key) !== null;
360
- };
312
+ }
361
313
 
362
- keys = () => {
314
+ /**
315
+ * 接收目录监听变更并增量更新扫描结果
316
+ * @description change.type 为 add/set/del/reload,path 为相对扫描根目录的路径;
317
+ * reload、空路径或非法条目触发全量重建;不关心的路径直接丢弃;
318
+ * 未命中的删除无法精确增量,同样退化为全量重建;
319
+ * 先规划再提交,重建时无需提前读取全量条目
320
+ * @param {Array<{ type: string, path: string }>} changes 监听变更
321
+ * @returns {Array<{ type: string, key: string, item: object }>} 标准化变更,type 为 add/change/unlink
322
+ */
323
+ apply(changes) {
363
324
  this.#ensureReady();
364
- return [...this.#files.keys()];
365
- };
366
325
 
367
- getAll = () => {
368
- this.#ensureReady();
369
- return [...this.#files.values()];
370
- };
326
+ let rebuild = changes.some((one) => {
327
+ let type = one.type;
328
+ return type === 'reload' || !one.path || (type !== 'add' && type !== 'set' && type !== 'del');
329
+ });
371
330
 
372
- /** 按"扩展名类型"筛:getByExt('.json') / getByExt('json') 都行 */
373
- getByExt = (ext) => {
374
- this.#ensureReady();
375
- const e = normalizeExt(ext);
376
- return this.getAll().filter((f) => f.ext === e);
377
- };
331
+ let planned = [];
332
+ if (!rebuild) {
333
+ for (let one of changes) {
334
+ let change = one.type === 'del' ? this.#planDel(one.path) : this.#planAdd(one.path);
335
+ if (change === null) continue;
336
+ if (change === false) {
337
+ rebuild = true;
338
+ break;
339
+ }
340
+ planned.push(change);
341
+ }
342
+ }
378
343
 
379
- /** 所有出现过的扩展名类型 */
380
- extTypes = () => {
381
- this.#ensureReady();
382
- const set = new Set();
383
- for (const f of this.#files.values()) set.add(f.ext);
384
- return [...set];
385
- };
344
+ if (rebuild) {
345
+ let before = this.#entries();
346
+ let entries = this.#walk();
347
+ this.#sync(entries);
348
+ return diffItems(before, [...entries.values()]);
349
+ }
386
350
 
387
- /** 按目录筛:getByDir('config') -> data/config/**.{json,yaml,...} */
388
- getByDir = (dir) => {
389
- this.#ensureReady();
390
- const norm = normalizeKey(dir);
391
- const prefix = norm ? norm + '/' : '';
392
- return this.getAll().filter((f) => f.key.startsWith(prefix));
393
- };
351
+ for (let change of planned) this.#commit(change);
352
+ return planned;
353
+ }
394
354
 
395
355
  /**
396
- * 按目录名与文件类型筛选文件
397
- * 目录参数可为目录名(匹配任意层级)或相对路径(匹配路径结尾)
398
- * @param {string} dir - 目录名或相对目录,如 'event_api'、'ai/event_api'
399
- * @param {string} ext - 扩展名或文件名,如 '.json'、'event.json'
400
- * @returns {Array<{ key: string, absPath: string, relPath: string, dir: string, name: string, ext: string }>} 命中的文件条目
356
+ * 全部扫描条目
357
+ * @returns {Array<object>} 条目数组
401
358
  */
402
- getFileByDir = (dir, ext) => {
403
- this.#ensureReady();
404
- const dir_key = normalizeKey(dir);
405
- return this.getAll().filter((f) => this.#matchDir(f.dir, dir_key) && this.#matchExt(f, ext));
406
- };
407
-
408
- /** 所有一级子目录名(可当作业务分类) */
409
- dirTypes = () => {
359
+ getAll() {
410
360
  this.#ensureReady();
411
- const set = new Set();
412
- for (const f of this.#files.values()) {
413
- const first = f.dir.split('/')[0];
414
- if (first) set.add(first);
415
- }
416
- return [...set];
417
- };
418
-
419
- /** 当前支持的扩展名列表 */
420
- get extensions() { return [...this.config.extensions]; }
361
+ return this.#entries();
362
+ }
421
363
 
422
364
  /**
423
365
  * 重新扫描(开发环境热更新用)
424
- * @description 只重建本实例的扫描结果并写回缓存、触发本实例回调;
425
- * 其他实例不受通知,其监听会随真实文件事件自行收敛
366
+ * @description 强制遍历本实例目录并同步各类型 Store
426
367
  * @returns {Scanner} 当前实例
427
368
  */
428
- rescan = () => {
369
+ rescan() {
429
370
  if (!this.#base_dir) throw new Error('[scanner] 尚未初始化,无法 rescan');
430
- const before = [...this.#files.values()];
431
- this.#walkAndFill();
432
- this.#writeCache();
433
- this.#notify(diffItems(before, this.getAll()));
371
+ this.#sync(this.#walk());
434
372
  return this;
435
- };
373
+ }
436
374
 
437
375
  /**
438
- * 开启文件监听,文件增删改时更新本实例扫描结果、写回缓存并触发回调
439
- * @description 共享监听器按 config.use_scope 经 watcherAdmin 取用(实例键为 use_scope@目录),
440
- * 同作用域同目录多实例复用同一底层句柄;
441
- * 监听器只声明监听哪个目录,忽略目录与扩展名白名单由本实例在事件处理中自行过滤;
442
- * 重复调用只追加回调(共享实例可被多方订阅);不支持递归监听的环境会静默降级
443
- * @param {(changes: Array<{ type: string, key: string, item: object }>) => void} [callback] 变更回调,type 为 add/change/unlink
444
- * @returns {Scanner} 当前实例
376
+ * 清空本模块写入的类型 Store
377
+ * @returns {void}
445
378
  */
446
- watch = (callback) => {
447
- this.#ensureReady();
448
- if (typeof callback === 'function') this.#callbacks.add(callback);
449
- if (this.watching) return this;
450
- if (this.#handlers) this.#detachHandlers();
451
-
452
- const watcher = watcherAdmin(this.config.use_scope, {
453
- target: this.#base_dir,
454
- debounce: WATCH_DEBOUNCE,
455
- });
456
- this.#watcher = watcher;
457
- this.#handlers = {
458
- add: (rel_path) => this.#onFileEvent(rel_path),
459
- set: (rel_path) => this.#onFileEvent(rel_path),
460
- del: (rel_path) => this.#onDelEvent(rel_path),
461
- reload: () => this.#onReloadEvent(),
462
- };
463
- watcher.on('add', this.#handlers.add);
464
- watcher.on('set', this.#handlers.set);
465
- watcher.on('del', this.#handlers.del);
466
- watcher.on('reload', this.#handlers.reload);
467
-
468
- if (!watcher.listen()) {
469
- this.#detachHandlers();
470
- return this;
471
- }
472
- this.#markWatched();
473
- return this;
474
- };
379
+ static clearCache() {
380
+ clearTypeStores();
381
+ }
475
382
 
476
383
  /**
477
- * 关闭本实例的变更回调与事件订阅
478
- * @description 传回调只摘除该回调,仍有其他订阅者时继续监听(共享实例的常见场景);
479
- * 无参摘除全部回调并释放本实例的事件处理器;
480
- * 共享监听器保留,统一由 Scanner.clearCache() 释放全部监听器
481
- * @param {Function} [callback] 此前注册过的变更回调
482
- * @returns {Scanner} 当前实例
384
+ * 已扫描条目总数
385
+ * @description 按本实例目录下各资源类型的 Store 条目计数累加
386
+ * @returns {number} 条目总数
483
387
  */
484
- unwatch = (callback) => {
485
- if (typeof callback === 'function') {
486
- this.#callbacks.delete(callback);
487
- } else {
488
- this.#callbacks.clear();
388
+ get size() {
389
+ if (!this.#scanned) return 0;
390
+ let total = 0;
391
+ for (let type of Object.keys(this.config.resources)) {
392
+ total += typeStore(type).count({ root: this.#base_dir });
489
393
  }
490
- if (this.#callbacks.size) return this;
491
- this.#detachHandlers();
492
- this.#markUnwatched();
493
- return this;
494
- };
394
+ return total;
395
+ }
495
396
 
496
397
  /**
497
- * 释放全部共享监听器并清空扫描缓存
498
- * @returns {void}
398
+ * 获取本实例绑定的扫描根目录
399
+ * @returns {string} 扫描根目录绝对路径
499
400
  */
500
- static clearCache = () => {
501
- for (const watcher of watcher_admin.maps.values()) {
502
- watcher.dispose();
503
- }
504
- cache_store.clear();
505
- };
506
-
507
- get size() { return this.#files.size; }
508
- get baseDir() { return this.#base_dir; }
509
- /** 当前实例是否处于监听状态 */
510
- get watching() { return !!(this.#handlers && this.#watcher && this.#watcher.active); }
401
+ get baseDir() {
402
+ return this.#base_dir;
403
+ }
511
404
  }
512
405
 
513
406
  /* 导出类 */