@zhin.js/core 1.1.34 → 1.1.37

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.
Files changed (326) hide show
  1. package/README.md +84 -142
  2. package/lib/built/ai-access.d.ts +36 -0
  3. package/lib/built/ai-access.js +46 -0
  4. package/lib/built/ai-outbound/extensions/onebot-keyboard.d.ts +2 -0
  5. package/lib/built/ai-outbound/extensions/onebot-keyboard.js +67 -0
  6. package/lib/built/ai-outbound/extensions/qq-message.d.ts +3 -0
  7. package/lib/built/ai-outbound/extensions/qq-message.js +23 -0
  8. package/lib/built/ai-outbound/index.d.ts +8 -0
  9. package/lib/built/ai-outbound/index.js +8 -0
  10. package/lib/built/ai-outbound/parse.d.ts +13 -0
  11. package/lib/built/ai-outbound/parse.js +104 -0
  12. package/lib/built/ai-outbound/plain-mention-rewrite.d.ts +6 -0
  13. package/lib/built/ai-outbound/plain-mention-rewrite.js +37 -0
  14. package/lib/built/ai-outbound/prompt.d.ts +11 -0
  15. package/lib/built/ai-outbound/prompt.js +44 -0
  16. package/lib/built/ai-outbound/resolve.d.ts +4 -0
  17. package/lib/built/ai-outbound/resolve.js +64 -0
  18. package/lib/built/ai-outbound/structured-detect.d.ts +3 -0
  19. package/lib/built/ai-outbound/structured-detect.js +6 -0
  20. package/lib/built/ai-outbound/types.d.ts +49 -0
  21. package/lib/built/ai-outbound/types.js +5 -0
  22. package/lib/built/ai-trigger.d.ts +12 -17
  23. package/lib/built/ai-trigger.js +39 -70
  24. package/lib/built/common-adapter-tools.d.ts +33 -29
  25. package/lib/built/common-adapter-tools.js +79 -67
  26. package/lib/built/generated-qrcode.d.ts +24 -0
  27. package/lib/built/generated-qrcode.js +45 -0
  28. package/lib/built/generic-segment-mapper.d.ts +4 -0
  29. package/lib/built/generic-segment-mapper.js +190 -0
  30. package/lib/built/html-segment-fallback.d.ts +2 -5
  31. package/lib/built/html-segment-fallback.js +0 -16
  32. package/lib/built/html-to-text.d.ts +0 -1
  33. package/lib/built/html-to-text.js +15 -15
  34. package/lib/built/interactive-segments/action.d.ts +17 -0
  35. package/lib/built/interactive-segments/action.js +69 -0
  36. package/lib/built/interactive-segments/button-spec.d.ts +10 -0
  37. package/lib/built/interactive-segments/button-spec.js +21 -0
  38. package/lib/built/interactive-segments/index.d.ts +6 -0
  39. package/lib/built/interactive-segments/index.js +6 -0
  40. package/lib/built/interactive-segments/keyboard-segment.d.ts +10 -0
  41. package/lib/built/interactive-segments/keyboard-segment.js +11 -0
  42. package/lib/built/interactive-segments/onebot-keyboard.d.ts +6 -0
  43. package/lib/built/interactive-segments/onebot-keyboard.js +49 -0
  44. package/lib/built/interactive-segments/resolve.d.ts +14 -0
  45. package/lib/built/interactive-segments/resolve.js +109 -0
  46. package/lib/built/interactive-segments/types.d.ts +45 -0
  47. package/lib/built/interactive-segments/types.js +9 -0
  48. package/lib/built/login-assist.d.ts +43 -16
  49. package/lib/built/login-assist.js +113 -11
  50. package/lib/built/message-enrich.d.ts +32 -0
  51. package/lib/built/message-enrich.js +67 -0
  52. package/lib/built/outbound-media-utils.d.ts +9 -0
  53. package/lib/built/outbound-media-utils.js +62 -0
  54. package/lib/built/queue-im-field-contract.d.ts +7 -2
  55. package/lib/built/queue-im-field-contract.js +13 -4
  56. package/lib/built/rich-segments/markdown-to-text.d.ts +3 -0
  57. package/lib/built/rich-segments/markdown-to-text.js +27 -0
  58. package/lib/built/roles.d.ts +4 -5
  59. package/lib/built/roles.js +4 -5
  60. package/lib/built/segment-contract/assert.d.ts +7 -0
  61. package/lib/built/segment-contract/assert.js +39 -0
  62. package/lib/built/segment-contract/delivery.d.ts +5 -0
  63. package/lib/built/segment-contract/delivery.js +40 -0
  64. package/lib/built/segment-contract/image.d.ts +5 -0
  65. package/lib/built/segment-contract/image.js +10 -0
  66. package/lib/built/segment-contract/index.d.ts +10 -0
  67. package/lib/built/segment-contract/index.js +9 -0
  68. package/lib/built/segment-contract/json-schema.d.ts +28 -0
  69. package/lib/built/segment-contract/json-schema.js +128 -0
  70. package/lib/built/segment-contract/media.d.ts +12 -0
  71. package/lib/built/segment-contract/media.js +22 -0
  72. package/lib/built/segment-contract/mention.d.ts +10 -0
  73. package/lib/built/segment-contract/mention.js +26 -0
  74. package/lib/built/segment-contract/preview.d.ts +3 -0
  75. package/lib/built/segment-contract/preview.js +159 -0
  76. package/lib/built/segment-contract/text.d.ts +7 -0
  77. package/lib/built/segment-contract/text.js +34 -0
  78. package/lib/built/segment-contract/types.d.ts +58 -0
  79. package/lib/built/segment-contract/types.js +1 -0
  80. package/lib/built/segment-contract/validate.d.ts +229 -0
  81. package/lib/built/segment-contract/validate.js +172 -0
  82. package/lib/built/tool-access.d.ts +5 -0
  83. package/lib/built/tool-access.js +17 -0
  84. package/lib/built/user-interaction.d.ts +30 -0
  85. package/lib/built/user-interaction.js +244 -0
  86. package/lib/component.d.ts +0 -1
  87. package/lib/component.js +30 -14
  88. package/lib/errors.d.ts +2 -3
  89. package/lib/errors.js +4 -5
  90. package/lib/feature/adapter.d.ts +2 -0
  91. package/lib/feature/adapter.js +2 -0
  92. package/lib/feature/command.d.ts +2 -0
  93. package/lib/feature/command.js +2 -0
  94. package/lib/feature/component.d.ts +2 -0
  95. package/lib/feature/component.js +2 -0
  96. package/lib/feature/handler.d.ts +48 -0
  97. package/lib/feature/handler.js +26 -0
  98. package/lib/feature/middleware.d.ts +2 -0
  99. package/lib/feature/middleware.js +2 -0
  100. package/lib/im-scene.d.ts +29 -0
  101. package/lib/im-scene.js +75 -0
  102. package/lib/im-session-id.d.ts +39 -0
  103. package/lib/im-session-id.js +47 -0
  104. package/lib/index.d.ts +29 -36
  105. package/lib/index.js +27 -41
  106. package/lib/jsx-dev-runtime.d.ts +0 -1
  107. package/lib/jsx-dev-runtime.js +0 -1
  108. package/lib/jsx-runtime.d.ts +1 -1
  109. package/lib/jsx-runtime.js +0 -1
  110. package/lib/jsx.d.ts +19 -22
  111. package/lib/jsx.js +0 -1
  112. package/lib/message.d.ts +17 -12
  113. package/lib/message.js +16 -13
  114. package/lib/models/system-log.d.ts +0 -3
  115. package/lib/models/system-log.js +1 -9
  116. package/lib/models/user.d.ts +0 -3
  117. package/lib/models/user.js +1 -8
  118. package/lib/notice.d.ts +16 -60
  119. package/lib/notice.js +1 -4
  120. package/lib/plugin-runtime/im/contracts.d.ts +191 -0
  121. package/lib/plugin-runtime/im/contracts.js +169 -0
  122. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  123. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  124. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  125. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  126. package/lib/plugin-runtime/im/im-runtime.d.ts +84 -0
  127. package/lib/plugin-runtime/im/im-runtime.js +201 -0
  128. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  129. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  130. package/lib/plugin-runtime/im/index.d.ts +11 -0
  131. package/lib/plugin-runtime/im/index.js +9 -0
  132. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  133. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  134. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  135. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  136. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  137. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  138. package/lib/plugin-runtime/im/login-assist-host.d.ts +6 -0
  139. package/lib/plugin-runtime/im/login-assist-host.js +6 -0
  140. package/lib/plugin-runtime/im/message-bus.d.ts +38 -0
  141. package/lib/plugin-runtime/im/message-bus.js +40 -0
  142. package/lib/plugin-runtime/im/message-dispatcher.d.ts +18 -0
  143. package/lib/plugin-runtime/im/message-dispatcher.js +107 -0
  144. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  145. package/lib/plugin-runtime/im/message-events.js +61 -0
  146. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  147. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  148. package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -0
  149. package/lib/plugin-runtime/im/outbound-renderer.js +70 -0
  150. package/lib/plugin-runtime/im/outbound-segments.d.ts +71 -0
  151. package/lib/plugin-runtime/im/outbound-segments.js +219 -0
  152. package/lib/plugin-runtime/im/public-api.d.ts +6 -0
  153. package/lib/plugin-runtime/im/public-api.js +6 -0
  154. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  155. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  156. package/lib/request.d.ts +17 -62
  157. package/lib/request.js +0 -4
  158. package/lib/side-event/base.d.ts +51 -0
  159. package/lib/side-event/base.js +30 -0
  160. package/lib/side-event/dispatch.d.ts +15 -0
  161. package/lib/side-event/dispatch.js +140 -0
  162. package/lib/side-event/index.d.ts +4 -0
  163. package/lib/side-event/index.js +4 -0
  164. package/lib/side-event/normalize.d.ts +38 -0
  165. package/lib/side-event/normalize.js +111 -0
  166. package/lib/side-event/types.d.ts +23 -0
  167. package/lib/side-event/types.js +55 -0
  168. package/lib/system-event.d.ts +14 -0
  169. package/lib/system-event.js +7 -0
  170. package/lib/types.d.ts +35 -193
  171. package/lib/types.js +0 -1
  172. package/lib/utils.d.ts +81 -6
  173. package/lib/utils.js +54 -25
  174. package/package.json +94 -16
  175. package/lib/adapter.d.ts +0 -96
  176. package/lib/adapter.d.ts.map +0 -1
  177. package/lib/adapter.js +0 -217
  178. package/lib/adapter.js.map +0 -1
  179. package/lib/agent-prompt.d.ts +0 -37
  180. package/lib/agent-prompt.d.ts.map +0 -1
  181. package/lib/agent-prompt.js +0 -2
  182. package/lib/agent-prompt.js.map +0 -1
  183. package/lib/bot.d.ts +0 -38
  184. package/lib/bot.d.ts.map +0 -1
  185. package/lib/bot.js +0 -2
  186. package/lib/bot.js.map +0 -1
  187. package/lib/built/adapter-process.d.ts +0 -43
  188. package/lib/built/adapter-process.d.ts.map +0 -1
  189. package/lib/built/adapter-process.js +0 -81
  190. package/lib/built/adapter-process.js.map +0 -1
  191. package/lib/built/agent-preset.d.ts +0 -65
  192. package/lib/built/agent-preset.d.ts.map +0 -1
  193. package/lib/built/agent-preset.js +0 -80
  194. package/lib/built/agent-preset.js.map +0 -1
  195. package/lib/built/ai-trigger.d.ts.map +0 -1
  196. package/lib/built/ai-trigger.js.map +0 -1
  197. package/lib/built/command.d.ts +0 -68
  198. package/lib/built/command.d.ts.map +0 -1
  199. package/lib/built/command.js +0 -92
  200. package/lib/built/command.js.map +0 -1
  201. package/lib/built/common-adapter-tools.d.ts.map +0 -1
  202. package/lib/built/common-adapter-tools.js.map +0 -1
  203. package/lib/built/component.d.ts +0 -69
  204. package/lib/built/component.d.ts.map +0 -1
  205. package/lib/built/component.js +0 -99
  206. package/lib/built/component.js.map +0 -1
  207. package/lib/built/config.d.ts +0 -99
  208. package/lib/built/config.d.ts.map +0 -1
  209. package/lib/built/config.js +0 -355
  210. package/lib/built/config.js.map +0 -1
  211. package/lib/built/cron.d.ts +0 -75
  212. package/lib/built/cron.d.ts.map +0 -1
  213. package/lib/built/cron.js +0 -122
  214. package/lib/built/cron.js.map +0 -1
  215. package/lib/built/database.d.ts +0 -66
  216. package/lib/built/database.d.ts.map +0 -1
  217. package/lib/built/database.js +0 -100
  218. package/lib/built/database.js.map +0 -1
  219. package/lib/built/dispatcher.d.ts +0 -139
  220. package/lib/built/dispatcher.d.ts.map +0 -1
  221. package/lib/built/dispatcher.js +0 -361
  222. package/lib/built/dispatcher.js.map +0 -1
  223. package/lib/built/html-segment-fallback.d.ts.map +0 -1
  224. package/lib/built/html-segment-fallback.js.map +0 -1
  225. package/lib/built/html-to-text.d.ts.map +0 -1
  226. package/lib/built/html-to-text.js.map +0 -1
  227. package/lib/built/inbound-runner.d.ts +0 -23
  228. package/lib/built/inbound-runner.d.ts.map +0 -1
  229. package/lib/built/inbound-runner.js +0 -37
  230. package/lib/built/inbound-runner.js.map +0 -1
  231. package/lib/built/login-assist.d.ts.map +0 -1
  232. package/lib/built/login-assist.js.map +0 -1
  233. package/lib/built/mcp-mesh-registrar.d.ts +0 -9
  234. package/lib/built/mcp-mesh-registrar.d.ts.map +0 -1
  235. package/lib/built/mcp-mesh-registrar.js +0 -17
  236. package/lib/built/mcp-mesh-registrar.js.map +0 -1
  237. package/lib/built/message-filter.d.ts +0 -177
  238. package/lib/built/message-filter.d.ts.map +0 -1
  239. package/lib/built/message-filter.js +0 -241
  240. package/lib/built/message-filter.js.map +0 -1
  241. package/lib/built/permission.d.ts +0 -55
  242. package/lib/built/permission.d.ts.map +0 -1
  243. package/lib/built/permission.js +0 -112
  244. package/lib/built/permission.js.map +0 -1
  245. package/lib/built/prepend-quote-context.d.ts +0 -35
  246. package/lib/built/prepend-quote-context.d.ts.map +0 -1
  247. package/lib/built/prepend-quote-context.js +0 -131
  248. package/lib/built/prepend-quote-context.js.map +0 -1
  249. package/lib/built/queue-im-field-contract.d.ts.map +0 -1
  250. package/lib/built/queue-im-field-contract.js.map +0 -1
  251. package/lib/built/roles.d.ts.map +0 -1
  252. package/lib/built/roles.js.map +0 -1
  253. package/lib/built/runtime-io.d.ts +0 -10
  254. package/lib/built/runtime-io.d.ts.map +0 -1
  255. package/lib/built/runtime-io.js +0 -68
  256. package/lib/built/runtime-io.js.map +0 -1
  257. package/lib/built/schema-feature.d.ts +0 -78
  258. package/lib/built/schema-feature.d.ts.map +0 -1
  259. package/lib/built/schema-feature.js +0 -132
  260. package/lib/built/schema-feature.js.map +0 -1
  261. package/lib/built/skill.d.ts +0 -121
  262. package/lib/built/skill.d.ts.map +0 -1
  263. package/lib/built/skill.js +0 -152
  264. package/lib/built/skill.js.map +0 -1
  265. package/lib/built/tool.d.ts +0 -150
  266. package/lib/built/tool.d.ts.map +0 -1
  267. package/lib/built/tool.js +0 -383
  268. package/lib/built/tool.js.map +0 -1
  269. package/lib/command.d.ts +0 -42
  270. package/lib/command.d.ts.map +0 -1
  271. package/lib/command.js +0 -75
  272. package/lib/command.js.map +0 -1
  273. package/lib/component.d.ts.map +0 -1
  274. package/lib/component.js.map +0 -1
  275. package/lib/errors.d.ts.map +0 -1
  276. package/lib/errors.js.map +0 -1
  277. package/lib/index.d.ts.map +0 -1
  278. package/lib/index.js.map +0 -1
  279. package/lib/jsx-dev-runtime.d.ts.map +0 -1
  280. package/lib/jsx-dev-runtime.js.map +0 -1
  281. package/lib/jsx-runtime.d.ts.map +0 -1
  282. package/lib/jsx-runtime.js.map +0 -1
  283. package/lib/jsx.d.ts.map +0 -1
  284. package/lib/jsx.js.map +0 -1
  285. package/lib/message-quote.d.ts +0 -11
  286. package/lib/message-quote.d.ts.map +0 -1
  287. package/lib/message-quote.js +0 -91
  288. package/lib/message-quote.js.map +0 -1
  289. package/lib/message.d.ts.map +0 -1
  290. package/lib/message.js.map +0 -1
  291. package/lib/models/system-log.d.ts.map +0 -1
  292. package/lib/models/system-log.js.map +0 -1
  293. package/lib/models/user.d.ts.map +0 -1
  294. package/lib/models/user.js.map +0 -1
  295. package/lib/notice.d.ts.map +0 -1
  296. package/lib/notice.js.map +0 -1
  297. package/lib/plugin.d.ts +0 -258
  298. package/lib/plugin.d.ts.map +0 -1
  299. package/lib/plugin.js +0 -688
  300. package/lib/plugin.js.map +0 -1
  301. package/lib/prompt.d.ts +0 -118
  302. package/lib/prompt.d.ts.map +0 -1
  303. package/lib/prompt.js +0 -244
  304. package/lib/prompt.js.map +0 -1
  305. package/lib/request.d.ts.map +0 -1
  306. package/lib/request.js.map +0 -1
  307. package/lib/scheduler/scheduler.d.ts +0 -49
  308. package/lib/scheduler/scheduler.d.ts.map +0 -1
  309. package/lib/scheduler/scheduler.js +0 -352
  310. package/lib/scheduler/scheduler.js.map +0 -1
  311. package/lib/scheduler/types.d.ts +0 -71
  312. package/lib/scheduler/types.d.ts.map +0 -1
  313. package/lib/scheduler/types.js +0 -8
  314. package/lib/scheduler/types.js.map +0 -1
  315. package/lib/tool-zod.d.ts +0 -28
  316. package/lib/tool-zod.d.ts.map +0 -1
  317. package/lib/tool-zod.js +0 -98
  318. package/lib/tool-zod.js.map +0 -1
  319. package/lib/types-generator.d.ts +0 -6
  320. package/lib/types-generator.d.ts.map +0 -1
  321. package/lib/types-generator.js +0 -72
  322. package/lib/types-generator.js.map +0 -1
  323. package/lib/types.d.ts.map +0 -1
  324. package/lib/types.js.map +0 -1
  325. package/lib/utils.d.ts.map +0 -1
  326. package/lib/utils.js.map +0 -1
