@zhin.js/core 1.1.35 → 1.1.38

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 (197) hide show
  1. package/README.md +79 -193
  2. package/lib/built/ai-outbound/index.d.ts +0 -1
  3. package/lib/built/ai-outbound/index.js +0 -1
  4. package/lib/built/ai-outbound/types.d.ts +0 -9
  5. package/lib/built/ai-trigger.d.ts +0 -5
  6. package/lib/built/ai-trigger.js +1 -27
  7. package/lib/built/common-adapter-tools.d.ts +0 -2
  8. package/lib/built/common-adapter-tools.js +0 -4
  9. package/lib/built/html-segment-fallback.d.ts +2 -5
  10. package/lib/built/html-segment-fallback.js +0 -15
  11. package/lib/built/interactive-segments/index.d.ts +0 -2
  12. package/lib/built/interactive-segments/index.js +0 -2
  13. package/lib/built/interactive-segments/keyboard-segment.d.ts +0 -1
  14. package/lib/built/interactive-segments/keyboard-segment.js +0 -1
  15. package/lib/built/interactive-segments/onebot-keyboard.d.ts +0 -1
  16. package/lib/built/interactive-segments/onebot-keyboard.js +0 -2
  17. package/lib/built/interactive-segments/resolve.d.ts +0 -1
  18. package/lib/built/interactive-segments/resolve.js +0 -1
  19. package/lib/built/interactive-segments/types.d.ts +0 -5
  20. package/lib/built/login-assist.d.ts +1 -8
  21. package/lib/built/message-enrich.d.ts +2 -8
  22. package/lib/built/message-enrich.js +3 -11
  23. package/lib/built/segment-contract/assert.js +2 -1
  24. package/lib/built/segment-contract/delivery.js +1 -0
  25. package/lib/built/segment-contract/index.d.ts +2 -2
  26. package/lib/built/segment-contract/index.js +1 -1
  27. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  28. package/lib/built/segment-contract/json-schema.js +33 -2
  29. package/lib/built/segment-contract/preview.js +7 -0
  30. package/lib/built/segment-contract/types.d.ts +2 -2
  31. package/lib/built/segment-contract/validate.d.ts +43 -2
  32. package/lib/built/segment-contract/validate.js +37 -3
  33. package/lib/built/tool-access.d.ts +5 -0
  34. package/lib/built/tool-access.js +17 -0
  35. package/lib/built/user-interaction.js +0 -4
  36. package/lib/feature/handler.d.ts +1 -5
  37. package/lib/index.d.ts +4 -45
  38. package/lib/index.js +3 -39
  39. package/lib/message.d.ts +1 -2
  40. package/lib/models/system-log.d.ts +0 -2
  41. package/lib/models/system-log.js +1 -8
  42. package/lib/models/user.d.ts +0 -2
  43. package/lib/models/user.js +1 -7
  44. package/lib/notice.d.ts +1 -2
  45. package/lib/plugin-runtime/im/conversation-runtime.d.ts +19 -0
  46. package/lib/plugin-runtime/im/conversation-runtime.js +312 -0
  47. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +79 -0
  48. package/lib/plugin-runtime/im/endpoint-runtime.js +162 -0
  49. package/lib/plugin-runtime/im/im-runtime.d.ts +13 -106
  50. package/lib/plugin-runtime/im/im-runtime.js +58 -1061
  51. package/lib/plugin-runtime/im/inbound-runtime.d.ts +31 -0
  52. package/lib/plugin-runtime/im/inbound-runtime.js +252 -0
  53. package/lib/plugin-runtime/im/index.d.ts +4 -2
  54. package/lib/plugin-runtime/im/index.js +2 -2
  55. package/lib/plugin-runtime/im/ingress-route.d.ts +10 -0
  56. package/lib/plugin-runtime/im/ingress-route.js +10 -0
  57. package/lib/plugin-runtime/im/interaction-runtime.d.ts +23 -0
  58. package/lib/plugin-runtime/im/interaction-runtime.js +181 -0
  59. package/lib/plugin-runtime/im/interactive-router.d.ts +17 -0
  60. package/lib/plugin-runtime/im/interactive-router.js +98 -0
  61. package/lib/plugin-runtime/im/message-bus.d.ts +3 -3
  62. package/lib/plugin-runtime/im/message-bus.js +3 -3
  63. package/lib/plugin-runtime/im/message-events.d.ts +26 -0
  64. package/lib/plugin-runtime/im/message-events.js +61 -0
  65. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +19 -0
  66. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +165 -0
  67. package/lib/plugin-runtime/im/outbound-segments.d.ts +2 -3
  68. package/lib/plugin-runtime/im/outbound-segments.js +3 -4
  69. package/lib/plugin-runtime/im/runtime-middleware.d.ts +3 -0
  70. package/lib/plugin-runtime/im/runtime-middleware.js +13 -0
  71. package/lib/request.d.ts +1 -2
  72. package/lib/side-event/base.d.ts +1 -2
  73. package/lib/side-event/normalize.d.ts +1 -5
  74. package/lib/side-event/normalize.js +1 -11
  75. package/lib/system-event.d.ts +1 -2
  76. package/lib/types.d.ts +9 -116
  77. package/lib/utils.d.ts +51 -24
  78. package/lib/utils.js +11 -23
  79. package/package.json +18 -28
  80. package/lib/adapter.d.ts +0 -145
  81. package/lib/adapter.js +0 -377
  82. package/lib/built/adapter-process.d.ts +0 -58
  83. package/lib/built/adapter-process.js +0 -128
  84. package/lib/built/agent-preset.d.ts +0 -64
  85. package/lib/built/agent-preset.js +0 -79
  86. package/lib/built/ai-outbound/adapter-access.d.ts +0 -3
  87. package/lib/built/ai-outbound/adapter-access.js +0 -9
  88. package/lib/built/authorization.d.ts +0 -10
  89. package/lib/built/authorization.js +0 -76
  90. package/lib/built/command.d.ts +0 -72
  91. package/lib/built/command.js +0 -105
  92. package/lib/built/component.d.ts +0 -67
  93. package/lib/built/component.js +0 -97
  94. package/lib/built/config.d.ts +0 -98
  95. package/lib/built/config.js +0 -372
  96. package/lib/built/connect-endpoint-instance.d.ts +0 -17
  97. package/lib/built/connect-endpoint-instance.js +0 -42
  98. package/lib/built/database.d.ts +0 -68
  99. package/lib/built/database.js +0 -106
  100. package/lib/built/dispatcher.d.ts +0 -141
  101. package/lib/built/dispatcher.js +0 -383
  102. package/lib/built/endpoint-commands.d.ts +0 -3
  103. package/lib/built/endpoint-commands.js +0 -99
  104. package/lib/built/endpoint-lifecycle-service.d.ts +0 -28
  105. package/lib/built/endpoint-lifecycle-service.js +0 -242
  106. package/lib/built/endpoint-lifecycle.d.ts +0 -27
  107. package/lib/built/endpoint-lifecycle.js +0 -36
  108. package/lib/built/endpoint-manager.d.ts +0 -34
  109. package/lib/built/endpoint-manager.js +0 -1
  110. package/lib/built/html-renderer-loader.d.ts +0 -13
  111. package/lib/built/html-renderer-loader.js +0 -33
  112. package/lib/built/inbound-pipeline.d.ts +0 -37
  113. package/lib/built/inbound-pipeline.js +0 -63
  114. package/lib/built/inbound-runner.d.ts +0 -22
  115. package/lib/built/inbound-runner.js +0 -34
  116. package/lib/built/interactive-segment-contract.d.ts +0 -6
  117. package/lib/built/interactive-segment-contract.js +0 -9
  118. package/lib/built/interactive-segments/fallback-store.d.ts +0 -29
  119. package/lib/built/interactive-segments/fallback-store.js +0 -63
  120. package/lib/built/interactive-segments/handlers.d.ts +0 -16
  121. package/lib/built/interactive-segments/handlers.js +0 -74
  122. package/lib/built/introspection-format.d.ts +0 -10
  123. package/lib/built/introspection-format.js +0 -28
  124. package/lib/built/management-command-guard.d.ts +0 -15
  125. package/lib/built/management-command-guard.js +0 -25
  126. package/lib/built/message-filter.d.ts +0 -176
  127. package/lib/built/message-filter.js +0 -239
  128. package/lib/built/optional-peer-import.d.ts +0 -3
  129. package/lib/built/optional-peer-import.js +0 -33
  130. package/lib/built/outbound-media-contract.d.ts +0 -22
  131. package/lib/built/outbound-media-contract.js +0 -10
  132. package/lib/built/permission.d.ts +0 -51
  133. package/lib/built/permission.js +0 -99
  134. package/lib/built/permit-check.d.ts +0 -7
  135. package/lib/built/permit-check.js +0 -35
  136. package/lib/built/permit-parse.d.ts +0 -16
  137. package/lib/built/permit-parse.js +0 -32
  138. package/lib/built/platform-permit.d.ts +0 -20
  139. package/lib/built/platform-permit.js +0 -91
  140. package/lib/built/rich-segments/adapter-policies.d.ts +0 -9
  141. package/lib/built/rich-segments/adapter-policies.js +0 -27
  142. package/lib/built/rich-segments/base.d.ts +0 -11
  143. package/lib/built/rich-segments/base.js +0 -24
  144. package/lib/built/rich-segments/builtins.d.ts +0 -4
  145. package/lib/built/rich-segments/builtins.js +0 -40
  146. package/lib/built/rich-segments/capabilities.d.ts +0 -6
  147. package/lib/built/rich-segments/capabilities.js +0 -38
  148. package/lib/built/rich-segments/html-segment.d.ts +0 -15
  149. package/lib/built/rich-segments/html-segment.js +0 -62
  150. package/lib/built/rich-segments/index.d.ts +0 -13
  151. package/lib/built/rich-segments/index.js +0 -13
  152. package/lib/built/rich-segments/markdown-segment.d.ts +0 -14
  153. package/lib/built/rich-segments/markdown-segment.js +0 -58
  154. package/lib/built/rich-segments/qrcode-segment.d.ts +0 -18
  155. package/lib/built/rich-segments/qrcode-segment.js +0 -73
  156. package/lib/built/rich-segments/registry.d.ts +0 -16
  157. package/lib/built/rich-segments/registry.js +0 -52
  158. package/lib/built/rich-segments/resolve.d.ts +0 -5
  159. package/lib/built/rich-segments/resolve.js +0 -87
  160. package/lib/built/rich-segments/tts-segment.d.ts +0 -13
  161. package/lib/built/rich-segments/tts-segment.js +0 -51
  162. package/lib/built/rich-segments/types.d.ts +0 -79
  163. package/lib/built/rich-segments/types.js +0 -17
  164. package/lib/built/runtime-io.d.ts +0 -9
  165. package/lib/built/runtime-io.js +0 -67
  166. package/lib/built/schedule.d.ts +0 -54
  167. package/lib/built/schedule.js +0 -112
  168. package/lib/built/schema-endpoint-manager.d.ts +0 -17
  169. package/lib/built/schema-endpoint-manager.js +0 -73
  170. package/lib/built/schema-feature.d.ts +0 -77
  171. package/lib/built/schema-feature.js +0 -130
  172. package/lib/built/skill.d.ts +0 -120
  173. package/lib/built/skill.js +0 -151
  174. package/lib/built/speech-loader.d.ts +0 -14
  175. package/lib/built/speech-loader.js +0 -32
  176. package/lib/built/tool.d.ts +0 -151
  177. package/lib/built/tool.js +0 -388
  178. package/lib/command.d.ts +0 -50
  179. package/lib/command.js +0 -106
  180. package/lib/endpoint-capabilities.d.ts +0 -46
  181. package/lib/endpoint-capabilities.js +0 -55
  182. package/lib/endpoint.d.ts +0 -19
  183. package/lib/endpoint.js +0 -3
  184. package/lib/host-plugin-registry.d.ts +0 -8
  185. package/lib/host-plugin-registry.js +0 -12
  186. package/lib/plugin-context.d.ts +0 -27
  187. package/lib/plugin-context.js +0 -64
  188. package/lib/plugin-runtime/im/interactive.d.ts +0 -26
  189. package/lib/plugin-runtime/im/interactive.js +0 -46
  190. package/lib/plugin-runtime/im/service-tokens.d.ts +0 -18
  191. package/lib/plugin-runtime/im/service-tokens.js +0 -13
  192. package/lib/plugin.d.ts +0 -268
  193. package/lib/plugin.js +0 -583
  194. package/lib/schema-interaction.d.ts +0 -117
  195. package/lib/schema-interaction.js +0 -247
  196. package/lib/tool-zod.d.ts +0 -43
  197. package/lib/tool-zod.js +0 -184
