doukui 0.8.0 → 0.9.0
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/README.en.md +85 -18
- package/README.md +8 -8
- package/bin/commands/help.js +2 -0
- package/bin/commands/plan-lint.js +105 -0
- package/bin/commands/verify.js +263 -0
- package/bin/doukui.js +2 -0
- package/package.json +1 -1
- package/plugins/core/hook-session-start/index.js +1 -1
- package/plugins/core/hook-skill-gate/index.js +64 -15
- package/plugins/core/hook-skill-gate/plugin.json +1 -1
- package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +7 -28
- package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +5 -177
- package/plugins/core/skill-agent-dispatcher/plugin.json +1 -1
- package/plugins/core/skill-agent-dispatcher/recovery-reference.md +99 -58
- package/plugins/core/skill-agent-dispatcher/roles-reference.md +9 -22
- package/plugins/core/skill-agent-dispatcher/skill.md +112 -524
- package/plugins/core/skill-agentic-loop/mirror-rules.md +15 -3
- package/plugins/core/skill-agentic-loop/plugin.json +1 -1
- package/plugins/core/skill-agentic-loop/skill.md +123 -324
- package/plugins/core/skill-batch-task-creator/plugin.json +1 -1
- package/plugins/core/skill-checklist/skill.md +15 -141
- package/plugins/core/skill-completion-report/plugin.json +1 -1
- package/plugins/core/skill-doukui-plan/plugin.json +1 -1
- package/plugins/core/skill-doukui-plan/skill.md +22 -22
- package/plugins/core/skill-experience-logger/plugin.json +1 -1
- package/plugins/core/skill-human-checkpoint/skill.md +1 -0
- package/plugins/core/skill-split-work-package/plugin.json +1 -1
- package/plugins/core/skill-task-creator/plugin.json +1 -1
- package/plugins/core/skill-task-creator/skill.md +1 -139
- package/plugins/core/skill-workflow-orchestrator/plugin.json +1 -1
- package/plugins/plugin-registry.json +0 -36
- package/plugins/runtime/harness-build.js +5 -5
- package/plugins/runtime/plan-reader.js +21 -3
- package/plugins/runtime/resolve-plugin-path.js +2 -2
- package/plugins/contracts/capabilities.js +0 -268
- package/plugins/core/provider-memory-store/index.js +0 -510
- package/plugins/core/provider-memory-store/plugin.json +0 -9
- package/plugins/core/provider-state-store/index.js +0 -244
- package/plugins/core/provider-state-store/plugin.json +0 -9
- package/plugins/core/provider-watchdog/assets/daemon-config.template.json +0 -32
- package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +0 -676
- package/plugins/core/provider-watchdog/assets/watchdog.js +0 -754
- package/plugins/core/provider-watchdog/index.js +0 -151
- package/plugins/core/provider-watchdog/plugin.json +0 -13
- package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +0 -249
- package/plugins/core/skill-watchdog-manager/plugin.json +0 -10
- package/plugins/core/skill-watchdog-manager/skill.md +0 -143
- package/plugins/core/validator-doc-sync/index.js +0 -248
- package/plugins/core/validator-doc-sync/plugin.json +0 -12
- package/plugins/core/validator-work-package/index.js +0 -300
- package/plugins/core/validator-work-package/plugin.json +0 -12
- package/plugins/runtime/audit-logger.js +0 -311
- package/plugins/runtime/build-cli.js +0 -89
- package/plugins/runtime/event-bus.js +0 -207
- package/plugins/runtime/hook-dispatcher.js +0 -315
- package/plugins/runtime/plugin-loader.js +0 -798
- package/plugins/runtime/plugin-trust.js +0 -182
- package/plugins/runtime/sandbox-context.js +0 -235
- package/plugins/runtime/sandbox-manager.js +0 -609
- package/plugins/runtime/sandbox-worker.js +0 -215
- package/plugins/runtime/text-tokenize.js +0 -24
- package/plugins/runtime/validator-pipeline.js +0 -475
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AuditLogger - JSONL audit log persistence for plugin sandboxing
|
|
3
|
-
*
|
|
4
|
-
* Writes structured audit events to a JSONL (JSON Lines) file.
|
|
5
|
-
* Each line is a complete JSON object representing one audit event.
|
|
6
|
-
*
|
|
7
|
-
* Event types (from design doc section 3.5.2):
|
|
8
|
-
* - sandbox.create — Worker Thread created
|
|
9
|
-
* - sandbox.terminate — Worker Thread terminated
|
|
10
|
-
* - plugin.load — plugin loaded (with capability review)
|
|
11
|
-
* - capability.check — runtime capability check (allow/deny)
|
|
12
|
-
* - capability.violation — plugin attempted undeclared capability
|
|
13
|
-
*
|
|
14
|
-
* File path: ${targetRoot}/.claude/logs/audit-${YYYYMMDD}.jsonl
|
|
15
|
-
*
|
|
16
|
-
* @module audit-logger
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
'use strict';
|
|
20
|
-
|
|
21
|
-
var fs = require('fs');
|
|
22
|
-
var path = require('path');
|
|
23
|
-
var Logger = require('./logger');
|
|
24
|
-
var logger = new Logger();
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* @typedef {object} AuditEntry
|
|
28
|
-
* @property {string} timestamp - ISO 8601 timestamp
|
|
29
|
-
* @property {string} event - event type
|
|
30
|
-
* @property {string} plugin - plugin name
|
|
31
|
-
* @property {string} [sourceType] - plugin source type (core/npm/local)
|
|
32
|
-
* @property {string} [capability] - requested capability (for capability events)
|
|
33
|
-
* @property {string} decision - allow | deny | warn | error
|
|
34
|
-
* @property {string} [detail] - additional detail
|
|
35
|
-
* @property {string} [sessionId] - session identifier for correlation
|
|
36
|
-
*/
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* AuditLogger writes structured audit events to JSONL files.
|
|
40
|
-
* @public
|
|
41
|
-
*/
|
|
42
|
-
class AuditLogger {
|
|
43
|
-
/**
|
|
44
|
-
* @public
|
|
45
|
-
* @param {object} [options]
|
|
46
|
-
* @param {string} [options.logDir] - directory for audit log files (default: .claude/logs under cwd)
|
|
47
|
-
* @param {string} [options.sessionId] - session identifier for correlation
|
|
48
|
-
* @param {object} [options.logger] - optional Logger instance for internal logging
|
|
49
|
-
*/
|
|
50
|
-
constructor(options) {
|
|
51
|
-
options = options || {};
|
|
52
|
-
this._logDir = options.logDir || path.join(process.cwd(), '.claude', 'logs');
|
|
53
|
-
this._sessionId = options.sessionId || '';
|
|
54
|
-
this._logger = options.logger || null;
|
|
55
|
-
this._currentDate = '';
|
|
56
|
-
this._buffer = [];
|
|
57
|
-
this._flushTimer = null;
|
|
58
|
-
this._flushInterval = options.flushInterval || 1000; // 1 second default
|
|
59
|
-
this._maxBufferSize = options.maxBufferSize || 100;
|
|
60
|
-
this._destroyed = false;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// --- Public API ---
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Log an audit event.
|
|
67
|
-
* Events are buffered and flushed periodically or when the buffer is full.
|
|
68
|
-
*
|
|
69
|
-
* @public
|
|
70
|
-
* @param {string} event - event type (sandbox.create, capability.check, etc.)
|
|
71
|
-
* @param {string} plugin - plugin name
|
|
72
|
-
* @param {object} [details] - additional fields to include in the entry
|
|
73
|
-
* @returns {void}
|
|
74
|
-
*/
|
|
75
|
-
log(event, plugin, details) {
|
|
76
|
-
if (this._destroyed) {
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
var entry = {
|
|
81
|
-
timestamp: new Date().toISOString(),
|
|
82
|
-
event: event,
|
|
83
|
-
plugin: plugin,
|
|
84
|
-
decision: (details && details.decision) || 'allow',
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
if (details) {
|
|
88
|
-
if (details.sourceType) entry.sourceType = details.sourceType;
|
|
89
|
-
if (details.capability) entry.capability = details.capability;
|
|
90
|
-
if (details.detail) entry.detail = details.detail;
|
|
91
|
-
if (details.decision) entry.decision = details.decision;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
if (this._sessionId) {
|
|
95
|
-
entry.sessionId = this._sessionId;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
this._buffer.push(entry);
|
|
99
|
-
|
|
100
|
-
// Flush immediately if buffer is full
|
|
101
|
-
if (this._buffer.length >= this._maxBufferSize) {
|
|
102
|
-
this._flush();
|
|
103
|
-
} else if (!this._flushTimer) {
|
|
104
|
-
// Schedule a delayed flush
|
|
105
|
-
var self = this;
|
|
106
|
-
this._flushTimer = setTimeout(function () {
|
|
107
|
-
self._flushTimer = null;
|
|
108
|
-
self._flush();
|
|
109
|
-
}, this._flushInterval);
|
|
110
|
-
// Unref so the timer doesn't keep the process alive
|
|
111
|
-
if (this._flushTimer.unref) {
|
|
112
|
-
this._flushTimer.unref();
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Shorthand for logging a capability check event.
|
|
119
|
-
*
|
|
120
|
-
* @public
|
|
121
|
-
* @param {string} plugin - plugin name
|
|
122
|
-
* @param {string} capability - requested capability
|
|
123
|
-
* @param {string} decision - 'allow' | 'deny' | 'warn' | 'error'
|
|
124
|
-
* @param {string} [detail] - additional detail
|
|
125
|
-
* @param {string} [sourceType] - plugin source type
|
|
126
|
-
*/
|
|
127
|
-
logCapabilityCheck(plugin, capability, decision, detail, sourceType) {
|
|
128
|
-
this.log('capability.check', plugin, {
|
|
129
|
-
capability: capability,
|
|
130
|
-
decision: decision,
|
|
131
|
-
detail: detail || '',
|
|
132
|
-
sourceType: sourceType || '',
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Shorthand for logging a sandbox lifecycle event.
|
|
138
|
-
*
|
|
139
|
-
* @public
|
|
140
|
-
* @param {string} event - 'sandbox.create' | 'sandbox.terminate'
|
|
141
|
-
* @param {string} plugin - plugin name
|
|
142
|
-
* @param {string} [detail] - additional detail (e.g. thread ID, termination reason)
|
|
143
|
-
*/
|
|
144
|
-
logSandboxEvent(event, plugin, detail) {
|
|
145
|
-
this.log(event, plugin, {
|
|
146
|
-
decision: 'allow',
|
|
147
|
-
detail: detail || '',
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Shorthand for logging a plugin load event.
|
|
153
|
-
*
|
|
154
|
-
* @public
|
|
155
|
-
* @param {string} plugin - plugin name
|
|
156
|
-
* @param {string} sourceType - plugin source type
|
|
157
|
-
* @param {string} decision - 'allow' | 'deny'
|
|
158
|
-
* @param {string} [detail] - capability review summary
|
|
159
|
-
*/
|
|
160
|
-
logPluginLoad(plugin, sourceType, decision, detail) {
|
|
161
|
-
this.log('plugin.load', plugin, {
|
|
162
|
-
sourceType: sourceType,
|
|
163
|
-
decision: decision,
|
|
164
|
-
detail: detail || '',
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Force-flush all buffered entries to disk.
|
|
170
|
-
* @public
|
|
171
|
-
*/
|
|
172
|
-
flush() {
|
|
173
|
-
this._flush();
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Destroy the audit logger, flushing any remaining entries.
|
|
178
|
-
* After calling destroy(), no more events can be logged.
|
|
179
|
-
* @public
|
|
180
|
-
*/
|
|
181
|
-
destroy() {
|
|
182
|
-
this._destroyed = true;
|
|
183
|
-
if (this._flushTimer) {
|
|
184
|
-
clearTimeout(this._flushTimer);
|
|
185
|
-
this._flushTimer = null;
|
|
186
|
-
}
|
|
187
|
-
this._flush();
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Query audit log entries from the current day's log file.
|
|
192
|
-
*
|
|
193
|
-
* @public
|
|
194
|
-
* @param {object} [filter]
|
|
195
|
-
* @param {string} [filter.event] - filter by event type
|
|
196
|
-
* @param {string} [filter.plugin] - filter by plugin name
|
|
197
|
-
* @param {string} [filter.decision] - filter by decision
|
|
198
|
-
* @param {number} [filter.limit] - max entries to return
|
|
199
|
-
* @returns {AuditEntry[]}
|
|
200
|
-
*/
|
|
201
|
-
query(filter) {
|
|
202
|
-
filter = filter || {};
|
|
203
|
-
var entries = this._readLogFile();
|
|
204
|
-
var results = entries;
|
|
205
|
-
|
|
206
|
-
if (filter.event) {
|
|
207
|
-
results = results.filter(function (e) { return e.event === filter.event; });
|
|
208
|
-
}
|
|
209
|
-
if (filter.plugin) {
|
|
210
|
-
results = results.filter(function (e) { return e.plugin === filter.plugin; });
|
|
211
|
-
}
|
|
212
|
-
if (filter.decision) {
|
|
213
|
-
results = results.filter(function (e) { return e.decision === filter.decision; });
|
|
214
|
-
}
|
|
215
|
-
if (filter.limit) {
|
|
216
|
-
results = results.slice(-filter.limit);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
return results;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Get the log file path for a given date.
|
|
224
|
-
*
|
|
225
|
-
* @public
|
|
226
|
-
* @param {Date} [date] - date object (default: today)
|
|
227
|
-
* @returns {string} absolute path to the JSONL file
|
|
228
|
-
*/
|
|
229
|
-
getLogFilePath(date) {
|
|
230
|
-
date = date || new Date();
|
|
231
|
-
var dateStr = date.toISOString().slice(0, 10).replace(/-/g, '');
|
|
232
|
-
return path.join(this._logDir, 'audit-' + dateStr + '.jsonl');
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
// --- Internal ---
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* Flush buffered entries to the JSONL file.
|
|
239
|
-
* @private
|
|
240
|
-
*/
|
|
241
|
-
_flush() {
|
|
242
|
-
if (this._buffer.length === 0) return;
|
|
243
|
-
|
|
244
|
-
var entries = this._buffer.splice(0, this._buffer.length);
|
|
245
|
-
|
|
246
|
-
try {
|
|
247
|
-
// Ensure log directory exists
|
|
248
|
-
if (!fs.existsSync(this._logDir)) {
|
|
249
|
-
fs.mkdirSync(this._logDir, { recursive: true });
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
var logPath = this.getLogFilePath();
|
|
253
|
-
var lines = [];
|
|
254
|
-
|
|
255
|
-
for (var i = 0; i < entries.length; i++) {
|
|
256
|
-
lines.push(JSON.stringify(entries[i]));
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
fs.appendFileSync(logPath, lines.join('\n') + '\n', 'utf-8');
|
|
260
|
-
} catch (err) {
|
|
261
|
-
this._internalLog('error', 'Failed to write audit log: ' + err.message);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Read all entries from today's log file.
|
|
267
|
-
* @private
|
|
268
|
-
* @returns {AuditEntry[]}
|
|
269
|
-
*/
|
|
270
|
-
_readLogFile() {
|
|
271
|
-
var logPath = this.getLogFilePath();
|
|
272
|
-
|
|
273
|
-
if (!fs.existsSync(logPath)) {
|
|
274
|
-
return [];
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
try {
|
|
278
|
-
var content = fs.readFileSync(logPath, 'utf-8');
|
|
279
|
-
var lines = content.split('\n').filter(function (line) {
|
|
280
|
-
return line.trim().length > 0;
|
|
281
|
-
});
|
|
282
|
-
|
|
283
|
-
var entries = [];
|
|
284
|
-
for (var i = 0; i < lines.length; i++) {
|
|
285
|
-
try {
|
|
286
|
-
entries.push(JSON.parse(lines[i]));
|
|
287
|
-
} catch (parseErr) {
|
|
288
|
-
// Skip malformed lines
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
return entries;
|
|
292
|
-
} catch (err) {
|
|
293
|
-
this._internalLog('error', 'Failed to read audit log: ' + err.message);
|
|
294
|
-
return [];
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Internal logging helper.
|
|
300
|
-
* @private
|
|
301
|
-
*/
|
|
302
|
-
_internalLog(level, message) {
|
|
303
|
-
if (this._logger && typeof this._logger[level] === 'function') {
|
|
304
|
-
this._logger[level]('audit-logger', message);
|
|
305
|
-
} else {
|
|
306
|
-
logger[level]('audit-logger', message);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
module.exports = AuditLogger;
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* build-cli - CLI entry point for HarnessBuild
|
|
3
|
-
*
|
|
4
|
-
* Provides the command-line interface for building and validating plugins.
|
|
5
|
-
* Separated from harness-build.js to keep CLI concerns isolated from core logic.
|
|
6
|
-
*
|
|
7
|
-
* @module build-cli
|
|
8
|
-
*
|
|
9
|
-
* Usage:
|
|
10
|
-
* node plugins/runtime/build-cli.js # build all plugins
|
|
11
|
-
* node plugins/runtime/build-cli.js --validate # validate only
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
'use strict';
|
|
15
|
-
|
|
16
|
-
var HarnessBuild = require('./harness-build');
|
|
17
|
-
|
|
18
|
-
// ---------------------------------------------------------------------------
|
|
19
|
-
// CLI entry point
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Run the CLI.
|
|
24
|
-
* @public
|
|
25
|
-
* @param {string[]} argv - process.argv
|
|
26
|
-
*/
|
|
27
|
-
function main(argv) {
|
|
28
|
-
var args = argv.slice(2);
|
|
29
|
-
var mode = 'build'; // default mode
|
|
30
|
-
|
|
31
|
-
for (var i = 0; i < args.length; i++) {
|
|
32
|
-
if (args[i] === '--validate') {
|
|
33
|
-
mode = 'validate';
|
|
34
|
-
} else if (args[i] === '--validate-config') {
|
|
35
|
-
mode = 'validate-config';
|
|
36
|
-
} else if (args[i] === '--help' || args[i] === '-h') {
|
|
37
|
-
console.log('Usage: node plugins/runtime/harness-build.js [OPTIONS]');
|
|
38
|
-
console.log('');
|
|
39
|
-
console.log('Options:');
|
|
40
|
-
console.log(' --validate Validate plugin.json files without building');
|
|
41
|
-
console.log(' --validate-config Validate harness-config.yaml file');
|
|
42
|
-
console.log(' --help, -h Show this help message');
|
|
43
|
-
process.exit(0);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
var builder = new HarnessBuild();
|
|
48
|
-
|
|
49
|
-
if (mode === 'validate') {
|
|
50
|
-
var result = builder.validate();
|
|
51
|
-
console.log(result.summary);
|
|
52
|
-
process.exit(result.valid ? 0 : 1);
|
|
53
|
-
} else if (mode === 'validate-config') {
|
|
54
|
-
var configResult = builder.validateConfig();
|
|
55
|
-
console.log(configResult.summary);
|
|
56
|
-
if (!configResult.valid) {
|
|
57
|
-
console.log('');
|
|
58
|
-
console.log('Errors:');
|
|
59
|
-
for (var j = 0; j < configResult.errors.length; j++) {
|
|
60
|
-
console.log(' - ' + configResult.errors[j]);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
if (configResult.warnings.length > 0) {
|
|
64
|
-
console.log('');
|
|
65
|
-
console.log('Warnings:');
|
|
66
|
-
for (var k = 0; k < configResult.warnings.length; k++) {
|
|
67
|
-
console.log(' - ' + configResult.warnings[k]);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
process.exit(configResult.valid ? 0 : 1);
|
|
71
|
-
} else {
|
|
72
|
-
var buildResult = builder.build();
|
|
73
|
-
console.log(buildResult.summary);
|
|
74
|
-
process.exit(buildResult.success ? 0 : 1);
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// ---------------------------------------------------------------------------
|
|
79
|
-
// Module exports
|
|
80
|
-
// ---------------------------------------------------------------------------
|
|
81
|
-
|
|
82
|
-
module.exports = {
|
|
83
|
-
main: main,
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
// Run directly if executed as main
|
|
87
|
-
if (require.main === module) {
|
|
88
|
-
main(process.argv);
|
|
89
|
-
}
|
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* EventBus - Event dispatch system for AI Agent Harness
|
|
3
|
-
*
|
|
4
|
-
* @module event-bus
|
|
5
|
-
*
|
|
6
|
-
* Features:
|
|
7
|
-
* - on(event, handler) register a listener
|
|
8
|
-
* - once(event, handler) one-time listener
|
|
9
|
-
* - off(event, handler) unregister a listener
|
|
10
|
-
* - emit(event, data) dispatch an event
|
|
11
|
-
* - History recording and query for debugging
|
|
12
|
-
* - Subscription objects with unsubscribe() support
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
'use strict';
|
|
16
|
-
|
|
17
|
-
var Logger = require('./logger');
|
|
18
|
-
var logger = new Logger();
|
|
19
|
-
|
|
20
|
-
class EventBus {
|
|
21
|
-
/**
|
|
22
|
-
* @public
|
|
23
|
-
* @param {object} [options]
|
|
24
|
-
* @param {number} [options.maxHistory=100] - max event history entries
|
|
25
|
-
*/
|
|
26
|
-
constructor(options) {
|
|
27
|
-
options = options || {};
|
|
28
|
-
/** @type {Map<string, Set<Function>>} event -> handlers */
|
|
29
|
-
this._handlers = new Map();
|
|
30
|
-
/** @type {object[]} */
|
|
31
|
-
this._history = [];
|
|
32
|
-
/** @type {number} */
|
|
33
|
-
this._maxHistory = options.maxHistory || 100;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// --- public API ---
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Register an event handler.
|
|
40
|
-
* @public
|
|
41
|
-
* @param {string} event - event name
|
|
42
|
-
* @param {Function} handler - callback(eventData)
|
|
43
|
-
* @returns {{ unsubscribe: Function }} subscription handle
|
|
44
|
-
*/
|
|
45
|
-
on(event, handler) {
|
|
46
|
-
if (typeof handler !== 'function') {
|
|
47
|
-
throw new TypeError('EventBus.on(): handler must be a function');
|
|
48
|
-
}
|
|
49
|
-
if (!this._handlers.has(event)) {
|
|
50
|
-
this._handlers.set(event, new Set());
|
|
51
|
-
}
|
|
52
|
-
this._handlers.get(event).add(handler);
|
|
53
|
-
|
|
54
|
-
var self = this;
|
|
55
|
-
var handlers = this._handlers.get(event);
|
|
56
|
-
return {
|
|
57
|
-
unsubscribe: function () {
|
|
58
|
-
handlers.delete(handler);
|
|
59
|
-
if (handlers.size === 0) {
|
|
60
|
-
self._handlers.delete(event);
|
|
61
|
-
}
|
|
62
|
-
},
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Register a one-time event handler. Automatically removed after first invocation.
|
|
68
|
-
* @public
|
|
69
|
-
* @param {string} event
|
|
70
|
-
* @param {Function} handler - callback(eventData)
|
|
71
|
-
* @returns {{ unsubscribe: Function }}
|
|
72
|
-
*/
|
|
73
|
-
once(event, handler) {
|
|
74
|
-
if (typeof handler !== 'function') {
|
|
75
|
-
throw new TypeError('EventBus.once(): handler must be a function');
|
|
76
|
-
}
|
|
77
|
-
var self = this;
|
|
78
|
-
var wrapped = function (data) {
|
|
79
|
-
handler(data);
|
|
80
|
-
innerSub.unsubscribe();
|
|
81
|
-
};
|
|
82
|
-
var innerSub = this.on(event, wrapped);
|
|
83
|
-
return innerSub;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Unregister a specific handler from an event.
|
|
88
|
-
* @public
|
|
89
|
-
* @param {string} event
|
|
90
|
-
* @param {Function} handler - the exact function reference originally passed to on()
|
|
91
|
-
*/
|
|
92
|
-
off(event, handler) {
|
|
93
|
-
var handlers = this._handlers.get(event);
|
|
94
|
-
if (!handlers) return;
|
|
95
|
-
handlers.delete(handler);
|
|
96
|
-
if (handlers.size === 0) {
|
|
97
|
-
this._handlers.delete(event);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Emit an event, calling all registered handlers synchronously.
|
|
103
|
-
* Errors in individual handlers are caught and logged, not propagated.
|
|
104
|
-
* @public
|
|
105
|
-
* @param {string} event
|
|
106
|
-
* @param {*} data
|
|
107
|
-
*/
|
|
108
|
-
emit(event, data) {
|
|
109
|
-
// Record in history
|
|
110
|
-
this._history.push({
|
|
111
|
-
event: event,
|
|
112
|
-
data: data,
|
|
113
|
-
timestamp: Date.now(),
|
|
114
|
-
});
|
|
115
|
-
if (this._history.length > this._maxHistory) {
|
|
116
|
-
this._history.shift();
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Dispatch to handlers
|
|
120
|
-
var handlers = this._handlers.get(event);
|
|
121
|
-
if (!handlers) return;
|
|
122
|
-
|
|
123
|
-
handlers.forEach(function (handler) {
|
|
124
|
-
try {
|
|
125
|
-
handler(data);
|
|
126
|
-
} catch (err) {
|
|
127
|
-
logger.error('event-bus', 'Error in handler for event "' + event + '": ' + err.message);
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Query event history for debugging.
|
|
134
|
-
* @public
|
|
135
|
-
* @param {object} [filter]
|
|
136
|
-
* @param {string} [filter.event] - substring match on event name
|
|
137
|
-
* @param {number} [filter.since] - timestamp lower bound (ms)
|
|
138
|
-
* @param {number} [filter.until] - timestamp upper bound (ms)
|
|
139
|
-
* @param {number} [filter.limit] - max entries to return
|
|
140
|
-
* @returns {object[]}
|
|
141
|
-
*/
|
|
142
|
-
getHistory(filter) {
|
|
143
|
-
filter = filter || {};
|
|
144
|
-
var results = this._history;
|
|
145
|
-
|
|
146
|
-
if (filter.event) {
|
|
147
|
-
var substr = filter.event;
|
|
148
|
-
results = results.filter(function (e) {
|
|
149
|
-
return e.event.indexOf(substr) !== -1;
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
if (filter.since) {
|
|
153
|
-
results = results.filter(function (e) { return e.timestamp >= filter.since; });
|
|
154
|
-
}
|
|
155
|
-
if (filter.until) {
|
|
156
|
-
results = results.filter(function (e) { return e.timestamp <= filter.until; });
|
|
157
|
-
}
|
|
158
|
-
if (filter.limit) {
|
|
159
|
-
results = results.slice(-filter.limit);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
return results;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* Clear all event history.
|
|
167
|
-
* @public
|
|
168
|
-
*/
|
|
169
|
-
clearHistory() {
|
|
170
|
-
this._history = [];
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Remove all handlers for a specific event, or all events.
|
|
175
|
-
* @public
|
|
176
|
-
* @param {string} [event] - if omitted, clears all handlers
|
|
177
|
-
*/
|
|
178
|
-
removeAllListeners(event) {
|
|
179
|
-
if (event) {
|
|
180
|
-
this._handlers.delete(event);
|
|
181
|
-
} else {
|
|
182
|
-
this._handlers.clear();
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
/**
|
|
187
|
-
* Get the number of handlers registered for a given event.
|
|
188
|
-
* @public
|
|
189
|
-
* @param {string} event
|
|
190
|
-
* @returns {number}
|
|
191
|
-
*/
|
|
192
|
-
listenerCount(event) {
|
|
193
|
-
var handlers = this._handlers.get(event);
|
|
194
|
-
return handlers ? handlers.size : 0;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* Getter for event history (for testing compatibility).
|
|
199
|
-
* @internal Use getHistory() for public access
|
|
200
|
-
* @returns {object[]}
|
|
201
|
-
*/
|
|
202
|
-
get events() {
|
|
203
|
-
return this._history;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
module.exports = EventBus;
|