package/lib/plugin.js DELETED
@@ -1,688 +0,0 @@
1
- /**
2
- * Plugin 类 — IM 特化插件,继承 PluginBase
3
- *
4
- * 在 PluginBase 的 DI/生命周期/事件基础上增加:
5
- * - Context 类型安全(Plugin.Contexts 映射)
6
- * - 生命周期事件类型安全(Plugin.Lifecycle)
7
- * - 中间件系统、适配器管理、useContext 等
8
- */
9
- import { AsyncLocalStorage } from "node:async_hooks";
10
- import * as fs from "node:fs";
11
- import * as path from "node:path";
12
- import { fileURLToPath, pathToFileURL } from "node:url";
13
- import { formatCompact } from "@zhin.js/logger";
14
- import { compose, remove, resolveEntry } from "./utils.js";
15
- import { Adapter } from "./adapter.js";
16
- import { Feature } from "@zhin.js/kernel";
17
- import { PluginBase, resolvePluginResolveDir as _resolvePluginResolveDir, pluginCreateRequire as _pluginCreateRequire, getFileHash, watchFile, registerExtension, unregisterExtensions, installExtensionProxy, } from "@zhin.js/kernel";
18
- const contextsKey = Symbol("contexts");
19
- function resolvePluginResolveDir(parent) {
20
- return _resolvePluginResolveDir(parent);
21
- }
22
- const loadedModules = new Map();
23
- function pluginCreateRequire() {
24
- return _pluginCreateRequire();
25
- }
26
- // ============================================================================
27
- // AsyncLocalStorage 上下文
28
- // ============================================================================
29
- export const storage = new AsyncLocalStorage();
30
- /**
31
- * 获取当前文件路径(调用者)
32
- */
33
- function getCurrentFile(metaUrl = import.meta.url) {
34
- if (typeof metaUrl !== "string" || metaUrl.length === 0) {
35
- return path.join(process.cwd(), "__zhin_edge_bootstrap__.mjs");
36
- }
37
- const previousPrepareStackTrace = Error.prepareStackTrace;
38
- Error.prepareStackTrace = function (_, stack) {
39
- return stack;
40
- };
41
- const stack = new Error().stack;
42
- Error.prepareStackTrace = previousPrepareStackTrace;
43
- const stackFiles = Array.from(new Set(stack.map((site) => site.getFileName())));
44
- const idx = stackFiles.findIndex((f) => f === fileURLToPath(metaUrl) || f === metaUrl);
45
- const result = stackFiles[idx + 1];
46
- if (!result) {
47
- return path.join(process.cwd(), "__zhin_edge_bootstrap__.mjs");
48
- }
49
- try {
50
- return fileURLToPath(result);
51
- }
52
- catch {
53
- return result;
54
- }
55
- }
56
- /**
57
- * usePlugin - 获取或创建当前插件实例
58
- * 类似 React Hooks 的设计,根据调用文件自动创建插件树
59
- * 同一上下文中同一文件多次调用返回同一实例
60
- */
61
- export function usePlugin() {
62
- const callerFile = getCurrentFile();
63
- // 如果当前 store 已是同一文件创建的插件,直接返回
64
- const current = storage.getStore();
65
- if (current && current.filePath.replace(/\?t=\d+$/, '') === callerFile.replace(/\?t=\d+$/, '')) {
66
- return current;
67
- }
68
- const parentPlugin = current;
69
- const newPlugin = new Plugin(callerFile, parentPlugin);
70
- try {
71
- storage.enterWith(newPlugin);
72
- }
73
- catch {
74
- // Cloudflare Workers 等环境未实现 enterWith;调用方须用 storage.run()
75
- }
76
- return newPlugin;
77
- }
78
- /**
79
- * getPlugin - 获取当前 AsyncLocalStorage 中的插件实例
80
- * 用于 extensions 等场景,不创建新插件
81
- */
82
- export function getPlugin() {
83
- const plugin = storage.getStore();
84
- if (!plugin) {
85
- throw new Error('getPlugin() must be called within a plugin context');
86
- }
87
- return plugin;
88
- }
89
- /**
90
- * Plugin 类 - IM 特化插件,继承 PluginBase
91
- *
92
- * 类型窄化:
93
- * - children: Plugin[] (而非 PluginBase[])
94
- * - parent: Plugin | undefined
95
- * - root: Plugin
96
- * - $contexts: Map<string, Context<any>>
97
- * - dispatch/broadcast: Plugin.Lifecycle 类型安全
98
- */
99
- export class Plugin extends PluginBase {
100
- static [contextsKey] = [];
101
- #cachedName;
102
- #manifest;
103
- adapters = [];
104
- // children/parent 继承 PluginBase 的类型(PluginBase[] / PluginBase | undefined),
105
- // 具体的 Plugin 类型通过 getter/builder 方法按需窄化
106
- get root() {
107
- return super.root;
108
- }
109
- // 插件功能
110
- #messageMiddleware = async (message, next) => {
111
- const commandService = this.inject('command');
112
- if (!commandService)
113
- return await next();
114
- const result = await commandService.handle(message, this);
115
- if (result === undefined || result === null)
116
- return await next();
117
- const adapter = this.inject(message.$adapter);
118
- if (!adapter || !(adapter instanceof Adapter))
119
- return await next();
120
- await message.$reply(result);
121
- };
122
- #middlewares = [this.#messageMiddleware];
123
- // Feature 贡献追踪
124
- #featureContributions = new Map();
125
- // 统一的清理函数集合
126
- #disposables = new Set();
127
- get middleware() {
128
- return compose(this.#middlewares);
129
- }
130
- recordFeatureContribution(featureName, itemName) {
131
- if (!this.#featureContributions.has(featureName)) {
132
- this.#featureContributions.set(featureName, new Set());
133
- }
134
- this.#featureContributions.get(featureName).add(itemName);
135
- }
136
- /**
137
- * 构造函数
138
- */
139
- constructor(filePath = "", parent) {
140
- super(filePath, parent);
141
- // 自动添加到父节点 — PluginBase constructor 已处理,
142
- // 但 PluginBase 使用 PluginBase[],这里需要确保正确
143
- // (super 已调用 parent.children.push(this),类型已通过 declare 窄化)
144
- // 绑定方法以支持解构使用
145
- this.$bindMethods();
146
- }
147
- // 标记是否已绑定方法
148
- #methodsBound = false;
149
- /**
150
- * 添加中间件
151
- * 中间件用于处理消息流转
152
- */
153
- addMiddleware(middleware, name) {
154
- this.#middlewares.push(middleware);
155
- const dispose = () => {
156
- remove(this.#middlewares, middleware);
157
- this.#disposables.delete(dispose);
158
- };
159
- this.#disposables.add(dispose);
160
- return dispose;
161
- }
162
- /**
163
- * 插件名称
164
- */
165
- get name() {
166
- if (this.#cachedName)
167
- return this.#cachedName;
168
- this.#cachedName = path
169
- .relative(process.cwd(), this.filePath)
170
- .replace(/\?t=\d+$/, "")
171
- .replace(/\\/g, "/")
172
- .replace(/\/index\.(js|ts)x?$/, "")
173
- .replace(/\/(lib|src|dist)$/, "")
174
- .replace(/.*\/node_modules\//, "")
175
- .replace(/.*\//, "")
176
- .replace(/\.(js|ts)x?$/, "");
177
- return this.#cachedName;
178
- }
179
- /**
180
- * 插件清单(从 plugin.yml 或 package.json 延迟读取)
181
- */
182
- get manifest() {
183
- if (this.#manifest !== undefined)
184
- return this.#manifest ?? undefined;
185
- if (!this.filePath) {
186
- this.#manifest = null;
187
- return undefined;
188
- }
189
- const dir = path.dirname(this.filePath);
190
- // 优先读取 plugin.yml
191
- const ymlPath = path.join(dir, 'plugin.yml');
192
- if (fs.existsSync(ymlPath)) {
193
- try {
194
- const content = fs.readFileSync(ymlPath, 'utf-8');
195
- const match = content.match(/^name:\s*(.+)$/m);
196
- const descMatch = content.match(/^description:\s*(.+)$/m);
197
- const verMatch = content.match(/^version:\s*(.+)$/m);
198
- if (match) {
199
- this.#manifest = {
200
- name: match[1].trim(),
201
- description: descMatch?.[1]?.trim(),
202
- version: verMatch?.[1]?.trim(),
203
- };
204
- return this.#manifest;
205
- }
206
- }
207
- catch { /* ignore */ }
208
- }
209
- // Fallback: package.json
210
- const pkgPath = path.join(dir, 'package.json');
211
- if (fs.existsSync(pkgPath)) {
212
- try {
213
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
214
- if (pkg.name) {
215
- this.#manifest = {
216
- name: pkg.name,
217
- description: pkg.description,
218
- version: pkg.version,
219
- };
220
- return this.#manifest;
221
- }
222
- }
223
- catch { /* ignore */ }
224
- }
225
- this.#manifest = null;
226
- return undefined;
227
- }
228
- // 根插件类型窄化已在 interface Plugin 声明
229
- /**
230
- * 上下文收集 — 使用类型窄化的 inject 替代直接 Map 访问
231
- */
232
- useContext(...args) {
233
- const contexts = args.slice(0, -1);
234
- const sideEffect = args[args.length - 1];
235
- const contextReadyCallback = async () => {
236
- if (sideEffect.finished)
237
- return;
238
- sideEffect.finished = true;
239
- const args = contexts.map(item => this.inject(item));
240
- const dispose = await sideEffect(...args);
241
- if (!dispose)
242
- return;
243
- const disposeFn = async (name) => {
244
- if (!contexts.includes(name))
245
- return;
246
- await dispose(this.inject(name));
247
- this.off('context.dispose', disposeFn);
248
- sideEffect.finished = false;
249
- };
250
- this.on('context.dispose', disposeFn);
251
- // 确保 dispose 时清理监听器(只注册一次)
252
- const cleanupOnDispose = () => {
253
- this.off('context.dispose', disposeFn);
254
- dispose(this.inject(args[0]));
255
- };
256
- this.once('dispose', cleanupOnDispose);
257
- };
258
- const onContextMounted = async (name) => {
259
- if (!this.#contextsIsReady(contexts) || !(contexts).includes(name))
260
- return;
261
- await contextReadyCallback();
262
- };
263
- this.on('context.mounted', onContextMounted);
264
- // 插件销毁时移除 context.mounted 监听器
265
- this.once('dispose', () => this.off('context.mounted', onContextMounted));
266
- if (!this.#contextsIsReady(contexts))
267
- return;
268
- contextReadyCallback();
269
- }
270
- inject(name) {
271
- const context = this.root.contexts.get(name);
272
- return context?.value;
273
- }
274
- injectAdapter(name) {
275
- const value = this.inject(name);
276
- return value instanceof Adapter ? value : undefined;
277
- }
278
- #contextsIsReady(contexts) {
279
- if (!contexts.length)
280
- return true;
281
- return contexts.every(name => this.contextIsReady(name));
282
- }
283
- contextIsReady(name) {
284
- try {
285
- return !!this.inject(name);
286
- }
287
- catch {
288
- return false;
289
- }
290
- }
291
- // ============================================================================
292
- // 生命周期方法
293
- // ============================================================================
294
- /**
295
- * 启动插件
296
- */
297
- async start(t) {
298
- if (this.started)
299
- return;
300
- // 挂载所有 Context,支持部分失败回滚
301
- const mountedContexts = [];
302
- for (const [name, context] of this.$contexts) {
303
- try {
304
- if (typeof context.mounted === "function") {
305
- const result = await context.mounted(this);
306
- // 仅在没有预设 value 时才用 mounted 返回值赋值
307
- if (!context.value) {
308
- context.value = result;
309
- }
310
- }
311
- // 注册扩展方法到共享 registry
312
- if (context.extensions) {
313
- installExtensionProxy(Plugin.prototype);
314
- for (const [extName, fn] of Object.entries(context.extensions)) {
315
- if (typeof fn === 'function') {
316
- registerExtension(extName, fn);
317
- }
318
- }
319
- }
320
- mountedContexts.push({ name, context });
321
- }
322
- catch (e) {
323
- // 回滚已挂载的 Context(逆序 dispose)
324
- this.logger.warn(`Context "${name}" mount failed: ${e}, rolling back ${mountedContexts.length} mounted contexts`);
325
- for (let i = mountedContexts.length - 1; i >= 0; i--) {
326
- const { name: mName, context: mCtx } = mountedContexts[i];
327
- try {
328
- if (mCtx.extensions) {
329
- unregisterExtensions(Object.keys(mCtx.extensions));
330
- }
331
- if (typeof mCtx.dispose === 'function') {
332
- await mCtx.dispose(mCtx.value);
333
- }
334
- }
335
- catch (disposeErr) {
336
- this.logger.warn(`Rollback dispose for "${mName}" failed: ${disposeErr}`);
337
- }
338
- }
339
- throw e;
340
- }
341
- }
342
- // 所有 Context 成功挂载后,才标记为已启动
343
- this.started = true;
344
- for (const { name } of mountedContexts) {
345
- this.dispatch('context.mounted', name);
346
- }
347
- await this.broadcast("mounted");
348
- // 先启动子插件,再打印当前插件启动日志
349
- for (const child of this.children) {
350
- await child.start(t);
351
- }
352
- if (t) {
353
- this.logger.debug(formatCompact({
354
- name: this.name,
355
- reload_ms: Date.now() - t,
356
- }));
357
- }
358
- }
359
- /**
360
- * 获取插件提供的功能
361
- * 从各个服务中获取数据
362
- */
363
- get features() {
364
- const commandService = this.inject('command');
365
- const componentService = this.inject('component');
366
- const cronService = this.inject('cron');
367
- return {
368
- commands: commandService ? commandService.items.map(c => c.pattern) : [],
369
- components: componentService ? componentService.getAllNames() : [],
370
- crons: cronService ? cronService.items.map(c => c.cronExpression) : [],
371
- middlewares: this.#middlewares.map((m, i) => m.name || `middleware_${i}`),
372
- };
373
- }
374
- /**
375
- * 获取插件功能摘要(数组形式)
376
- * 返回各功能类型的名称和数量
377
- */
378
- getFeatures() {
379
- const result = [];
380
- const f = this.features;
381
- if (f.commands.length > 0)
382
- result.push({ name: 'command', count: f.commands.length });
383
- if (f.components.length > 0)
384
- result.push({ name: 'component', count: f.components.length });
385
- if (f.crons.length > 0)
386
- result.push({ name: 'cron', count: f.crons.length });
387
- // #middlewares includes the default command middleware, only count user-added ones
388
- const userMiddlewareCount = this.#middlewares.length - 1; // subtract default #messageMiddleware
389
- if (userMiddlewareCount > 0)
390
- result.push({ name: 'middleware', count: userMiddlewareCount });
391
- // Tool count is now tracked via ToolFeature, not Plugin#tools
392
- return result;
393
- }
394
- info() {
395
- return {
396
- [this.name]: {
397
- features: this.features,
398
- children: this.children.map(child => child.info())
399
- }
400
- };
401
- }
402
- /**
403
- * 停止插件
404
- */
405
- async stop() {
406
- if (!this.started)
407
- return;
408
- this.logger.debug(`Stopping plugin "${this.name}"`);
409
- this.started = false;
410
- // 停止子插件
411
- for (const child of this.children) {
412
- await child.stop();
413
- }
414
- this.children = [];
415
- // 停止服务
416
- for (const [name, context] of this.$contexts) {
417
- remove(Plugin[contextsKey], name);
418
- // 从共享 registry 注销扩展方法(引用计数,不影响其他提供者)
419
- if (context.extensions) {
420
- unregisterExtensions(Object.keys(context.extensions));
421
- }
422
- if (typeof context.dispose === "function") {
423
- await context.dispose(context.value);
424
- }
425
- }
426
- // 清理 contexts Map
427
- this.$contexts.clear();
428
- // 清空缓存的名称
429
- this.#cachedName = undefined;
430
- // 触发 dispose 事件
431
- this.emit("dispose");
432
- // 执行所有清理函数
433
- for (const dispose of this.#disposables) {
434
- try {
435
- await dispose();
436
- }
437
- catch (e) {
438
- this.logger.warn(`Dispose callback failed: ${e}`);
439
- }
440
- }
441
- this.#disposables.clear();
442
- // 清空 middlewares 数组(保留默认的消息中间件)
443
- this.#middlewares.length = 1;
444
- // 清理 feature 贡献记录
445
- this.#featureContributions.clear();
446
- if (this.parent) {
447
- remove(this.parent?.children, this);
448
- }
449
- // 从全局 loadedModules Map 中移除,防止内存泄漏
450
- if (this.filePath) {
451
- try {
452
- const realPath = fs.realpathSync(this.filePath);
453
- loadedModules.delete(realPath);
454
- }
455
- catch {
456
- // 文件可能已不存在,忽略错误
457
- }
458
- }
459
- this.removeAllListeners();
460
- this.logger.debug(`Plugin "${this.name}" stopped`);
461
- }
462
- // ============================================================================
463
- // 生命周期钩子
464
- // ============================================================================
465
- onMounted(callback) {
466
- this.on("mounted", callback);
467
- }
468
- onDispose(callback) {
469
- this.#disposables.add(callback);
470
- return () => {
471
- this.#disposables.delete(callback);
472
- };
473
- }
474
- // ============================================================================
475
- // 事件广播
476
- // ============================================================================
477
- /**
478
- * dispatch - 向上冒泡到父插件,或者在根节点广播(类型安全版本)
479
- */
480
- async dispatch(name, ...args) {
481
- if (this.parent) {
482
- return this.parent.dispatch(name, ...args);
483
- }
484
- return this.broadcast(name, ...args);
485
- }
486
- /**
487
- * broadcast - 向下广播到所有子插件(类型安全版本)
488
- */
489
- async broadcast(name, ...args) {
490
- const listeners = this.listeners(name);
491
- for (const listener of listeners) {
492
- try {
493
- await listener(...args);
494
- }
495
- catch (e) {
496
- this.logger.warn(`Broadcast "${String(name)}" listener error: ${e}`);
497
- }
498
- }
499
- for (const child of this.children) {
500
- await child.broadcast(name, ...args);
501
- }
502
- }
503
- // ============================================================================
504
- // 依赖注入
505
- // ============================================================================
506
- /**
507
- * 注册上下文(类型安全版本)
508
- */
509
- provide(target) {
510
- if (target instanceof Feature) {
511
- const feature = target;
512
- const ctx = {
513
- name: feature.name,
514
- description: feature.desc,
515
- value: feature,
516
- mounted: feature.mounted
517
- ? async (plugin) => {
518
- await feature.mounted(plugin);
519
- return feature;
520
- }
521
- : undefined,
522
- dispose: feature.dispose
523
- ? async () => { await feature.dispose(); }
524
- : undefined,
525
- extensions: feature.extensions,
526
- };
527
- return this.provide(ctx);
528
- }
529
- const context = target;
530
- if (!Plugin[contextsKey].includes(context.name)) {
531
- Plugin[contextsKey].push(context.name);
532
- }
533
- this.logger.debug(`Context "${context.name}" provided`);
534
- this.$contexts.set(context.name, context);
535
- // 注册扩展方法到共享 registry,确保后续 import 的插件可用
536
- if (context.extensions) {
537
- installExtensionProxy(Plugin.prototype);
538
- for (const [name, fn] of Object.entries(context.extensions)) {
539
- if (typeof fn === 'function') {
540
- registerExtension(name, fn);
541
- }
542
- }
543
- }
544
- return this;
545
- }
546
- // ============================================================================
547
- // 插件加载
548
- // ============================================================================
549
- /**
550
- * 导入插件(Plugin 类型窄化版本)
551
- */
552
- async import(entry, t) {
553
- if (!entry)
554
- throw new Error(`import plugin failed: entry is empty`);
555
- const resolved = resolveEntry(path.isAbsolute(entry) ?
556
- entry :
557
- path.resolve(path.dirname(this.filePath), entry)) || entry;
558
- let realPath;
559
- try {
560
- realPath = fs.realpathSync(resolved);
561
- }
562
- catch {
563
- realPath = resolved;
564
- }
565
- // 避免重复加载同一路径的插件
566
- const normalized = realPath.replace(/\?t=\d+$/, '').replace(/\\/g, '/');
567
- const existing = this.children.find(child => child.filePath.replace(/\?t=\d+$/, '').replace(/\\/g, '/') === normalized);
568
- if (existing) {
569
- this.logger.warn(`Plugin "${entry}" already loaded, skipping...`);
570
- if (this.started && !existing.started)
571
- await existing.start(t);
572
- return existing;
573
- }
574
- const plugin = await Plugin.create(realPath, this);
575
- if (this.started)
576
- await plugin.start(t);
577
- if (process.env.NODE_ENV === 'development') {
578
- plugin.watch((p) => p.reload());
579
- }
580
- return plugin;
581
- }
582
- /**
583
- * 重载插件(Plugin 类型窄化版本)
584
- */
585
- async reload(plugin = this) {
586
- const p = plugin;
587
- this.logger.info(formatCompact({ name: p.name, reload: true }));
588
- const now = Date.now();
589
- if (!p.parent) {
590
- // 根插件重载 = 退出进程(由 CLI 重启)
591
- return process.exit(51);
592
- }
593
- const entry = p.filePath;
594
- const parent = p.parent;
595
- await p.stop();
596
- let fresh;
597
- try {
598
- fresh = await parent.import(entry, now);
599
- }
600
- catch (err) {
601
- this.logger.error(formatCompact({
602
- name: p.name,
603
- reload: false,
604
- error: err instanceof Error ? err.message : String(err),
605
- hint: 'full_restart',
606
- }));
607
- throw err;
608
- }
609
- await fresh.broadcast('mounted');
610
- this.logger.debug(formatCompact({ name: fresh.name, reload_ms: Date.now() - now }));
611
- }
612
- /**
613
- * 监听文件变化(Plugin 类型窄化版本)
614
- */
615
- watch(callback, recursive = false) {
616
- if (!this.filePath || this.filePath.includes("node_modules"))
617
- return;
618
- const unwatch = watchFile(this.filePath, () => {
619
- const newHash = getFileHash(this.filePath);
620
- if (newHash === this.fileHash)
621
- return;
622
- this.logger.debug(`Plugin "${this.name}" file changed, reloading...`);
623
- callback(this);
624
- this.fileHash = newHash;
625
- });
626
- this.on("dispose", unwatch);
627
- if (recursive) {
628
- for (const child of this.children) {
629
- child.watch(callback, recursive);
630
- }
631
- }
632
- }
633
- // ============================================================================
634
- // 辅助方法
635
- // ============================================================================
636
- // 核心方法列表(需要绑定的方法)
637
- static #coreMethods = new Set([
638
- 'addMiddleware', 'useContext', 'inject', 'contextIsReady',
639
- 'start', 'stop', 'onMounted', 'onDispose',
640
- 'dispatch', 'broadcast', 'provide', 'import', 'reload', 'watch', 'info'
641
- ]);
642
- /**
643
- * 自动绑定核心方法(只在构造函数中调用一次)
644
- */
645
- $bindMethods() {
646
- if (this.#methodsBound)
647
- return;
648
- this.#methodsBound = true;
649
- const proto = Object.getPrototypeOf(this);
650
- for (const key of Plugin.#coreMethods) {
651
- const value = proto[key];
652
- if (typeof value === "function") {
653
- this[key] = value.bind(this);
654
- }
655
- }
656
- }
657
- // ============================================================================
658
- // 静态方法
659
- // ============================================================================
660
- /**
661
- * 创建插件实例(异步加载)
662
- */
663
- static async create(entry, parent) {
664
- entry = path.resolve(resolvePluginResolveDir(parent), entry);
665
- const entryFile = fs.existsSync(entry) ? entry : pluginCreateRequire().resolve(entry);
666
- const realPath = fs.realpathSync(entryFile);
667
- // 检查模块是否已加载(跳过热重载后已 stop 的僵尸实例)
668
- const existing = loadedModules.get(realPath);
669
- if (existing?.started) {
670
- return existing;
671
- }
672
- if (existing) {
673
- loadedModules.delete(realPath);
674
- }
675
- const plugin = new Plugin(realPath, parent);
676
- plugin.fileHash = getFileHash(entryFile);
677
- // 先记录,防止循环依赖时重复加载
678
- loadedModules.set(realPath, plugin);
679
- await storage.run(plugin, async () => {
680
- await import(`${pathToFileURL(entryFile).href}?t=${Date.now()}`);
681
- });
682
- return plugin;
683
- }
684
- }
685
- export function defineContext(options) {
686
- return options;
687
- }
688
- //# sourceMappingURL=plugin.js.map