@@ -1,372 +0,0 @@
1
- /**
2
- * ConfigFeature
3
- * 配置管理服务,继承自 Feature 抽象类
4
- * 保留原有 ConfigLoader / ConfigService 逻辑,增加 addConfig 扩展
5
- */
6
- import path from "node:path";
7
- import fs from "node:fs";
8
- import { stringify as stringifyYaml, parse as parseYaml, parseDocument } from "yaml";
9
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
10
- import { Feature } from "@zhin.js/kernel";
11
- /** Deno / Node 统一的工作目录(`Deno.chdir` 后应与 `process.cwd()` 一致) */
12
- export function runtimeCwd() {
13
- const g = globalThis;
14
- return g.Deno?.cwd?.() ?? process.cwd();
15
- }
16
- function envLookup(key) {
17
- const g = globalThis;
18
- return g.Deno?.env.get(key) ?? g.process?.env?.[key];
19
- }
20
- // ============================================================================
21
- // ConfigLoader(保持不变)
22
- // ============================================================================
23
- export class ConfigLoader {
24
- filename;
25
- initial;
26
- schema;
27
- #data;
28
- /** `load()` 时解析的绝对路径,避免 proxy `save` 写到 cwd 下错误目录 */
29
- #resolvedPath = '';
30
- get data() {
31
- return this.#proxy(this.#data, this);
32
- }
33
- get raw() {
34
- return this.#data;
35
- }
36
- get extension() {
37
- return path.extname(this.filename).toLowerCase();
38
- }
39
- /** `load()` / `patchKey()` 使用的绝对路径 */
40
- get resolvedPath() {
41
- return this.#resolvedPath || this.resolvePath();
42
- }
43
- constructor(filename, initial, schema) {
44
- this.filename = filename;
45
- this.initial = initial;
46
- this.schema = schema;
47
- this.#data = this.initial;
48
- }
49
- #proxy(data, loader) {
50
- return new Proxy(data, {
51
- get(target, prop, receiver) {
52
- if (typeof prop === 'symbol' || prop === 'constructor' || prop === 'prototype') {
53
- return Reflect.get(target, prop, receiver);
54
- }
55
- const result = Reflect.get(target, prop, receiver);
56
- if (typeof result === 'function') {
57
- return result;
58
- }
59
- if (result instanceof Object && result !== null && typeof result !== 'function') {
60
- return loader.#proxy(result, loader);
61
- }
62
- if (typeof result === 'string') {
63
- if (result.startsWith('\\${') && result.endsWith('}'))
64
- return result.slice(1);
65
- if (/^\$\{(.*)\}$/.test(result)) {
66
- const content = result.slice(2, -1);
67
- // 支持 bash 风格的默认值语法:${VAR:-default} 和 ${VAR:=default}
68
- let key;
69
- let defaultValue;
70
- const bashDefaultMatch = content.match(/^([^:}]+):[-=](.*)$/);
71
- if (bashDefaultMatch) {
72
- // ${VAR:-default} 或 ${VAR:=default}
73
- key = bashDefaultMatch[1];
74
- defaultValue = bashDefaultMatch[2];
75
- }
76
- else {
77
- key = content;
78
- defaultValue = undefined;
79
- }
80
- return envLookup(key) ?? defaultValue ?? loader.initial[key] ?? result;
81
- }
82
- }
83
- return result;
84
- },
85
- set(target, prop, value, receiver) {
86
- const result = Reflect.set(target, prop, value, receiver);
87
- loader.save();
88
- return result;
89
- },
90
- deleteProperty(target, prop) {
91
- const result = Reflect.deleteProperty(target, prop);
92
- loader.save();
93
- return result;
94
- }
95
- });
96
- }
97
- resolvePath(baseDir = runtimeCwd()) {
98
- return path.isAbsolute(this.filename)
99
- ? this.filename
100
- : path.resolve(baseDir, this.filename);
101
- }
102
- load(baseDir) {
103
- const fullPath = baseDir !== undefined
104
- ? this.resolvePath(baseDir)
105
- : (this.#resolvedPath || this.resolvePath());
106
- this.#resolvedPath = fullPath;
107
- if (!fs.existsSync(fullPath)) {
108
- try {
109
- this.save(fullPath);
110
- }
111
- catch {
112
- // Workers 等无 fs.writeFileSync 的环境:使用内存 defaults
113
- const hasDefaults = this.initial != null && typeof this.initial === "object" && Object.keys(this.initial).length > 0;
114
- if (hasDefaults) {
115
- const merged = mergeConfigDefaults(this.initial, {});
116
- this.#data = this.schema ? this.schema(merged) : merged;
117
- return;
118
- }
119
- throw new Error(`Config file missing and cannot create: ${fullPath}`);
120
- }
121
- }
122
- const content = fs.readFileSync(fullPath, "utf-8");
123
- let rawConfig;
124
- switch (this.extension) {
125
- case ".json":
126
- rawConfig = JSON.parse(content);
127
- break;
128
- case ".yaml":
129
- case ".yml":
130
- rawConfig = parseYaml(content);
131
- break;
132
- case ".toml":
133
- rawConfig = parseToml(content);
134
- break;
135
- }
136
- const merged = mergeConfigDefaults(this.initial, rawConfig || {});
137
- if (this.schema) {
138
- this.#data = this.schema(merged);
139
- }
140
- else {
141
- this.#data = merged;
142
- }
143
- }
144
- save(fullPath) {
145
- if (fullPath) {
146
- this.#resolvedPath = fullPath;
147
- }
148
- const target = this.#resolvedPath || this.resolvePath();
149
- if (!target) {
150
- throw new Error('ConfigLoader: call load() before save()');
151
- }
152
- switch (this.extension) {
153
- case ".json":
154
- fs.writeFileSync(target, JSON.stringify(this.#data, null, 2));
155
- break;
156
- case ".yaml":
157
- case ".yml":
158
- fs.writeFileSync(target, stringifyYaml(this.#data));
159
- break;
160
- case ".toml":
161
- fs.writeFileSync(target, stringifyToml(this.#data));
162
- break;
163
- }
164
- }
165
- /**
166
- * 精准修改单个顶层 key 并写回文件
167
- * 保留注释、格式和未修改字段(如 ${VAR} 环境变量引用)
168
- */
169
- patchKey(key, value) {
170
- const fullPath = this.#resolvedPath || this.resolvePath();
171
- switch (this.extension) {
172
- case ".yaml":
173
- case ".yml": {
174
- const content = fs.readFileSync(fullPath, 'utf-8');
175
- const doc = parseDocument(content);
176
- doc.set(key, value);
177
- fs.writeFileSync(fullPath, doc.toString());
178
- break;
179
- }
180
- case ".json": {
181
- const content = fs.readFileSync(fullPath, 'utf-8');
182
- const obj = JSON.parse(content);
183
- obj[key] = value;
184
- fs.writeFileSync(fullPath, JSON.stringify(obj, null, 2));
185
- break;
186
- }
187
- case ".toml": {
188
- const content = fs.readFileSync(fullPath, 'utf-8');
189
- const obj = parseToml(content);
190
- obj[key] = value;
191
- fs.writeFileSync(fullPath, stringifyToml(obj));
192
- break;
193
- }
194
- }
195
- // 同步更新内存
196
- this.#data[key] = value;
197
- }
198
- }
199
- function isPlainObject(value) {
200
- return !!value
201
- && typeof value === 'object'
202
- && !Array.isArray(value)
203
- && Object.getPrototypeOf(value) === Object.prototype;
204
- }
205
- /** 解析 endpoint 配置中的 `${ENV}` 引用(运行时 add 后热连接用) */
206
- export function resolveEndpointConfigEnv(config) {
207
- const out = { ...config };
208
- for (const [key, value] of Object.entries(out)) {
209
- if (typeof value !== 'string')
210
- continue;
211
- const match = value.match(/^\$\{([^}]+)\}$/);
212
- if (!match)
213
- continue;
214
- const envKey = match[1];
215
- const resolved = envLookup(envKey);
216
- if (resolved != null && resolved !== '') {
217
- out[key] = resolved;
218
- }
219
- }
220
- return out;
221
- }
222
- export function mergeConfigDefaults(defaults, overrides) {
223
- if (Array.isArray(defaults)) {
224
- return (Array.isArray(overrides) ? overrides : defaults);
225
- }
226
- if (!isPlainObject(defaults)) {
227
- return (overrides === undefined ? defaults : overrides);
228
- }
229
- if (!isPlainObject(overrides)) {
230
- return defaults;
231
- }
232
- const result = { ...defaults };
233
- for (const [key, value] of Object.entries(overrides)) {
234
- result[key] = key in result
235
- ? mergeConfigDefaults(result[key], value)
236
- : value;
237
- }
238
- return result;
239
- }
240
- (function (ConfigLoader) {
241
- ConfigLoader.supportedExtensions = [".json", ".yaml", ".yml", ".toml"];
242
- /**
243
- * 自动发现配置文件(按优先级:yml > yaml > json > toml)
244
- */
245
- function discover(basename, cwd = runtimeCwd()) {
246
- for (const ext of ['.yml', '.yaml', '.json', '.toml']) {
247
- const filename = `${basename}${ext}`;
248
- if (fs.existsSync(path.resolve(cwd, filename))) {
249
- return filename;
250
- }
251
- }
252
- return null;
253
- }
254
- ConfigLoader.discover = discover;
255
- function load(filename, initial, schema, baseDir) {
256
- const result = new ConfigLoader(filename, initial ?? {}, schema);
257
- result.load(baseDir);
258
- return result;
259
- }
260
- ConfigLoader.load = load;
261
- })(ConfigLoader || (ConfigLoader = {}));
262
- export class ConfigFeature extends Feature {
263
- name = 'config';
264
- icon = 'Settings';
265
- desc = '配置';
266
- /** 内部配置文件管理 */
267
- configs = new Map();
268
- /** 主配置文件名(第一个加载的配置文件) */
269
- #primaryConfigFile = '';
270
- /** 获取主配置文件名 */
271
- get primaryFile() {
272
- return this.#primaryConfigFile;
273
- }
274
- /**
275
- * 加载配置文件
276
- */
277
- load(filename, initial, schema, baseDir) {
278
- const ext = path.extname(filename).toLowerCase();
279
- if (!ConfigLoader.supportedExtensions.includes(ext)) {
280
- throw new Error(`不支持的配置文件格式: ${ext}`);
281
- }
282
- const config = ConfigLoader.load(filename, initial, schema, baseDir);
283
- this.configs.set(filename, config);
284
- if (!this.#primaryConfigFile) {
285
- this.#primaryConfigFile = filename;
286
- }
287
- return config;
288
- }
289
- /**
290
- * 获取配置数据(代理模式,自动保存)
291
- */
292
- get(filename, initial, schema) {
293
- if (!this.configs.has(filename))
294
- this.load(filename, initial, schema);
295
- const config = this.configs.get(filename);
296
- if (!config)
297
- throw new Error(`配置文件 ${filename} 未加载`);
298
- return config.data;
299
- }
300
- /**
301
- * 获取主配置文件数据(第一个加载的配置文件)
302
- */
303
- getPrimary() {
304
- if (!this.#primaryConfigFile)
305
- throw new Error('没有加载任何配置文件');
306
- return this.get(this.#primaryConfigFile);
307
- }
308
- /**
309
- * 获取原始配置数据
310
- */
311
- getRaw(filename, initial, schema) {
312
- if (!this.configs.has(filename))
313
- this.load(filename, initial, schema);
314
- const config = this.configs.get(filename);
315
- if (!config)
316
- throw new Error(`配置文件 ${filename} 未加载`);
317
- return config.raw;
318
- }
319
- /**
320
- * 更新配置文件内容
321
- */
322
- set(filename, data) {
323
- const config = this.configs.get(filename);
324
- if (!config)
325
- throw new Error(`配置文件 ${filename} 未加载`);
326
- Object.assign(config.raw, data);
327
- config.save(path.resolve(runtimeCwd(), filename));
328
- }
329
- /**
330
- * 序列化为 JSON
331
- */
332
- toJSON(pluginName) {
333
- const list = pluginName ? this.getByPlugin(pluginName) : this.items;
334
- return {
335
- name: this.name,
336
- icon: this.icon,
337
- desc: this.desc,
338
- count: list.length,
339
- items: list.map(r => ({
340
- name: r.key,
341
- // 不暴露 defaultValue 以防止泄露密钥/令牌
342
- })),
343
- };
344
- }
345
- /**
346
- * 提供给 Plugin.prototype 的扩展方法
347
- */
348
- get extensions() {
349
- const feature = this;
350
- return {
351
- addConfig(key, defaultValue) {
352
- const plugin = this;
353
- // 尝试写入主配置文件(如果 key 不存在)
354
- if (feature.#primaryConfigFile) {
355
- const config = feature.configs.get(feature.#primaryConfigFile);
356
- if (config) {
357
- const raw = config.raw;
358
- if (!(key in raw)) {
359
- raw[key] = defaultValue;
360
- config.save(path.resolve(runtimeCwd(), feature.#primaryConfigFile));
361
- }
362
- }
363
- }
364
- const record = { key, defaultValue };
365
- const dispose = feature.add(record, plugin.name);
366
- plugin.recordFeatureContribution(feature.name, key);
367
- plugin.onDispose(dispose);
368
- return dispose;
369
- },
370
- };
371
- }
372
- }
@@ -1,17 +0,0 @@
1
- import type { Adapter } from '../adapter.js';
2
- import type { Endpoint } from '../endpoint.js';
3
- import type { Plugin } from '../plugin.js';
4
- import { type EndpointCapabilitiesConfig } from '../endpoint-capabilities.js';
5
- export interface ConnectEndpointInstanceOptions {
6
- plugin: Plugin;
7
- adapter: Adapter;
8
- config: EndpointCapabilitiesConfig & Record<string, unknown>;
9
- }
10
- /**
11
- * 按 Endpoint capabilities 连接或注册单个实例(connectEndpoints 与 Adapter.start 共用)。
12
- */
13
- export declare function connectEndpointInstance(options: ConnectEndpointInstanceOptions): Promise<Endpoint>;
14
- /**
15
- * 按 Endpoint capabilities 断开单个实例。
16
- */
17
- export declare function disconnectEndpointInstance(plugin: Plugin, adapter: Adapter, endpoint: Endpoint): Promise<void>;
@@ -1,42 +0,0 @@
1
- import { assertInbound, getAdapterCapabilities, hasInbound, registerEndpointCapabilities, resolveEndpointCapabilities, } from '../endpoint-capabilities.js';
2
- import { emitEndpointLifecycle } from './endpoint-lifecycle.js';
3
- import { resolveEndpointConfigEnv } from './config.js';
4
- /**
5
- * 按 Endpoint capabilities 连接或注册单个实例(connectEndpoints 与 Adapter.start 共用)。
6
- */
7
- export async function connectEndpointInstance(options) {
8
- const { plugin, adapter, config } = options;
9
- const adapterCaps = getAdapterCapabilities(adapter);
10
- const caps = resolveEndpointCapabilities(adapterCaps, config.capabilities);
11
- const resolvedConfig = resolveEndpointConfigEnv(config);
12
- const endpoint = adapter.createEndpoint(resolvedConfig);
13
- registerEndpointCapabilities(endpoint, caps);
14
- if (caps.includes('inbound')) {
15
- assertInbound(endpoint);
16
- try {
17
- await endpoint.$connect();
18
- await emitEndpointLifecycle(plugin, adapter, endpoint, 'connect');
19
- }
20
- catch (error) {
21
- await emitEndpointLifecycle(plugin, adapter, endpoint, 'error', {
22
- error: error instanceof Error ? error.message : String(error),
23
- phase: 'connect',
24
- });
25
- throw error;
26
- }
27
- }
28
- else {
29
- endpoint.$connected = true;
30
- }
31
- return endpoint;
32
- }
33
- /**
34
- * 按 Endpoint capabilities 断开单个实例。
35
- */
36
- export async function disconnectEndpointInstance(plugin, adapter, endpoint) {
37
- if (!hasInbound(endpoint))
38
- return;
39
- assertInbound(endpoint);
40
- await endpoint.$disconnect();
41
- await emitEndpointLifecycle(plugin, adapter, endpoint, 'disconnect');
42
- }
@@ -1,68 +0,0 @@
1
- /**
2
- * DatabaseFeature
3
- * 数据库服务,管理数据模型定义,继承自 Feature 抽象类
4
- */
5
- import { Definition, Database } from "@zhin.js/database";
6
- import { DatabaseConfig, Models } from "../types.js";
7
- import { Feature, FeatureJSON, type PluginLike } from '@zhin.js/kernel';
8
- /**
9
- * 模型定义记录
10
- */
11
- export interface ModelRecord {
12
- name: string;
13
- definition: Definition<any>;
14
- }
15
- declare module "../plugin.js" {
16
- namespace Plugin {
17
- interface Extensions {
18
- defineModel<K extends keyof Models>(name: K, definition: Definition<Models[K]>): void;
19
- }
20
- interface Contexts {
21
- database: DatabaseFeature;
22
- }
23
- }
24
- }
25
- type DatabaseAfterStartHook = (db: Database<any, Models, any>) => void | Promise<void>;
26
- /** 在 `db.start()` 完成之后、`context.mounted` 发出之前执行(用于 schema 迁移) */
27
- export declare function onDatabaseAfterStart(hook: DatabaseAfterStartHook): void;
28
- export declare class DatabaseFeature extends Feature<ModelRecord> {
29
- readonly name: "database";
30
- readonly icon = "Database";
31
- readonly desc = "\u6570\u636E\u6A21\u578B";
32
- /** 内部数据库实例 */
33
- readonly db: Database<any, Models, any>;
34
- /** 按模型名索引 */
35
- readonly byName: Map<string, ModelRecord>;
36
- constructor(config: DatabaseConfig);
37
- get models(): Database.Models<Models, any, any>;
38
- define<K extends keyof Models>(name: K, definition: Definition<Models[K]>): void;
39
- start(): Promise<void>;
40
- stop(): Promise<void>;
41
- /**
42
- * 添加模型定义
43
- */
44
- add(record: ModelRecord, pluginName: string): () => void;
45
- /**
46
- * 移除模型定义
47
- */
48
- remove(record: ModelRecord): boolean;
49
- /**
50
- * 生命周期: 启动数据库
51
- */
52
- mounted(plugin: PluginLike): Promise<void>;
53
- /**
54
- * 生命周期: 停止数据库
55
- */
56
- dispose(): Promise<void>;
57
- /**
58
- * 序列化为 JSON
59
- */
60
- toJSON(pluginName?: string): FeatureJSON;
61
- /**
62
- * 提供给 Plugin.prototype 的扩展方法
63
- */
64
- get extensions(): {
65
- defineModel<K extends keyof Models>(name: K, definition: Definition<Models[K]>): void;
66
- };
67
- }
68
- export {};
@@ -1,106 +0,0 @@
1
- /**
2
- * DatabaseFeature
3
- * 数据库服务,管理数据模型定义,继承自 Feature 抽象类
4
- */
5
- import { Registry } from "@zhin.js/database";
6
- import { formatCompact } from '@zhin.js/logger';
7
- import { Feature } from '@zhin.js/kernel';
8
- import { SystemLogDefinition } from "../models/system-log.js";
9
- import { UserDefinition } from "../models/user.js";
10
- const databaseAfterStartHooks = [];
11
- /** 在 `db.start()` 完成之后、`context.mounted` 发出之前执行(用于 schema 迁移) */
12
- export function onDatabaseAfterStart(hook) {
13
- databaseAfterStartHooks.push(hook);
14
- }
15
- export class DatabaseFeature extends Feature {
16
- name = 'database';
17
- icon = 'Database';
18
- desc = '数据模型';
19
- /** 内部数据库实例 */
20
- db;
21
- /** 按模型名索引 */
22
- byName = new Map();
23
- constructor(config) {
24
- super();
25
- this.db = Registry.create(config.dialect, config, {
26
- SystemLog: SystemLogDefinition,
27
- User: UserDefinition,
28
- });
29
- }
30
- // ====================================================================
31
- // 向后兼容代理:旧代码 inject('database').xxx 可直接使用
32
- // ====================================================================
33
- get models() {
34
- return this.db.models;
35
- }
36
- define(name, definition) {
37
- return this.db.define(name, definition);
38
- }
39
- start() {
40
- return this.db.start();
41
- }
42
- stop() {
43
- return this.db.stop();
44
- }
45
- /**
46
- * 添加模型定义
47
- */
48
- add(record, pluginName) {
49
- this.db.define(record.name, record.definition);
50
- this.byName.set(record.name, record);
51
- return super.add(record, pluginName);
52
- }
53
- /**
54
- * 移除模型定义
55
- */
56
- remove(record) {
57
- this.byName.delete(record.name);
58
- return super.remove(record);
59
- }
60
- /**
61
- * 生命周期: 启动数据库
62
- */
63
- async mounted(plugin) {
64
- plugin.logger.debug(formatCompact({ ready: true }));
65
- await this.db.start();
66
- for (const hook of databaseAfterStartHooks) {
67
- await hook(this.db);
68
- }
69
- }
70
- /**
71
- * 生命周期: 停止数据库
72
- */
73
- async dispose() {
74
- await this.db.stop();
75
- }
76
- /**
77
- * 序列化为 JSON
78
- */
79
- toJSON(pluginName) {
80
- const list = pluginName ? this.getByPlugin(pluginName) : this.items;
81
- return {
82
- name: this.name,
83
- icon: this.icon,
84
- desc: this.desc,
85
- count: list.length,
86
- items: list.map(r => ({
87
- name: r.name,
88
- })),
89
- };
90
- }
91
- /**
92
- * 提供给 Plugin.prototype 的扩展方法
93
- */
94
- get extensions() {
95
- const feature = this;
96
- return {
97
- defineModel(name, definition) {
98
- const plugin = this;
99
- const record = { name: name, definition };
100
- const dispose = feature.add(record, plugin.name);
101
- plugin.recordFeatureContribution(feature.name, name);
102
- plugin.onDispose(dispose);
103
- },
104
- };
105
- }
106
- }