@chatbi-v/core 2.0.1 → 2.0.2

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/dist/index.cjs DELETED
@@ -1,2521 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __commonJS = (cb, mod) => function __require() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
- };
14
- var __export = (target, all) => {
15
- for (var name in all)
16
- __defProp(target, name, { get: all[name], enumerable: true });
17
- };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
-
36
- // src/config-manager.ts
37
- var config_manager_exports = {};
38
- __export(config_manager_exports, {
39
- ConfigManager: () => ConfigManager,
40
- configManager: () => configManager
41
- });
42
- var ConfigManager, configManager;
43
- var init_config_manager = __esm({
44
- "src/config-manager.ts"() {
45
- "use strict";
46
- ConfigManager = class {
47
- /** 存储配置的 Map */
48
- config = /* @__PURE__ */ new Map();
49
- /**
50
- * 设置配置项
51
- * @param key 配置键
52
- * @param value 配置值
53
- */
54
- set(key, value) {
55
- this.config.set(key, value);
56
- }
57
- /**
58
- * 获取配置项
59
- * @param key 配置键
60
- */
61
- get(key) {
62
- return this.config.get(key);
63
- }
64
- /**
65
- * 合并配置
66
- * @param config 配置对象
67
- */
68
- merge(config) {
69
- Object.keys(config).forEach((key) => {
70
- const existing = this.config.get(key);
71
- const incoming = config[key];
72
- if (existing && typeof existing === "object" && incoming && typeof incoming === "object") {
73
- this.config.set(key, { ...existing, ...incoming });
74
- } else {
75
- this.config.set(key, incoming);
76
- }
77
- });
78
- }
79
- /**
80
- * 获取所有配置
81
- */
82
- getAll() {
83
- return Object.fromEntries(this.config);
84
- }
85
- };
86
- configManager = new ConfigManager();
87
- }
88
- });
89
-
90
- // ../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/dayjs.min.js
91
- var require_dayjs_min = __commonJS({
92
- "../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/dayjs.min.js"(exports2, module2) {
93
- "use strict";
94
- !(function(t, e) {
95
- "object" == typeof exports2 && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
96
- })(exports2, (function() {
97
- "use strict";
98
- var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
99
- var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
100
- return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
101
- } }, m = function(t2, e2, n2) {
102
- var r2 = String(t2);
103
- return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
104
- }, v = { s: m, z: function(t2) {
105
- var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
106
- return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
107
- }, m: function t2(e2, n2) {
108
- if (e2.date() < n2.date()) return -t2(n2, e2);
109
- var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
110
- return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
111
- }, a: function(t2) {
112
- return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
113
- }, p: function(t2) {
114
- return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
115
- }, u: function(t2) {
116
- return void 0 === t2;
117
- } }, g = "en", D = {};
118
- D[g] = M;
119
- var p = "$isDayjsObject", S = function(t2) {
120
- return t2 instanceof _ || !(!t2 || !t2[p]);
121
- }, w = function t2(e2, n2, r2) {
122
- var i2;
123
- if (!e2) return g;
124
- if ("string" == typeof e2) {
125
- var s2 = e2.toLowerCase();
126
- D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
127
- var u2 = e2.split("-");
128
- if (!i2 && u2.length > 1) return t2(u2[0]);
129
- } else {
130
- var a2 = e2.name;
131
- D[a2] = e2, i2 = a2;
132
- }
133
- return !r2 && i2 && (g = i2), i2 || !r2 && g;
134
- }, O = function(t2, e2) {
135
- if (S(t2)) return t2.clone();
136
- var n2 = "object" == typeof e2 ? e2 : {};
137
- return n2.date = t2, n2.args = arguments, new _(n2);
138
- }, b = v;
139
- b.l = w, b.i = S, b.w = function(t2, e2) {
140
- return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
141
- };
142
- var _ = (function() {
143
- function M2(t2) {
144
- this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
145
- }
146
- var m2 = M2.prototype;
147
- return m2.parse = function(t2) {
148
- this.$d = (function(t3) {
149
- var e2 = t3.date, n2 = t3.utc;
150
- if (null === e2) return /* @__PURE__ */ new Date(NaN);
151
- if (b.u(e2)) return /* @__PURE__ */ new Date();
152
- if (e2 instanceof Date) return new Date(e2);
153
- if ("string" == typeof e2 && !/Z$/i.test(e2)) {
154
- var r2 = e2.match($);
155
- if (r2) {
156
- var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
157
- return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
158
- }
159
- }
160
- return new Date(e2);
161
- })(t2), this.init();
162
- }, m2.init = function() {
163
- var t2 = this.$d;
164
- this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
165
- }, m2.$utils = function() {
166
- return b;
167
- }, m2.isValid = function() {
168
- return !(this.$d.toString() === l);
169
- }, m2.isSame = function(t2, e2) {
170
- var n2 = O(t2);
171
- return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
172
- }, m2.isAfter = function(t2, e2) {
173
- return O(t2) < this.startOf(e2);
174
- }, m2.isBefore = function(t2, e2) {
175
- return this.endOf(e2) < O(t2);
176
- }, m2.$g = function(t2, e2, n2) {
177
- return b.u(t2) ? this[e2] : this.set(n2, t2);
178
- }, m2.unix = function() {
179
- return Math.floor(this.valueOf() / 1e3);
180
- }, m2.valueOf = function() {
181
- return this.$d.getTime();
182
- }, m2.startOf = function(t2, e2) {
183
- var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
184
- var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
185
- return r2 ? i2 : i2.endOf(a);
186
- }, $2 = function(t3, e3) {
187
- return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
188
- }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
189
- switch (f2) {
190
- case h:
191
- return r2 ? l2(1, 0) : l2(31, 11);
192
- case c:
193
- return r2 ? l2(1, M3) : l2(0, M3 + 1);
194
- case o:
195
- var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
196
- return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
197
- case a:
198
- case d:
199
- return $2(v2 + "Hours", 0);
200
- case u:
201
- return $2(v2 + "Minutes", 1);
202
- case s:
203
- return $2(v2 + "Seconds", 2);
204
- case i:
205
- return $2(v2 + "Milliseconds", 3);
206
- default:
207
- return this.clone();
208
- }
209
- }, m2.endOf = function(t2) {
210
- return this.startOf(t2, false);
211
- }, m2.$set = function(t2, e2) {
212
- var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
213
- if (o2 === c || o2 === h) {
214
- var y2 = this.clone().set(d, 1);
215
- y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
216
- } else l2 && this.$d[l2]($2);
217
- return this.init(), this;
218
- }, m2.set = function(t2, e2) {
219
- return this.clone().$set(t2, e2);
220
- }, m2.get = function(t2) {
221
- return this[b.p(t2)]();
222
- }, m2.add = function(r2, f2) {
223
- var d2, l2 = this;
224
- r2 = Number(r2);
225
- var $2 = b.p(f2), y2 = function(t2) {
226
- var e2 = O(l2);
227
- return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
228
- };
229
- if ($2 === c) return this.set(c, this.$M + r2);
230
- if ($2 === h) return this.set(h, this.$y + r2);
231
- if ($2 === a) return y2(1);
232
- if ($2 === o) return y2(7);
233
- var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
234
- return b.w(m3, this);
235
- }, m2.subtract = function(t2, e2) {
236
- return this.add(-1 * t2, e2);
237
- }, m2.format = function(t2) {
238
- var e2 = this, n2 = this.$locale();
239
- if (!this.isValid()) return n2.invalidDate || l;
240
- var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
241
- return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
242
- }, d2 = function(t3) {
243
- return b.s(s2 % 12 || 12, t3, "0");
244
- }, $2 = f2 || function(t3, e3, n3) {
245
- var r3 = t3 < 12 ? "AM" : "PM";
246
- return n3 ? r3.toLowerCase() : r3;
247
- };
248
- return r2.replace(y, (function(t3, r3) {
249
- return r3 || (function(t4) {
250
- switch (t4) {
251
- case "YY":
252
- return String(e2.$y).slice(-2);
253
- case "YYYY":
254
- return b.s(e2.$y, 4, "0");
255
- case "M":
256
- return a2 + 1;
257
- case "MM":
258
- return b.s(a2 + 1, 2, "0");
259
- case "MMM":
260
- return h2(n2.monthsShort, a2, c2, 3);
261
- case "MMMM":
262
- return h2(c2, a2);
263
- case "D":
264
- return e2.$D;
265
- case "DD":
266
- return b.s(e2.$D, 2, "0");
267
- case "d":
268
- return String(e2.$W);
269
- case "dd":
270
- return h2(n2.weekdaysMin, e2.$W, o2, 2);
271
- case "ddd":
272
- return h2(n2.weekdaysShort, e2.$W, o2, 3);
273
- case "dddd":
274
- return o2[e2.$W];
275
- case "H":
276
- return String(s2);
277
- case "HH":
278
- return b.s(s2, 2, "0");
279
- case "h":
280
- return d2(1);
281
- case "hh":
282
- return d2(2);
283
- case "a":
284
- return $2(s2, u2, true);
285
- case "A":
286
- return $2(s2, u2, false);
287
- case "m":
288
- return String(u2);
289
- case "mm":
290
- return b.s(u2, 2, "0");
291
- case "s":
292
- return String(e2.$s);
293
- case "ss":
294
- return b.s(e2.$s, 2, "0");
295
- case "SSS":
296
- return b.s(e2.$ms, 3, "0");
297
- case "Z":
298
- return i2;
299
- }
300
- return null;
301
- })(t3) || i2.replace(":", "");
302
- }));
303
- }, m2.utcOffset = function() {
304
- return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
305
- }, m2.diff = function(r2, d2, l2) {
306
- var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
307
- return b.m(y2, m3);
308
- };
309
- switch (M3) {
310
- case h:
311
- $2 = D2() / 12;
312
- break;
313
- case c:
314
- $2 = D2();
315
- break;
316
- case f:
317
- $2 = D2() / 3;
318
- break;
319
- case o:
320
- $2 = (g2 - v2) / 6048e5;
321
- break;
322
- case a:
323
- $2 = (g2 - v2) / 864e5;
324
- break;
325
- case u:
326
- $2 = g2 / n;
327
- break;
328
- case s:
329
- $2 = g2 / e;
330
- break;
331
- case i:
332
- $2 = g2 / t;
333
- break;
334
- default:
335
- $2 = g2;
336
- }
337
- return l2 ? $2 : b.a($2);
338
- }, m2.daysInMonth = function() {
339
- return this.endOf(c).$D;
340
- }, m2.$locale = function() {
341
- return D[this.$L];
342
- }, m2.locale = function(t2, e2) {
343
- if (!t2) return this.$L;
344
- var n2 = this.clone(), r2 = w(t2, e2, true);
345
- return r2 && (n2.$L = r2), n2;
346
- }, m2.clone = function() {
347
- return b.w(this.$d, this);
348
- }, m2.toDate = function() {
349
- return new Date(this.valueOf());
350
- }, m2.toJSON = function() {
351
- return this.isValid() ? this.toISOString() : null;
352
- }, m2.toISOString = function() {
353
- return this.$d.toISOString();
354
- }, m2.toString = function() {
355
- return this.$d.toUTCString();
356
- }, M2;
357
- })(), k = _.prototype;
358
- return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach((function(t2) {
359
- k[t2[1]] = function(e2) {
360
- return this.$g(e2, t2[0], t2[1]);
361
- };
362
- })), O.extend = function(t2, e2) {
363
- return t2.$i || (t2(e2, _, O), t2.$i = true), O;
364
- }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
365
- return O(1e3 * t2);
366
- }, O.en = D[g], O.Ls = D, O.p = {}, O;
367
- }));
368
- }
369
- });
370
-
371
- // ../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/plugin/relativeTime.js
372
- var require_relativeTime = __commonJS({
373
- "../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/plugin/relativeTime.js"(exports2, module2) {
374
- "use strict";
375
- !(function(r, e) {
376
- "object" == typeof exports2 && "undefined" != typeof module2 ? module2.exports = e() : "function" == typeof define && define.amd ? define(e) : (r = "undefined" != typeof globalThis ? globalThis : r || self).dayjs_plugin_relativeTime = e();
377
- })(exports2, (function() {
378
- "use strict";
379
- return function(r, e, t) {
380
- r = r || {};
381
- var n = e.prototype, o = { future: "in %s", past: "%s ago", s: "a few seconds", m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", M: "a month", MM: "%d months", y: "a year", yy: "%d years" };
382
- function i(r2, e2, t2, o2) {
383
- return n.fromToBase(r2, e2, t2, o2);
384
- }
385
- t.en.relativeTime = o, n.fromToBase = function(e2, n2, i2, d2, u) {
386
- for (var f, a, s, l = i2.$locale().relativeTime || o, h = r.thresholds || [{ l: "s", r: 44, d: "second" }, { l: "m", r: 89 }, { l: "mm", r: 44, d: "minute" }, { l: "h", r: 89 }, { l: "hh", r: 21, d: "hour" }, { l: "d", r: 35 }, { l: "dd", r: 25, d: "day" }, { l: "M", r: 45 }, { l: "MM", r: 10, d: "month" }, { l: "y", r: 17 }, { l: "yy", d: "year" }], m = h.length, c = 0; c < m; c += 1) {
387
- var y = h[c];
388
- y.d && (f = d2 ? t(e2).diff(i2, y.d, true) : i2.diff(e2, y.d, true));
389
- var p = (r.rounding || Math.round)(Math.abs(f));
390
- if (s = f > 0, p <= y.r || !y.r) {
391
- p <= 1 && c > 0 && (y = h[c - 1]);
392
- var v = l[y.l];
393
- u && (p = u("" + p)), a = "string" == typeof v ? v.replace("%d", p) : v(p, n2, y.l, s);
394
- break;
395
- }
396
- }
397
- if (n2) return a;
398
- var M = s ? l.future : l.past;
399
- return "function" == typeof M ? M(a) : M.replace("%s", a);
400
- }, n.to = function(r2, e2) {
401
- return i(r2, e2, this, true);
402
- }, n.from = function(r2, e2) {
403
- return i(r2, e2, this);
404
- };
405
- var d = function(r2) {
406
- return r2.$u ? t.utc() : t();
407
- };
408
- n.toNow = function(r2) {
409
- return this.to(d(this), r2);
410
- }, n.fromNow = function(r2) {
411
- return this.from(d(this), r2);
412
- };
413
- };
414
- }));
415
- }
416
- });
417
-
418
- // ../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/locale/zh-cn.js
419
- var require_zh_cn = __commonJS({
420
- "../../node_modules/.pnpm/dayjs@1.11.19/node_modules/dayjs/locale/zh-cn.js"(exports2, module2) {
421
- "use strict";
422
- !(function(e, _) {
423
- "object" == typeof exports2 && "undefined" != typeof module2 ? module2.exports = _(require_dayjs_min()) : "function" == typeof define && define.amd ? define(["dayjs"], _) : (e = "undefined" != typeof globalThis ? globalThis : e || self).dayjs_locale_zh_cn = _(e.dayjs);
424
- })(exports2, (function(e) {
425
- "use strict";
426
- function _(e2) {
427
- return e2 && "object" == typeof e2 && "default" in e2 ? e2 : { default: e2 };
428
- }
429
- var t = _(e), d = { name: "zh-cn", weekdays: "\u661F\u671F\u65E5_\u661F\u671F\u4E00_\u661F\u671F\u4E8C_\u661F\u671F\u4E09_\u661F\u671F\u56DB_\u661F\u671F\u4E94_\u661F\u671F\u516D".split("_"), weekdaysShort: "\u5468\u65E5_\u5468\u4E00_\u5468\u4E8C_\u5468\u4E09_\u5468\u56DB_\u5468\u4E94_\u5468\u516D".split("_"), weekdaysMin: "\u65E5_\u4E00_\u4E8C_\u4E09_\u56DB_\u4E94_\u516D".split("_"), months: "\u4E00\u6708_\u4E8C\u6708_\u4E09\u6708_\u56DB\u6708_\u4E94\u6708_\u516D\u6708_\u4E03\u6708_\u516B\u6708_\u4E5D\u6708_\u5341\u6708_\u5341\u4E00\u6708_\u5341\u4E8C\u6708".split("_"), monthsShort: "1\u6708_2\u6708_3\u6708_4\u6708_5\u6708_6\u6708_7\u6708_8\u6708_9\u6708_10\u6708_11\u6708_12\u6708".split("_"), ordinal: function(e2, _2) {
430
- return "W" === _2 ? e2 + "\u5468" : e2 + "\u65E5";
431
- }, weekStart: 1, yearStart: 4, formats: { LT: "HH:mm", LTS: "HH:mm:ss", L: "YYYY/MM/DD", LL: "YYYY\u5E74M\u6708D\u65E5", LLL: "YYYY\u5E74M\u6708D\u65E5Ah\u70B9mm\u5206", LLLL: "YYYY\u5E74M\u6708D\u65E5ddddAh\u70B9mm\u5206", l: "YYYY/M/D", ll: "YYYY\u5E74M\u6708D\u65E5", lll: "YYYY\u5E74M\u6708D\u65E5 HH:mm", llll: "YYYY\u5E74M\u6708D\u65E5dddd HH:mm" }, relativeTime: { future: "%s\u5185", past: "%s\u524D", s: "\u51E0\u79D2", m: "1 \u5206\u949F", mm: "%d \u5206\u949F", h: "1 \u5C0F\u65F6", hh: "%d \u5C0F\u65F6", d: "1 \u5929", dd: "%d \u5929", M: "1 \u4E2A\u6708", MM: "%d \u4E2A\u6708", y: "1 \u5E74", yy: "%d \u5E74" }, meridiem: function(e2, _2) {
432
- var t2 = 100 * e2 + _2;
433
- return t2 < 600 ? "\u51CC\u6668" : t2 < 900 ? "\u65E9\u4E0A" : t2 < 1100 ? "\u4E0A\u5348" : t2 < 1300 ? "\u4E2D\u5348" : t2 < 1800 ? "\u4E0B\u5348" : "\u665A\u4E0A";
434
- } };
435
- return t.default.locale(d, null, true), d;
436
- }));
437
- }
438
- });
439
-
440
- // src/index.ts
441
- var index_exports = {};
442
- __export(index_exports, {
443
- ApiEngine: () => ApiEngine,
444
- ApiProvider: () => ApiProvider,
445
- AvatarSkeleton: () => AvatarSkeleton,
446
- AxiosAdapter: () => AxiosAdapter,
447
- BasePlugin: () => BasePlugin,
448
- BlockSkeleton: () => BlockSkeleton,
449
- ConfigManager: () => ConfigManager,
450
- DefaultEventBus: () => DefaultEventBus,
451
- LocalStorageAdapter: () => LocalStorageAdapter,
452
- LogLevel: () => LogLevel,
453
- Logger: () => Logger,
454
- PLUGIN_TYPES: () => PLUGIN_TYPES,
455
- PluginErrorBoundary: () => PluginErrorBoundary,
456
- PluginManager: () => PluginManager,
457
- PluginProvider: () => PluginProvider,
458
- PluginRuntime: () => PluginRuntime,
459
- PluginSandbox: () => PluginSandbox,
460
- PluginSlot: () => PluginSlot,
461
- SUCCESS_CODE: () => SUCCESS_CODE,
462
- ScopedStorageAdapter: () => ScopedStorageAdapter,
463
- ServiceRegistry: () => ServiceRegistry,
464
- SidebarIconSkeleton: () => SidebarIconSkeleton,
465
- Slot: () => Slot,
466
- StatusBarItemSkeleton: () => StatusBarItemSkeleton,
467
- StorageManager: () => StorageManager,
468
- apiEngine: () => apiEngine,
469
- cleanUrlParams: () => cleanUrlParams,
470
- configManager: () => configManager,
471
- createLogger: () => createLogger,
472
- dateUtils: () => dateUtils,
473
- definePlugin: () => definePlugin,
474
- isMockMode: () => isMockMode,
475
- logger: () => logger,
476
- normalizeParams: () => normalizeParams,
477
- pluginManager: () => pluginManager,
478
- resolveApiModules: () => resolveApiModules,
479
- resolvePluginRegistry: () => resolvePluginRegistry,
480
- serviceRegistry: () => serviceRegistry,
481
- useApi: () => useApi,
482
- usePluginLoader: () => usePluginLoader,
483
- usePluginManager: () => usePluginManager,
484
- useStorageState: () => useStorageState,
485
- version: () => version
486
- });
487
- module.exports = __toCommonJS(index_exports);
488
-
489
- // src/ports/plugin-port.ts
490
- var PLUGIN_TYPES = ["business", "functional", "view", "theme", "renderer", "system"];
491
- var Slot = {
492
- Sidebar: "sidebar",
493
- SidebarPanel: "sidebar-panel",
494
- Header: "header",
495
- StatusBar: "status-bar",
496
- Settings: "settings",
497
- MessageRenderer: "message-renderer",
498
- MessageContentRenderer: "message-content-renderer",
499
- SidebarSystem: "sidebar-system",
500
- SidebarBottom: "sidebar-bottom",
501
- RootLayout: "root-layout",
502
- Custom: "custom"
503
- };
504
- var BasePlugin = class {
505
- /**
506
- * 插件 ID
507
- * @description 自动从 metadata.id 获取
508
- */
509
- get id() {
510
- return this.metadata.id;
511
- }
512
- };
513
- function definePlugin(plugin) {
514
- return {
515
- ...plugin,
516
- get id() {
517
- return this.metadata.id;
518
- }
519
- };
520
- }
521
-
522
- // src/utils/logger.ts
523
- var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
524
- LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
525
- LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
526
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
527
- LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
528
- LogLevel2[LogLevel2["NONE"] = 4] = "NONE";
529
- return LogLevel2;
530
- })(LogLevel || {});
531
- var Logger = class _Logger {
532
- /** 全局默认日志等级 */
533
- static level = 1 /* INFO */;
534
- /** 当前实例的前缀 */
535
- prefix;
536
- /**
537
- * 构造函数
538
- * @param prefix 日志前缀,默认为 'App'
539
- */
540
- constructor(prefix = "App") {
541
- this.prefix = prefix;
542
- }
543
- /**
544
- * 设置全局日志等级
545
- * @param level 日志等级
546
- */
547
- static setLevel(level) {
548
- this.level = level;
549
- console.info(`[Logger] Global log level set to: ${LogLevel[level]}`);
550
- }
551
- /**
552
- * 获取当前日志等级
553
- * @returns 当前全局日志等级
554
- */
555
- static getLevel() {
556
- return this.level;
557
- }
558
- /**
559
- * 打印 DEBUG 级别日志
560
- */
561
- get debug() {
562
- return _Logger.level <= 0 /* DEBUG */ ? console.debug.bind(console, `[${this.prefix}]`) : noop;
563
- }
564
- /**
565
- * 打印 INFO 级别日志
566
- */
567
- get info() {
568
- return _Logger.level <= 1 /* INFO */ ? console.info.bind(console, `[${this.prefix}]`) : noop;
569
- }
570
- /**
571
- * 打印 WARN 级别日志
572
- */
573
- get warn() {
574
- return _Logger.level <= 2 /* WARN */ ? console.warn.bind(console, `[${this.prefix}]`) : noop;
575
- }
576
- /**
577
- * 打印 ERROR 级别日志
578
- */
579
- get error() {
580
- return _Logger.level <= 3 /* ERROR */ ? console.error.bind(console, `[${this.prefix}]`) : noop;
581
- }
582
- /**
583
- * 开始一个日志分组
584
- * @param label 分组标签
585
- * @param collapsed 是否默认折叠,默认为 false
586
- */
587
- group(label, collapsed = false) {
588
- if (_Logger.level <= 1 /* INFO */) {
589
- if (collapsed) {
590
- console.groupCollapsed(`[${this.prefix}] ${label}`);
591
- } else {
592
- console.group(`[${this.prefix}] ${label}`);
593
- }
594
- }
595
- }
596
- /**
597
- * 结束当前日志分组
598
- */
599
- get groupEnd() {
600
- return _Logger.level <= 1 /* INFO */ ? console.groupEnd.bind(console) : noop;
601
- }
602
- };
603
- var noop = () => {
604
- };
605
- var logger = new Logger();
606
- var createLogger = (prefix) => new Logger(prefix);
607
-
608
- // src/application/service-registry.ts
609
- var logger2 = createLogger("ServiceRegistry");
610
- var ServiceRegistry = class {
611
- services = /* @__PURE__ */ new Map();
612
- listeners = /* @__PURE__ */ new Map();
613
- /**
614
- * 注册服务
615
- * @param name 服务名称 (建议格式: pluginId.serviceName)
616
- * @param service 服务实现
617
- */
618
- register(name, service) {
619
- if (this.services.has(name)) {
620
- logger2.warn(`\u670D\u52A1 "${name}" \u5DF2\u5B58\u5728\uFF0C\u5C06\u88AB\u8986\u76D6`);
621
- }
622
- this.services.set(name, service);
623
- logger2.info(`\u670D\u52A1\u5DF2\u6CE8\u518C: ${name}`);
624
- if (this.listeners.has(name)) {
625
- const set = this.listeners.get(name);
626
- set.forEach((callback) => callback(service));
627
- this.listeners.delete(name);
628
- }
629
- }
630
- /**
631
- * 获取服务
632
- * @param name 服务名称
633
- */
634
- get(name) {
635
- return this.services.get(name);
636
- }
637
- /**
638
- * 异步获取服务 (如果尚未注册则等待)
639
- * @param name 服务名称
640
- */
641
- async waitFor(name) {
642
- const service = this.services.get(name);
643
- if (service) return service;
644
- return new Promise((resolve) => {
645
- if (!this.listeners.has(name)) {
646
- this.listeners.set(name, /* @__PURE__ */ new Set());
647
- }
648
- this.listeners.get(name).add(resolve);
649
- });
650
- }
651
- /**
652
- * 注销服务
653
- * @param name 服务名称
654
- */
655
- unregister(name) {
656
- this.services.delete(name);
657
- logger2.info(`\u670D\u52A1\u5DF2\u6CE8\u9500: ${name}`);
658
- }
659
- /**
660
- * 清除所有服务 (通常在系统重置时使用)
661
- */
662
- clear() {
663
- this.services.clear();
664
- this.listeners.clear();
665
- }
666
- };
667
- var serviceRegistry = new ServiceRegistry();
668
-
669
- // src/api-context.tsx
670
- var import_react = require("react");
671
- var import_jsx_runtime = require("react/jsx-runtime");
672
- var ApiContext = (0, import_react.createContext)(null);
673
- var ApiProvider = ({ api, children }) => {
674
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ApiContext.Provider, { value: api, children });
675
- };
676
- var useApi = () => {
677
- const context = (0, import_react.useContext)(ApiContext);
678
- if (!context) {
679
- throw new Error("useApi must be used within an ApiProvider");
680
- }
681
- return context;
682
- };
683
-
684
- // src/index.ts
685
- init_config_manager();
686
-
687
- // src/components/PluginErrorBoundary.tsx
688
- var import_react2 = require("react");
689
- var import_jsx_runtime2 = require("react/jsx-runtime");
690
- var logger3 = createLogger("PluginErrorBoundary");
691
- var PluginErrorBoundary = class extends import_react2.Component {
692
- constructor(props) {
693
- super(props);
694
- this.state = { hasError: false, error: null };
695
- }
696
- static getDerivedStateFromError(error) {
697
- return { hasError: true, error };
698
- }
699
- componentDidCatch(error, errorInfo) {
700
- logger3.error(`\u63D2\u4EF6 ${this.props.pluginId || "\u672A\u77E5"} \u53D1\u751F\u9519\u8BEF:`, error, errorInfo);
701
- }
702
- handleRetry = () => {
703
- this.setState({ hasError: false, error: null });
704
- };
705
- render() {
706
- if (this.state.hasError) {
707
- if (this.props.fallback) {
708
- return this.props.fallback;
709
- }
710
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "p-4 border border-dashed border-red-500/50 rounded-lg bg-red-50 dark:bg-red-500/5 text-center", children: [
711
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "text-red-500 font-medium mb-1", children: "\u63D2\u4EF6\u6E32\u67D3\u5931\u8D25" }),
712
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "text-xs text-slate-500 dark:text-slate-400 mb-3", children: [
713
- "\u63D2\u4EF6 ",
714
- this.props.pluginId ? `"${this.props.pluginId}"` : "\u672A\u77E5",
715
- " \u53D1\u751F\u5F02\u5E38: ",
716
- this.state.error?.message
717
- ] }),
718
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
719
- "button",
720
- {
721
- onClick: this.handleRetry,
722
- className: "px-3 py-1.5 bg-red-500 hover:bg-red-600 text-white text-xs rounded transition-colors duration-150",
723
- children: "\u91CD\u8BD5"
724
- }
725
- )
726
- ] });
727
- }
728
- return this.props.children;
729
- }
730
- };
731
-
732
- // src/components/PluginSlot.tsx
733
- var import_react3 = require("react");
734
-
735
- // src/adapters/local-storage-adapter.ts
736
- var LocalStorageAdapter = class {
737
- prefix;
738
- constructor(prefix = "") {
739
- this.prefix = prefix;
740
- }
741
- getKey(key) {
742
- return this.prefix ? `${this.prefix}:${key}` : key;
743
- }
744
- getOriginalKey(namespacedKey) {
745
- if (!this.prefix) return namespacedKey;
746
- if (namespacedKey.startsWith(this.prefix + ":")) {
747
- return namespacedKey.slice(this.prefix.length + 1);
748
- }
749
- return null;
750
- }
751
- getItem(key) {
752
- return localStorage.getItem(this.getKey(key));
753
- }
754
- setItem(key, value) {
755
- localStorage.setItem(this.getKey(key), value);
756
- }
757
- removeItem(key) {
758
- localStorage.removeItem(this.getKey(key));
759
- }
760
- clear() {
761
- if (!this.prefix) {
762
- localStorage.clear();
763
- return;
764
- }
765
- const keysToRemove = [];
766
- for (let i = 0; i < localStorage.length; i++) {
767
- const key = localStorage.key(i);
768
- if (key && key.startsWith(this.prefix + ":")) {
769
- keysToRemove.push(key);
770
- }
771
- }
772
- keysToRemove.forEach((key) => localStorage.removeItem(key));
773
- }
774
- get length() {
775
- if (!this.prefix) return localStorage.length;
776
- let count = 0;
777
- for (let i = 0; i < localStorage.length; i++) {
778
- const key = localStorage.key(i);
779
- if (key && key.startsWith(this.prefix + ":")) {
780
- count++;
781
- }
782
- }
783
- return count;
784
- }
785
- key(index) {
786
- if (!this.prefix) return localStorage.key(index);
787
- let count = 0;
788
- for (let i = 0; i < localStorage.length; i++) {
789
- const key = localStorage.key(i);
790
- if (key && key.startsWith(this.prefix + ":")) {
791
- if (count === index) {
792
- return this.getOriginalKey(key);
793
- }
794
- count++;
795
- }
796
- }
797
- return null;
798
- }
799
- };
800
-
801
- // src/domain/plugin-manager.ts
802
- init_config_manager();
803
-
804
- // src/event-bus.ts
805
- var logger4 = createLogger("EventBus");
806
- var DefaultEventBus = class {
807
- listeners = /* @__PURE__ */ new Map();
808
- on(event, callback) {
809
- if (!this.listeners.has(event)) {
810
- this.listeners.set(event, []);
811
- }
812
- this.listeners.get(event)?.push(callback);
813
- return () => this.off(event, callback);
814
- }
815
- off(event, callback) {
816
- const callbacks = this.listeners.get(event);
817
- if (callbacks) {
818
- this.listeners.set(event, callbacks.filter((cb) => cb !== callback));
819
- }
820
- }
821
- emit(event, ...args) {
822
- const callbacks = this.listeners.get(event);
823
- if (callbacks) {
824
- callbacks.forEach((cb) => {
825
- try {
826
- cb(...args);
827
- } catch (error) {
828
- logger4.error(`\u4E8B\u4EF6\u76D1\u542C\u5668\u5904\u7406\u9519\u8BEF (${event}):`, error);
829
- }
830
- });
831
- }
832
- }
833
- once(event, callback) {
834
- const wrapper = (...args) => {
835
- callback(...args);
836
- this.off(event, wrapper);
837
- };
838
- this.on(event, wrapper);
839
- }
840
- };
841
-
842
- // src/sandbox/proxy-sandbox.ts
843
- var logger5 = createLogger("ProxySandbox");
844
- var ProxySandbox = class {
845
- /** 沙箱名称 */
846
- name;
847
- /** 代理后的 Window 对象 */
848
- proxy;
849
- /** 沙箱是否激活 */
850
- running = false;
851
- /** 记录新增/修改的全局变量 */
852
- updatedValueSet = /* @__PURE__ */ new Set();
853
- /** 副作用记录池 */
854
- effectPool = {
855
- timeouts: /* @__PURE__ */ new Set(),
856
- intervals: /* @__PURE__ */ new Set(),
857
- listeners: /* @__PURE__ */ new Map()
858
- };
859
- /** 真实的 Window 对象 */
860
- globalContext;
861
- /** 白名单全局变量(允许透传访问真实 Window) */
862
- static globalWhitelist = [
863
- "System",
864
- "console",
865
- // 'setTimeout', // 移除白名单,改为劫持
866
- // 'setInterval',
867
- // 'clearTimeout',
868
- // 'clearInterval',
869
- "requestAnimationFrame",
870
- "cancelAnimationFrame",
871
- // 'addEventListener', // 移除白名单,改为劫持
872
- // 'removeEventListener',
873
- "location",
874
- "history",
875
- "navigator",
876
- "document"
877
- ];
878
- constructor(name, globalContext = window) {
879
- this.name = name;
880
- this.globalContext = globalContext;
881
- const { fakeWindow, propertiesWithGetter } = this.createFakeWindow(globalContext);
882
- this.patchGlobalEffects(fakeWindow);
883
- const proxy = new Proxy(fakeWindow, {
884
- set: (target, p, value) => {
885
- if (this.running) {
886
- this.updatedValueSet.add(p);
887
- target[p] = value;
888
- return true;
889
- }
890
- logger5.warn(`${name} \u672A\u8FD0\u884C\uFF0C\u65E0\u6CD5\u8BBE\u7F6E\u5C5E\u6027 '${String(p)}'`);
891
- return false;
892
- },
893
- get: (target, p) => {
894
- if (p === Symbol.unscopables) return void 0;
895
- if (p === "window" || p === "self" || p === "globalThis") {
896
- return this.proxy;
897
- }
898
- if (p === "top" || p === "parent") {
899
- return this.globalContext[p];
900
- }
901
- const value = target[p];
902
- if (value !== void 0 || this.updatedValueSet.has(p)) {
903
- return value;
904
- }
905
- const rawValue = this.globalContext[p];
906
- if (typeof rawValue === "function" && !this.isConstructor(rawValue)) {
907
- if (this.isNativeFunction(rawValue)) {
908
- return rawValue.bind(this.globalContext);
909
- }
910
- }
911
- return rawValue;
912
- },
913
- has: (target, p) => {
914
- return p in target || p in this.globalContext;
915
- },
916
- defineProperty: (target, p, attributes) => {
917
- if (this.running) {
918
- this.updatedValueSet.add(p);
919
- return Reflect.defineProperty(target, p, attributes);
920
- }
921
- return false;
922
- }
923
- });
924
- this.proxy = proxy;
925
- }
926
- /**
927
- * 激活沙箱
928
- */
929
- active() {
930
- if (!this.running) {
931
- this.running = true;
932
- }
933
- }
934
- /**
935
- * 销毁沙箱
936
- */
937
- inactive() {
938
- this.running = false;
939
- this.effectPool.timeouts.forEach((id) => this.globalContext.clearTimeout(id));
940
- this.effectPool.timeouts.clear();
941
- this.effectPool.intervals.forEach((id) => this.globalContext.clearInterval(id));
942
- this.effectPool.intervals.clear();
943
- this.effectPool.listeners.forEach((listeners, type) => {
944
- listeners.forEach(({ listener, options }) => {
945
- this.globalContext.removeEventListener(type, listener, options);
946
- });
947
- });
948
- this.effectPool.listeners.clear();
949
- logger5.debug(`${this.name} \u5DF2\u505C\u7528\uFF0C\u526F\u4F5C\u7528\u5DF2\u6E05\u9664\u3002`);
950
- }
951
- /**
952
- * 在沙箱中执行代码
953
- * @param code JS 代码字符串
954
- * @returns 执行结果
955
- */
956
- eval(code) {
957
- const evalCode = `
958
- ;(function(window, self, globalThis){
959
- with(window) {
960
- ${code}
961
- }
962
- }).bind(window.proxy)(window.proxy, window.proxy, window.proxy);
963
- `;
964
- return (0, eval)(evalCode);
965
- }
966
- /**
967
- * 创建伪造的 Window 对象
968
- */
969
- createFakeWindow(globalContext) {
970
- const propertiesWithGetter = /* @__PURE__ */ new Map();
971
- const fakeWindow = {};
972
- Object.getOwnPropertyNames(globalContext).forEach((p) => {
973
- const descriptor = Object.getOwnPropertyDescriptor(globalContext, p);
974
- if (descriptor && !descriptor.configurable) {
975
- }
976
- });
977
- return { fakeWindow, propertiesWithGetter };
978
- }
979
- isConstructor(fn) {
980
- const prototype = fn.prototype;
981
- return !!(prototype && prototype.constructor === fn && Object.getOwnPropertyNames(prototype).length > 0);
982
- }
983
- isNativeFunction(fn) {
984
- return fn.toString().indexOf("[native code]") > -1;
985
- }
986
- /**
987
- * 劫持全局副作用 API
988
- */
989
- patchGlobalEffects(fakeWindow) {
990
- fakeWindow.setTimeout = (handler, timeout, ...args) => {
991
- const id = this.globalContext.setTimeout(handler, timeout, ...args);
992
- this.effectPool.timeouts.add(id);
993
- return id;
994
- };
995
- fakeWindow.clearTimeout = (id) => {
996
- if (id) {
997
- this.effectPool.timeouts.delete(id);
998
- this.globalContext.clearTimeout(id);
999
- }
1000
- };
1001
- fakeWindow.setInterval = (handler, timeout, ...args) => {
1002
- const id = this.globalContext.setInterval(handler, timeout, ...args);
1003
- this.effectPool.intervals.add(id);
1004
- return id;
1005
- };
1006
- fakeWindow.clearInterval = (id) => {
1007
- if (id) {
1008
- this.effectPool.intervals.delete(id);
1009
- this.globalContext.clearInterval(id);
1010
- }
1011
- };
1012
- fakeWindow.addEventListener = (type, listener, options) => {
1013
- const listeners = this.effectPool.listeners.get(type) || [];
1014
- listeners.push({ listener, options });
1015
- this.effectPool.listeners.set(type, listeners);
1016
- return this.globalContext.addEventListener(type, listener, options);
1017
- };
1018
- fakeWindow.removeEventListener = (type, listener, options) => {
1019
- const listeners = this.effectPool.listeners.get(type);
1020
- if (listeners) {
1021
- const index = listeners.findIndex((item) => item.listener === listener && item.options === options);
1022
- if (index !== -1) listeners.splice(index, 1);
1023
- }
1024
- return this.globalContext.removeEventListener(type, listener, options);
1025
- };
1026
- }
1027
- };
1028
-
1029
- // src/domain/plugin-sandbox.ts
1030
- var PluginSandbox = class {
1031
- pluginId;
1032
- storageManager;
1033
- constructor(pluginId, storageManager) {
1034
- this.pluginId = pluginId;
1035
- this.storageManager = storageManager;
1036
- }
1037
- /**
1038
- * 获取隔离的存储接口
1039
- */
1040
- get storage() {
1041
- return this.storageManager.getContextStorage(this.pluginId);
1042
- }
1043
- /**
1044
- * 获取隔离的日志接口
1045
- */
1046
- get logger() {
1047
- return createLogger(`Plugin:${this.pluginId}`);
1048
- }
1049
- };
1050
-
1051
- // src/domain/plugin-runtime.ts
1052
- var logger6 = createLogger("PluginRuntime");
1053
- var PluginRuntime = class {
1054
- plugin;
1055
- context;
1056
- storageSandbox;
1057
- windowSandbox;
1058
- isLoaded = false;
1059
- isMounted = false;
1060
- constructor(plugin, sharedContext, storageManager) {
1061
- this.plugin = plugin;
1062
- this.storageSandbox = new PluginSandbox(plugin.id, storageManager);
1063
- this.windowSandbox = new ProxySandbox(plugin.id);
1064
- this.context = {
1065
- pluginId: plugin.id,
1066
- api: sharedContext.api,
1067
- events: sharedContext.events,
1068
- storage: this.storageSandbox.storage,
1069
- logger: this.storageSandbox.logger,
1070
- window: this.windowSandbox.proxy,
1071
- getService: (name) => serviceRegistry.get(name),
1072
- registerService: (name, service) => serviceRegistry.register(`${plugin.id}.${name}`, service)
1073
- };
1074
- }
1075
- /**
1076
- * 加载插件 (onLoad)
1077
- * @description 注册服务、初始化非 UI 逻辑
1078
- */
1079
- async load() {
1080
- if (this.isLoaded) return;
1081
- logger6.debug(`\u6B63\u5728\u52A0\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);
1082
- try {
1083
- if (this.plugin.metadata.api && this.context.api && typeof this.context.api.register === "function") {
1084
- this.context.api.register(this.plugin.metadata.api);
1085
- logger6.debug(`\u5DF2\u4E3A\u63D2\u4EF6 ${this.plugin.id} \u81EA\u52A8\u6CE8\u518C API \u914D\u7F6E`);
1086
- }
1087
- if (this.plugin.onLoad) {
1088
- await this.plugin.onLoad(this.context);
1089
- }
1090
- this.isLoaded = true;
1091
- logger6.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u52A0\u8F7D\u3002`);
1092
- } catch (error) {
1093
- logger6.error(`\u63D2\u4EF6 ${this.plugin.id} \u52A0\u8F7D\u5931\u8D25:`, error);
1094
- throw error;
1095
- }
1096
- }
1097
- /**
1098
- * 挂载插件 (onMount)
1099
- * @description 激活沙箱、处理 UI 相关的副作用
1100
- */
1101
- async mount() {
1102
- if (!this.isLoaded) await this.load();
1103
- if (this.isMounted) return;
1104
- logger6.debug(`\u6B63\u5728\u6302\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);
1105
- try {
1106
- this.windowSandbox.active();
1107
- if (this.plugin.onMount) {
1108
- this.plugin.onMount(this.context);
1109
- }
1110
- this.isMounted = true;
1111
- logger6.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u6302\u8F7D\u3002`);
1112
- } catch (error) {
1113
- logger6.error(`\u63D2\u4EF6 ${this.plugin.id} \u6302\u8F7D\u5931\u8D25:`, error);
1114
- throw error;
1115
- }
1116
- }
1117
- /**
1118
- * 卸载插件 (onUnmount)
1119
- */
1120
- async unmount() {
1121
- if (!this.isMounted) return;
1122
- logger6.debug(`\u6B63\u5728\u5378\u8F7D\u63D2\u4EF6: ${this.plugin.id}`);
1123
- try {
1124
- if (this.plugin.onUnmount) {
1125
- this.plugin.onUnmount(this.context);
1126
- }
1127
- } catch (error) {
1128
- logger6.error(`\u63D2\u4EF6 ${this.plugin.id} \u5378\u8F7D\u65F6\u51FA\u9519:`, error);
1129
- } finally {
1130
- this.windowSandbox.inactive();
1131
- this.isMounted = false;
1132
- logger6.info(`\u63D2\u4EF6 ${this.plugin.id} \u5DF2\u5378\u8F7D\u3002`);
1133
- }
1134
- }
1135
- /**
1136
- * 销毁插件 (完全移除)
1137
- */
1138
- async destroy() {
1139
- await this.unmount();
1140
- this.isLoaded = false;
1141
- }
1142
- get status() {
1143
- if (this.isMounted) return "mounted";
1144
- if (this.isLoaded) return "loaded";
1145
- return "initial";
1146
- }
1147
- };
1148
-
1149
- // src/adapters/scoped-storage-adapter.ts
1150
- var ScopedStorageAdapter = class {
1151
- constructor(underlyingStorage, prefix) {
1152
- this.underlyingStorage = underlyingStorage;
1153
- this.prefix = prefix;
1154
- }
1155
- getKey(key) {
1156
- return this.prefix ? `${this.prefix}:${key}` : key;
1157
- }
1158
- getOriginalKey(namespacedKey) {
1159
- if (!this.prefix) return namespacedKey;
1160
- if (namespacedKey.startsWith(this.prefix + ":")) {
1161
- return namespacedKey.slice(this.prefix.length + 1);
1162
- }
1163
- return null;
1164
- }
1165
- getItem(key) {
1166
- return this.underlyingStorage.getItem(this.getKey(key));
1167
- }
1168
- setItem(key, value) {
1169
- this.underlyingStorage.setItem(this.getKey(key), value);
1170
- }
1171
- removeItem(key) {
1172
- this.underlyingStorage.removeItem(this.getKey(key));
1173
- }
1174
- clear() {
1175
- if (!this.prefix) {
1176
- this.underlyingStorage.clear();
1177
- return;
1178
- }
1179
- const keysToRemove = [];
1180
- for (let i = 0; i < this.underlyingStorage.length; i++) {
1181
- const key = this.underlyingStorage.key(i);
1182
- if (key && key.startsWith(this.prefix + ":")) {
1183
- keysToRemove.push(key);
1184
- }
1185
- }
1186
- keysToRemove.forEach((k) => this.underlyingStorage.removeItem(k));
1187
- }
1188
- get length() {
1189
- let count = 0;
1190
- for (let i = 0; i < this.underlyingStorage.length; i++) {
1191
- const key = this.underlyingStorage.key(i);
1192
- if (key && key.startsWith(this.prefix + ":")) {
1193
- count++;
1194
- }
1195
- }
1196
- return count;
1197
- }
1198
- key(index) {
1199
- let count = 0;
1200
- for (let i = 0; i < this.underlyingStorage.length; i++) {
1201
- const key = this.underlyingStorage.key(i);
1202
- if (key && key.startsWith(this.prefix + ":")) {
1203
- if (count === index) {
1204
- return this.getOriginalKey(key);
1205
- }
1206
- count++;
1207
- }
1208
- }
1209
- return null;
1210
- }
1211
- };
1212
-
1213
- // src/domain/storage-manager.ts
1214
- init_config_manager();
1215
- var StorageManager = class {
1216
- baseStorage;
1217
- schemas = /* @__PURE__ */ new Map();
1218
- constructor(baseStorage) {
1219
- this.baseStorage = baseStorage;
1220
- }
1221
- /**
1222
- * 注册插件存储 Schema
1223
- */
1224
- registerSchema(pluginId, schema) {
1225
- this.schemas.set(pluginId, schema);
1226
- }
1227
- /**
1228
- * 验证 Key 是否符合 Schema 定义 (仅在开发环境或严格模式下警告)
1229
- */
1230
- validateKey(pluginId, key, scope = "plugin") {
1231
- const schemaList = this.schemas.get(pluginId);
1232
- if (!schemaList) return;
1233
- const item = schemaList.find((s) => s.key === key);
1234
- if (!item) {
1235
- console.warn(`[Storage] Key "${key}" not defined in plugin "${pluginId}" schema.`);
1236
- return;
1237
- }
1238
- const definedScope = item.scope || "plugin";
1239
- if (definedScope !== scope) {
1240
- console.warn(`[Storage] Key "${key}" defined in scope "${definedScope}" but accessed via "${scope}".`);
1241
- }
1242
- }
1243
- /**
1244
- * 获取插件专用存储适配器
1245
- * @param pluginId 插件 ID
1246
- */
1247
- getPluginStorage(pluginId) {
1248
- return new ScopedStorageAdapter(this.baseStorage, `plugin:${pluginId}`);
1249
- }
1250
- /**
1251
- * 获取共享存储适配器
1252
- */
1253
- getSharedStorage() {
1254
- return new ScopedStorageAdapter(this.baseStorage, "shared");
1255
- }
1256
- /**
1257
- * 获取系统存储适配器
1258
- */
1259
- getSystemStorage() {
1260
- return new ScopedStorageAdapter(this.baseStorage, "system");
1261
- }
1262
- /**
1263
- * 获取插件上下文中的 storage 对象 (包含类型转换辅助方法)
1264
- * @param pluginId 插件 ID
1265
- */
1266
- getContextStorage(pluginId) {
1267
- const pluginStorage = this.getPluginStorage(pluginId);
1268
- const sharedStorage = this.getSharedStorage();
1269
- const createHelpers = (adapter, scope) => ({
1270
- get: (key) => {
1271
- this.validateKey(pluginId, key, scope);
1272
- try {
1273
- const val = adapter.getItem(key);
1274
- if (val !== null) {
1275
- try {
1276
- return JSON.parse(val);
1277
- } catch {
1278
- return val;
1279
- }
1280
- }
1281
- if (scope === "plugin") {
1282
- const externalConfig = configManager.get(pluginId);
1283
- if (externalConfig && externalConfig[key] !== void 0) {
1284
- return externalConfig[key];
1285
- }
1286
- }
1287
- const schema = this.schemas.get(pluginId)?.find((s) => s.key === key);
1288
- if (schema && schema.default !== void 0) {
1289
- return schema.default;
1290
- }
1291
- return null;
1292
- } catch (e) {
1293
- console.warn(`[Storage] Failed to read key "${key}"`, e);
1294
- return null;
1295
- }
1296
- },
1297
- set: (key, value) => {
1298
- this.validateKey(pluginId, key, scope);
1299
- try {
1300
- adapter.setItem(key, JSON.stringify(value));
1301
- } catch (e) {
1302
- console.warn(`[Storage] Failed to stringify key "${key}"`, e);
1303
- }
1304
- },
1305
- remove: (key) => {
1306
- this.validateKey(pluginId, key, scope);
1307
- adapter.removeItem(key);
1308
- }
1309
- });
1310
- return {
1311
- ...createHelpers(pluginStorage, "plugin"),
1312
- shared: createHelpers(sharedStorage, "shared")
1313
- };
1314
- }
1315
- };
1316
-
1317
- // src/domain/plugin-manager.ts
1318
- var logger7 = createLogger("PluginManager");
1319
- var PluginManager = class {
1320
- /** 全局事件总线 */
1321
- eventBus = new DefaultEventBus();
1322
- /** 存储接口 */
1323
- storageManager;
1324
- /** 所有插件运行时实例 */
1325
- runtimes = /* @__PURE__ */ new Map();
1326
- /** 所有注册的插件(原始数据) */
1327
- plugins = /* @__PURE__ */ new Map();
1328
- /** 收集的路由 */
1329
- routes = [];
1330
- /** 收集的扩展点 */
1331
- extensions = /* @__PURE__ */ new Map();
1332
- /** 插件状态管理(启用/禁用、排序) */
1333
- pluginStates = {};
1334
- /** 状态变更监听器 */
1335
- listeners = /* @__PURE__ */ new Set();
1336
- /** 共享上下文缓存 */
1337
- sharedContext = null;
1338
- /** 收集的工具函数 */
1339
- utils = {};
1340
- constructor(storage) {
1341
- this.storageManager = new StorageManager(storage);
1342
- this.loadStates();
1343
- this.subscribe(() => {
1344
- this.saveStates();
1345
- });
1346
- }
1347
- loadStates() {
1348
- try {
1349
- const systemStorage = this.storageManager.getSystemStorage();
1350
- const savedStates = systemStorage.getItem("plugin_states");
1351
- if (savedStates) {
1352
- this.pluginStates = JSON.parse(savedStates);
1353
- logger7.debug("\u4ECE\u7CFB\u7EDF\u5B58\u50A8\u4E2D\u52A0\u8F7D\u72B6\u6001:", this.pluginStates);
1354
- }
1355
- } catch (e) {
1356
- logger7.error("\u52A0\u8F7D\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:", e);
1357
- }
1358
- }
1359
- saveStates() {
1360
- try {
1361
- this.storageManager.getSystemStorage().setItem("plugin_states", JSON.stringify(this.pluginStates));
1362
- logger7.debug("\u5DF2\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5230\u5B58\u50A8");
1363
- } catch (e) {
1364
- logger7.error("\u4FDD\u5B58\u63D2\u4EF6\u72B6\u6001\u5931\u8D25:", e);
1365
- }
1366
- }
1367
- /**
1368
- * 订阅插件状态变更
1369
- * @param listener 监听函数
1370
- * @returns 取消订阅函数
1371
- */
1372
- subscribe(listener) {
1373
- this.listeners.add(listener);
1374
- return () => {
1375
- this.listeners.delete(listener);
1376
- };
1377
- }
1378
- getStorageManager() {
1379
- return this.storageManager;
1380
- }
1381
- /**
1382
- * 触发状态变更通知
1383
- */
1384
- notify() {
1385
- this.listeners.forEach((listener) => listener());
1386
- }
1387
- /**
1388
- * 获取所有已注册的插件
1389
- */
1390
- getPlugins() {
1391
- const typePriority = {
1392
- system: 0,
1393
- theme: 1,
1394
- renderer: 2,
1395
- functional: 3,
1396
- business: 4,
1397
- view: 5
1398
- };
1399
- return Array.from(this.plugins.values()).sort((a, b) => {
1400
- const priorityA = typePriority[a.metadata.type] ?? 99;
1401
- const priorityB = typePriority[b.metadata.type] ?? 99;
1402
- if (priorityA !== priorityB) {
1403
- return priorityA - priorityB;
1404
- }
1405
- const stateA = this.pluginStates[a.id] || { order: 0 };
1406
- const stateB = this.pluginStates[b.id] || { order: 0 };
1407
- return stateA.order - stateB.order;
1408
- });
1409
- }
1410
- /**
1411
- * 获取插件状态
1412
- * @param pluginId 插件 ID
1413
- */
1414
- getPluginState(pluginId) {
1415
- return this.pluginStates[pluginId] || { enabled: true, order: 0 };
1416
- }
1417
- /**
1418
- * 检查插件是否启用
1419
- * @param pluginId 插件 ID
1420
- */
1421
- isPluginEnabled(pluginId) {
1422
- const state = this.pluginStates[pluginId];
1423
- return state ? state.enabled : true;
1424
- }
1425
- /**
1426
- * 切换插件启用状态
1427
- * @param pluginId 插件 ID
1428
- * @param enabled 是否启用
1429
- */
1430
- togglePlugin(pluginId, enabled) {
1431
- const state = this.pluginStates[pluginId] || { enabled: true, order: 0 };
1432
- this.pluginStates[pluginId] = { ...state, enabled };
1433
- if (!enabled) {
1434
- const runtime = this.runtimes.get(pluginId);
1435
- if (runtime) {
1436
- runtime.unmount();
1437
- this.runtimes.delete(pluginId);
1438
- }
1439
- } else {
1440
- if (this.sharedContext) {
1441
- const plugin = this.plugins.get(pluginId);
1442
- if (plugin) {
1443
- try {
1444
- const runtime = new PluginRuntime(plugin, this.sharedContext, this.storageManager);
1445
- this.runtimes.set(pluginId, runtime);
1446
- runtime.mount();
1447
- } catch (e) {
1448
- logger7.error(`\u542F\u7528\u63D2\u4EF6 ${pluginId} \u5931\u8D25:`, e);
1449
- }
1450
- }
1451
- }
1452
- }
1453
- this.notify();
1454
- }
1455
- /**
1456
- * 设置插件排序
1457
- * @param pluginId 插件 ID
1458
- * @param order 排序值
1459
- */
1460
- setPluginOrder(pluginId, order) {
1461
- const state = this.pluginStates[pluginId] || { enabled: true, order: 0 };
1462
- this.pluginStates[pluginId] = { ...state, order };
1463
- this.notify();
1464
- }
1465
- /**
1466
- * 获取插件的统一能力描述
1467
- * @param pluginId 插件 ID
1468
- */
1469
- getUnifiedCapabilities(pluginId) {
1470
- const plugin = this.plugins.get(pluginId);
1471
- return plugin?.metadata.capabilities || {};
1472
- }
1473
- /**
1474
- * 更新插件配置
1475
- * @param pluginId 插件 ID
1476
- * @param key 配置项 Key
1477
- * @param value 配置值
1478
- */
1479
- updatePluginConfig(pluginId, key, value) {
1480
- const currentConfig = configManager.get(pluginId) || {};
1481
- currentConfig[key] = value;
1482
- configManager.set(pluginId, currentConfig);
1483
- try {
1484
- this.storageManager.getContextStorage(pluginId).set(key, value);
1485
- } catch (e) {
1486
- logger7.warn("\u4FDD\u5B58\u914D\u7F6E\u5230\u5B58\u50A8\u5931\u8D25", e);
1487
- }
1488
- this.eventBus.emit("config:changed", { pluginId, key, value });
1489
- }
1490
- /**
1491
- * 获取插件配置
1492
- * @param pluginId 插件 ID
1493
- * @param key 配置键
1494
- * @returns 配置值
1495
- */
1496
- getPluginConfig(pluginId, key) {
1497
- const config = configManager.get(pluginId);
1498
- return config ? config[key] : void 0;
1499
- }
1500
- /**
1501
- * 获取系统全局配置 (非插件特定配置)
1502
- * @param key 配置键 (如 title, version)
1503
- */
1504
- getSystemConfig(key) {
1505
- const systemConfig = configManager.get("system");
1506
- return systemConfig ? systemConfig[key] : void 0;
1507
- }
1508
- /**
1509
- * 获取注册的服务
1510
- * @param name 服务名称
1511
- */
1512
- getService(name) {
1513
- return serviceRegistry.get(name);
1514
- }
1515
- /**
1516
- * 获取指定插槽的扩展
1517
- * @param slot 插槽位置
1518
- */
1519
- getExtensions(slot) {
1520
- const targetSlot = slot;
1521
- let extensions = this.extensions.get(targetSlot) || [];
1522
- extensions = extensions.filter((ext) => {
1523
- const pluginId = ext._pluginId;
1524
- return !pluginId || this.isPluginEnabled(pluginId);
1525
- });
1526
- return extensions.sort((a, b) => (a.order || 0) - (b.order || 0));
1527
- }
1528
- getRoutes() {
1529
- const activeRoutes = [];
1530
- this.getPlugins().forEach((plugin) => {
1531
- if (this.isPluginEnabled(plugin.id) && plugin.metadata.routes) {
1532
- const config = configManager.get(plugin.id) || {};
1533
- plugin.metadata.routes.forEach((route) => {
1534
- activeRoutes.push({
1535
- ...route,
1536
- meta: {
1537
- ...route.meta,
1538
- pluginId: plugin.id,
1539
- config
1540
- }
1541
- });
1542
- });
1543
- }
1544
- });
1545
- return activeRoutes;
1546
- }
1547
- /**
1548
- * 注册插件
1549
- * @param plugin 插件实例
1550
- * @param notify 是否触发状态变更通知
1551
- */
1552
- register(plugin, notify = true) {
1553
- if (!this.validatePlugin(plugin)) {
1554
- logger7.error(`\u63D2\u4EF6\u6CE8\u518C\u5931\u8D25: ${plugin?.id || "\u672A\u77E5"}`);
1555
- return;
1556
- }
1557
- if (this.plugins.has(plugin.id)) {
1558
- return;
1559
- }
1560
- const storageSchema = [
1561
- ...plugin.metadata.storage || [],
1562
- ...plugin.metadata.configuration?.map((c) => ({
1563
- key: c.key,
1564
- // 将 configuration 的 type 映射为 storage 支持的类型
1565
- type: c.type === "select" ? "string" : c.type,
1566
- label: c.label,
1567
- description: c.description,
1568
- default: c.default,
1569
- scope: "plugin"
1570
- })) || []
1571
- ];
1572
- if (storageSchema.length > 0) {
1573
- this.storageManager.registerSchema(plugin.id, storageSchema);
1574
- }
1575
- if (!this.pluginStates[plugin.id]) {
1576
- this.pluginStates[plugin.id] = { enabled: true, order: 0 };
1577
- }
1578
- const metadataDefaults = {};
1579
- const userOverrides = {};
1580
- const pluginStorage = this.storageManager.getPluginStorage(plugin.id);
1581
- if (plugin.metadata.configuration) {
1582
- plugin.metadata.configuration.forEach((item) => {
1583
- if (item.default !== void 0) {
1584
- metadataDefaults[item.key] = item.default;
1585
- }
1586
- try {
1587
- const saved = pluginStorage.getItem(item.key);
1588
- if (saved !== null) {
1589
- userOverrides[item.key] = JSON.parse(saved);
1590
- }
1591
- } catch (e) {
1592
- }
1593
- });
1594
- }
1595
- const mergedConfig = {
1596
- ...metadataDefaults,
1597
- ...plugin.defaultConfig,
1598
- ...configManager.get(plugin.id) || {},
1599
- ...userOverrides
1600
- };
1601
- configManager.set(plugin.id, mergedConfig);
1602
- switch (plugin.metadata.type) {
1603
- case "business":
1604
- this.handleBusinessPlugin(plugin);
1605
- break;
1606
- case "functional":
1607
- this.handleFunctionalPlugin(plugin);
1608
- break;
1609
- case "view":
1610
- this.handleViewPlugin(plugin);
1611
- break;
1612
- case "theme":
1613
- this.handleThemePlugin(plugin);
1614
- break;
1615
- case "system":
1616
- this.handleSystemPlugin(plugin);
1617
- break;
1618
- case "renderer":
1619
- break;
1620
- default:
1621
- logger7.warn(`\u63D2\u4EF6 ${plugin.id} \u7C7B\u578B\u672A\u77E5: ${plugin.metadata.type}`);
1622
- break;
1623
- }
1624
- if (plugin.metadata.routes && plugin.metadata.routes.length > 0) {
1625
- logger7.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${plugin.id} \u6536\u96C6\u8DEF\u7531:`, plugin.metadata.routes);
1626
- }
1627
- if (plugin.metadata.extensions && plugin.metadata.extensions.length > 0) {
1628
- plugin.metadata.extensions.forEach((ext) => {
1629
- const list = this.extensions.get(ext.slot) || [];
1630
- list.push({ ...ext, _pluginId: plugin.id });
1631
- this.extensions.set(ext.slot, list);
1632
- });
1633
- logger7.info(`\u5DF2\u4ECE\u63D2\u4EF6 ${plugin.id} \u6536\u96C6\u6269\u5C55\u70B9`);
1634
- }
1635
- this.plugins.set(plugin.id, plugin);
1636
- logger7.info(`\u63D2\u4EF6 ${plugin.id} \u5DF2\u6CE8\u518C\u4E3A ${plugin.metadata.type}\u3002`);
1637
- if (notify) {
1638
- this.notify();
1639
- }
1640
- }
1641
- /**
1642
- * 初始化所有插件
1643
- * @param sharedContext 共享上下文
1644
- */
1645
- async initPlugins(sharedContext = {}) {
1646
- this.sharedContext = {
1647
- ...sharedContext,
1648
- events: this.eventBus
1649
- };
1650
- this.plugins.forEach((plugin) => {
1651
- if (!this.isPluginEnabled(plugin.id)) return;
1652
- if (!this.runtimes.has(plugin.id)) {
1653
- const runtime = new PluginRuntime(plugin, this.sharedContext, this.storageManager);
1654
- this.runtimes.set(plugin.id, runtime);
1655
- }
1656
- });
1657
- const sortedPluginIds = this.getSortedPluginIds();
1658
- for (const id of sortedPluginIds) {
1659
- const runtime = this.runtimes.get(id);
1660
- if (runtime) {
1661
- try {
1662
- await runtime.load();
1663
- } catch (e) {
1664
- logger7.error(`\u63D2\u4EF6 ${id} \u52A0\u8F7D\u5931\u8D25:`, e);
1665
- }
1666
- }
1667
- }
1668
- for (const id of sortedPluginIds) {
1669
- const runtime = this.runtimes.get(id);
1670
- if (runtime) {
1671
- try {
1672
- await runtime.mount();
1673
- } catch (e) {
1674
- logger7.error(`\u63D2\u4EF6 ${id} \u6302\u8F7D\u5931\u8D25:`, e);
1675
- }
1676
- }
1677
- }
1678
- }
1679
- /**
1680
- * 获取排序后的插件 ID 列表 (处理依赖)
1681
- */
1682
- getSortedPluginIds() {
1683
- const ids = Array.from(this.runtimes.keys());
1684
- const visited = /* @__PURE__ */ new Set();
1685
- const sorted = [];
1686
- const visiting = /* @__PURE__ */ new Set();
1687
- const visit = (id) => {
1688
- if (visited.has(id)) return;
1689
- if (visiting.has(id)) {
1690
- logger7.error(`\u5FAA\u73AF\u4F9D\u8D56\u68C0\u6D4B\u5230: ${id}`);
1691
- return;
1692
- }
1693
- visiting.add(id);
1694
- const plugin = this.plugins.get(id);
1695
- if (plugin?.metadata.dependencies) {
1696
- plugin.metadata.dependencies.forEach((depId) => {
1697
- if (this.runtimes.has(depId)) {
1698
- visit(depId);
1699
- }
1700
- });
1701
- }
1702
- visiting.delete(id);
1703
- visited.add(id);
1704
- sorted.push(id);
1705
- };
1706
- const priorityMap = {
1707
- "system": 100,
1708
- "functional": 50,
1709
- "business": 10
1710
- };
1711
- const sortedIdsByType = [...ids].sort((a, b) => {
1712
- const pA = priorityMap[this.plugins.get(a)?.metadata.type || ""] || 0;
1713
- const pB = priorityMap[this.plugins.get(b)?.metadata.type || ""] || 0;
1714
- return pB - pA;
1715
- });
1716
- sortedIdsByType.forEach((id) => visit(id));
1717
- return sorted;
1718
- }
1719
- /**
1720
- * 加载插件列表
1721
- * @param configs 插件配置
1722
- * @param registry 插件注册表 (动态导入函数)
1723
- */
1724
- async loadPlugins(configs, registry) {
1725
- logger7.info("\u5F00\u59CB\u52A0\u8F7D\u63D2\u4EF6...");
1726
- const localLoadPromises = Object.entries(registry).map(async ([registryId, importFn]) => {
1727
- try {
1728
- const module2 = await importFn();
1729
- const config = configs[registryId];
1730
- const plugin = this.instantiatePlugin(registryId, module2, config);
1731
- if (plugin && config) {
1732
- configManager.set(plugin.id, config);
1733
- }
1734
- return plugin;
1735
- } catch (e) {
1736
- logger7.error(`\u52A0\u8F7D\u672C\u5730\u63D2\u4EF6\u6A21\u5757 ${registryId} \u5931\u8D25:`, e);
1737
- return null;
1738
- }
1739
- });
1740
- const onlineLoadPromises = Object.entries(configs).filter(([id, config]) => config.url && !registry[id]).map(async ([pluginId, config]) => {
1741
- try {
1742
- const plugin = await this.loadRemotePlugin(pluginId, config.url, config);
1743
- if (plugin && config) {
1744
- configManager.set(plugin.id, config);
1745
- }
1746
- return plugin;
1747
- } catch (e) {
1748
- logger7.error(`\u52A0\u8F7D\u5728\u7EBF\u63D2\u4EF6 ${pluginId} \u5931\u8D25:`, e);
1749
- return null;
1750
- }
1751
- });
1752
- const loadedPlugins = await Promise.all([...localLoadPromises, ...onlineLoadPromises]);
1753
- loadedPlugins.forEach((plugin) => {
1754
- if (plugin) {
1755
- this.register(plugin, false);
1756
- }
1757
- });
1758
- this.notify();
1759
- logger7.info(`\u63D2\u4EF6\u52A0\u8F7D\u5B8C\u6210\uFF0C\u5171\u52A0\u8F7D ${this.plugins.size} \u4E2A\u63D2\u4EF6`);
1760
- }
1761
- /**
1762
- * 加载远程插件
1763
- * @param pluginId 插件 ID
1764
- * @param url 远程 URL
1765
- * @param config 插件配置
1766
- */
1767
- async loadRemotePlugin(pluginId, url, config) {
1768
- logger7.info(`\u6B63\u5728\u4ECE ${url} \u52A0\u8F7D\u8FDC\u7A0B\u63D2\u4EF6 ${pluginId}...`);
1769
- try {
1770
- const module2 = await import(
1771
- /* @vite-ignore */
1772
- url
1773
- );
1774
- return this.instantiatePlugin(pluginId, module2, config);
1775
- } catch (e) {
1776
- logger7.warn(`ESM \u52A0\u8F7D\u5931\u8D25\uFF0C\u5C1D\u8BD5 IIFE \u52A0\u8F7D: ${pluginId}`);
1777
- return new Promise((resolve, reject) => {
1778
- const script = document.createElement("script");
1779
- script.src = url;
1780
- script.onload = () => {
1781
- const globalName = pluginId.replace(/[^a-zA-Z0-9]/g, "_");
1782
- const pluginModule = window[globalName];
1783
- if (pluginModule) {
1784
- resolve(this.instantiatePlugin(pluginId, pluginModule, config));
1785
- } else {
1786
- reject(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${pluginId} \u52A0\u8F7D\u540E\u672A\u627E\u5230\u5168\u5C40\u53D8\u91CF ${globalName}`));
1787
- }
1788
- };
1789
- script.onerror = () => reject(new Error(`\u8FDC\u7A0B\u63D2\u4EF6 ${pluginId} \u52A0\u8F7D\u5931\u8D25: ${url}`));
1790
- document.head.appendChild(script);
1791
- });
1792
- }
1793
- }
1794
- /**
1795
- * 实例化插件
1796
- */
1797
- instantiatePlugin(pluginId, module2, config) {
1798
- let PluginClass = module2.default;
1799
- if (!PluginClass) {
1800
- const key = Object.keys(module2).find((k) => k.endsWith("Plugin"));
1801
- if (key) PluginClass = module2[key];
1802
- }
1803
- if (!PluginClass && typeof module2 === "object") {
1804
- if (module2.id && module2.metadata) {
1805
- PluginClass = module2;
1806
- }
1807
- }
1808
- if (PluginClass) {
1809
- const isClass = typeof PluginClass === "function" && PluginClass.prototype;
1810
- if (isClass) {
1811
- logger7.warn(`\u63D2\u4EF6 ${pluginId} \u4F7F\u7528\u4E86\u7C7B\u5B9A\u4E49\u6A21\u5F0F\u3002\u5EFA\u8BAE\u7EDF\u4E00\u4F7F\u7528 definePlugin() \u5DE5\u5382\u6A21\u5F0F\u4EE5\u6D88\u9664\u6B67\u4E49\u5E76\u7B80\u5316\u4EE3\u7801\u3002`);
1812
- }
1813
- const pluginInstance = typeof PluginClass === "function" ? new PluginClass() : PluginClass;
1814
- if (pluginId && pluginInstance.metadata) {
1815
- if (pluginInstance.metadata.id !== pluginId) {
1816
- pluginInstance.metadata.id = pluginId;
1817
- }
1818
- }
1819
- if (!pluginInstance.id && pluginInstance.metadata?.id) {
1820
- try {
1821
- pluginInstance.id = pluginInstance.metadata.id;
1822
- } catch (e) {
1823
- }
1824
- }
1825
- if (config) {
1826
- pluginInstance.defaultConfig = { ...pluginInstance.defaultConfig, ...config };
1827
- }
1828
- return pluginInstance;
1829
- }
1830
- logger7.warn(`\u6A21\u5757 ${pluginId} \u672A\u5BFC\u51FA\u6709\u6548\u7684\u63D2\u4EF6\u5165\u53E3`);
1831
- return null;
1832
- }
1833
- // --- Private Handlers ---
1834
- validatePlugin(plugin) {
1835
- if (!plugin.id) return false;
1836
- if (!plugin.metadata) return false;
1837
- return true;
1838
- }
1839
- handleBusinessPlugin(plugin) {
1840
- }
1841
- handleFunctionalPlugin(plugin) {
1842
- }
1843
- handleViewPlugin(plugin) {
1844
- }
1845
- handleThemePlugin(plugin) {
1846
- }
1847
- handleSystemPlugin(plugin) {
1848
- }
1849
- };
1850
- var pluginManager = new PluginManager(new LocalStorageAdapter());
1851
-
1852
- // src/components/PluginSlot.tsx
1853
- var import_jsx_runtime3 = require("react/jsx-runtime");
1854
- var PluginSlot = ({
1855
- slot,
1856
- props = {},
1857
- className,
1858
- style,
1859
- renderItem,
1860
- skeleton,
1861
- fallback
1862
- }) => {
1863
- const extensions = pluginManager.getExtensions(slot);
1864
- const systemConfig = pluginManager.getSystemConfig("title") ? {
1865
- title: pluginManager.getSystemConfig("title"),
1866
- logo: pluginManager.getSystemConfig("logo"),
1867
- version: pluginManager.getSystemConfig("version")
1868
- } : void 0;
1869
- const mergedProps = (0, import_react3.useMemo)(() => ({
1870
- ...props,
1871
- systemConfig
1872
- }), [props, systemConfig]);
1873
- const items = (0, import_react3.useMemo)(() => {
1874
- return extensions.map((ext, index) => {
1875
- const Component2 = ext.component;
1876
- const key = ext.meta?.key || `${ext.slot}-${ext.order || 0}-${index}`;
1877
- return {
1878
- key,
1879
- extension: ext,
1880
- component: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(PluginErrorBoundary, { pluginId: `extension-${key}`, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Component2, { ...mergedProps }) }, key)
1881
- };
1882
- });
1883
- }, [extensions, mergedProps]);
1884
- if (items.length === 0) {
1885
- if (fallback) {
1886
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: fallback });
1887
- }
1888
- if (skeleton) {
1889
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: `plugin-slot plugin-slot-${slot} plugin-slot-skeleton ${className || ""}`, style, children: skeleton });
1890
- }
1891
- return null;
1892
- }
1893
- if (items.length === 1 && slot === "root-layout" && !className && !style && !renderItem) {
1894
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: items[0].component });
1895
- }
1896
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: `plugin-slot plugin-slot-${slot} ${className || ""}`, style, children: renderItem ? items.map((item, index) => renderItem(item, index)) : items.map((item) => item.component) });
1897
- };
1898
-
1899
- // src/components/SlotSkeletons.tsx
1900
- var import_jsx_runtime4 = require("react/jsx-runtime");
1901
- var SidebarIconSkeleton = ({ expanded = false }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: `flex items-center transition-all duration-300 relative
1902
- ${expanded ? "w-full" : "w-12 justify-center"} px-3 h-11 rounded-xl`, children: [
1903
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "w-6 h-6 bg-slate-200 dark:bg-white/10 rounded-lg shrink-0 animate-pulse" }),
1904
- expanded && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "ml-3 flex-1 h-4 bg-slate-200 dark:bg-white/10 rounded animate-pulse" })
1905
- ] });
1906
- var StatusBarItemSkeleton = () => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "h-4 w-16 bg-slate-200 dark:bg-white/10 rounded animate-pulse" });
1907
- var AvatarSkeleton = () => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "w-10 h-10 rounded-full bg-slate-200 dark:bg-white/10 animate-pulse" });
1908
- var BlockSkeleton = ({ className }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: `bg-slate-200 dark:bg-white/10 rounded animate-pulse ${className || "w-full h-full"}` });
1909
-
1910
- // src/domain/auto-loader.ts
1911
- var logger8 = createLogger("AutoLoader");
1912
- var DEFAULT_RULES = [
1913
- { pathSegment: "@chatbi-plugins", idPrefix: "@chatbi-v/plugin" },
1914
- { pathSegment: "@chatbi-apps", idPrefix: "@chatbi-v/app" },
1915
- { pathSegment: "packages/plugins", idPrefix: "@chatbi-v/plugin" },
1916
- { pathSegment: "packages/apps", idPrefix: "@chatbi-v/app" }
1917
- ];
1918
- var resolvePluginRegistry = (options) => {
1919
- const { modules, rules = DEFAULT_RULES } = options;
1920
- const registry = {};
1921
- const compiledRules = rules.map((rule) => {
1922
- const escapedSegment = rule.pathSegment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1923
- return {
1924
- ...rule,
1925
- regex: new RegExp(`${escapedSegment}/([^/]+)/src/index`)
1926
- };
1927
- });
1928
- for (const path in modules) {
1929
- try {
1930
- let pluginId = null;
1931
- for (const rule of compiledRules) {
1932
- const match = path.match(rule.regex);
1933
- if (match && match[1]) {
1934
- pluginId = `${rule.idPrefix}-${match[1]}`;
1935
- logger8.info(`\u89E3\u6790\u8DEF\u5F84\u6210\u529F: ${path} -> ${pluginId}`);
1936
- break;
1937
- }
1938
- }
1939
- if (pluginId) {
1940
- registry[pluginId] = modules[path];
1941
- } else {
1942
- logger8.warn(`\u65E0\u6CD5\u4ECE\u8DEF\u5F84\u89E3\u6790\u63D2\u4EF6 ID: ${path}\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u7B26\u5408\u547D\u540D\u7EA6\u5B9A\u3002`);
1943
- }
1944
- } catch (e) {
1945
- logger8.error(`\u89E3\u6790\u63D2\u4EF6\u8DEF\u5F84\u5931\u8D25: ${path}`, e);
1946
- }
1947
- }
1948
- return registry;
1949
- };
1950
-
1951
- // src/domain/models.ts
1952
- var SUCCESS_CODE = "000000";
1953
-
1954
- // src/plugin-context.tsx
1955
- var import_react4 = require("react");
1956
- var import_jsx_runtime5 = require("react/jsx-runtime");
1957
- var PluginContext = (0, import_react4.createContext)(null);
1958
- var PluginProvider = ({ manager, children }) => {
1959
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(PluginContext.Provider, { value: manager, children });
1960
- };
1961
- var usePluginManager = () => {
1962
- const context = (0, import_react4.useContext)(PluginContext);
1963
- if (!context) {
1964
- throw new Error("usePluginManager must be used within a PluginProvider");
1965
- }
1966
- return context;
1967
- };
1968
-
1969
- // src/api/adapters/axios-adapter.ts
1970
- var import_axios = __toESM(require("axios"));
1971
- var AxiosAdapter = class {
1972
- client;
1973
- constructor(baseURL = "/api", timeout = 1e4) {
1974
- this.client = import_axios.default.create({
1975
- baseURL,
1976
- timeout
1977
- });
1978
- this.client.interceptors.response.use(
1979
- (response) => response,
1980
- (error) => Promise.reject(error)
1981
- );
1982
- }
1983
- async request(config) {
1984
- return this.client.request(config);
1985
- }
1986
- async stream(config, callbacks, endpointConfig) {
1987
- const { onMessage, onError, onFinish } = callbacks;
1988
- try {
1989
- const baseURL = this.client.defaults.baseURL || "";
1990
- let url = config.url;
1991
- if (url && !url.startsWith("http") && baseURL) {
1992
- const cleanBase = baseURL.endsWith("/") ? baseURL.slice(0, -1) : baseURL;
1993
- const cleanUrl = url.startsWith("/") ? url : `/${url}`;
1994
- url = `${cleanBase}${cleanUrl}`;
1995
- }
1996
- if (config.params) {
1997
- const params = new URLSearchParams();
1998
- Object.entries(config.params).forEach(([key, value]) => {
1999
- if (value !== void 0) params.append(key, String(value));
2000
- });
2001
- url += (url.includes("?") ? "&" : "?") + params.toString();
2002
- }
2003
- const headers = {
2004
- ...this.client.defaults.headers.common || {},
2005
- "Content-Type": "application/json",
2006
- ...config.headers || {}
2007
- };
2008
- const defaultHeaders = this.client.defaults.headers;
2009
- if (defaultHeaders.Authorization) {
2010
- headers["Authorization"] = defaultHeaders.Authorization;
2011
- }
2012
- if (defaultHeaders["x-token"]) {
2013
- headers["x-token"] = defaultHeaders["x-token"];
2014
- }
2015
- const { signal, ...otherConfig } = config;
2016
- const response = await fetch(url, {
2017
- method: config.method,
2018
- headers,
2019
- body: config.data ? JSON.stringify(config.data) : void 0,
2020
- signal
2021
- });
2022
- if (!response.ok) {
2023
- throw new Error(`HTTP error! status: ${response.status}`);
2024
- }
2025
- if (!response.body) {
2026
- throw new Error("\u54CD\u5E94\u4F53\u4E3A\u7A7A");
2027
- }
2028
- const reader = response.body.getReader();
2029
- const decoder = new TextDecoder();
2030
- let buffer = "";
2031
- while (true) {
2032
- const { done, value } = await reader.read();
2033
- if (done) break;
2034
- buffer += decoder.decode(value, { stream: true });
2035
- const parts = buffer.split("\n\n");
2036
- buffer = parts.pop() || "";
2037
- for (const part of parts) {
2038
- if (onMessage) {
2039
- onMessage(part + "\n\n");
2040
- }
2041
- }
2042
- }
2043
- if (buffer && onMessage) {
2044
- onMessage(buffer);
2045
- }
2046
- if (onFinish) onFinish();
2047
- } catch (error) {
2048
- if (onError) onError(error);
2049
- }
2050
- }
2051
- };
2052
-
2053
- // src/api/engine.ts
2054
- var logger9 = createLogger("ApiEngine");
2055
- var ApiEngine = class {
2056
- adapter;
2057
- config = {};
2058
- interceptors = [];
2059
- constructor(adapter) {
2060
- this.adapter = adapter || new AxiosAdapter();
2061
- }
2062
- /**
2063
- * 注册拦截器
2064
- */
2065
- registerInterceptor(interceptor) {
2066
- this.interceptors.push(interceptor);
2067
- }
2068
- /**
2069
- * 移除拦截器
2070
- */
2071
- unregisterInterceptor(interceptor) {
2072
- this.interceptors = this.interceptors.filter((i) => i !== interceptor);
2073
- }
2074
- /**
2075
- * 切换请求适配器
2076
- * @param adapter 新的适配器实例
2077
- */
2078
- useAdapter(adapter) {
2079
- this.adapter = adapter;
2080
- }
2081
- /**
2082
- * 注册 API 配置
2083
- * @param config 配置对象
2084
- */
2085
- register(config) {
2086
- logger9.info("\u6B63\u5728\u6CE8\u518C API \u914D\u7F6E:", Object.keys(config));
2087
- this.config = { ...this.config, ...config };
2088
- }
2089
- /**
2090
- * 获取接口配置
2091
- */
2092
- getEndpoint(module2, action) {
2093
- return this.config[module2]?.[action];
2094
- }
2095
- /**
2096
- * 发起 API 请求
2097
- * @param module 模块名
2098
- * @param action 动作名
2099
- * @param data 请求数据 (Body 或 Query)
2100
- * @param options 请求选项
2101
- */
2102
- async call(module2, action, data, options = {}) {
2103
- const endpoint = this.getEndpoint(module2, action);
2104
- if (!endpoint) {
2105
- logger9.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${module2}.${action} (\u5F53\u524D\u5DF2\u6CE8\u518C\u6A21\u5757: ${Object.keys(this.config).join(", ")})`);
2106
- return Promise.resolve(void 0);
2107
- }
2108
- let requestConfig = await this.prepareRequestConfig(endpoint, data, options);
2109
- let response;
2110
- try {
2111
- response = await this.adapter.request(requestConfig, endpoint);
2112
- } catch (error) {
2113
- if (error.response) {
2114
- response = error.response;
2115
- } else {
2116
- throw error;
2117
- }
2118
- }
2119
- if (this.interceptors.length > 0) {
2120
- const context = this.createInterceptorContext(response, requestConfig);
2121
- for (const interceptor of this.interceptors) {
2122
- if (interceptor.interceptResponse) {
2123
- const hijacked = await interceptor.interceptResponse(context);
2124
- if (hijacked) {
2125
- logger9.info("\u8BF7\u6C42\u88AB\u62E6\u622A\u5668\u52AB\u6301:", module2, action);
2126
- return void 0;
2127
- }
2128
- }
2129
- }
2130
- }
2131
- if (response && response.status && (response.status < 200 || response.status >= 300)) {
2132
- const responseData2 = this.isAxiosResponse(response) ? response.data : response;
2133
- const isBaseResponse = this.isBaseResponse(responseData2);
2134
- if (!isBaseResponse) {
2135
- throw new Error(`Request failed with status ${response.status}`);
2136
- }
2137
- }
2138
- const responseData = this.isAxiosResponse(response) ? response.data : response;
2139
- if (this.isBaseResponse(responseData)) {
2140
- const res = responseData;
2141
- const code = String(res.code);
2142
- const isSuccess = code === SUCCESS_CODE || code === "200" || code === "0";
2143
- if (!isSuccess) {
2144
- const strategy = endpoint.errorStrategy || "reject";
2145
- if (strategy === "reject") {
2146
- logger9.error(`API \u8BF7\u6C42\u4E1A\u52A1\u9519\u8BEF (${module2}.${action}):`, res.message);
2147
- throw new Error(res.message || `Request failed with code ${code}`);
2148
- }
2149
- }
2150
- }
2151
- return responseData;
2152
- }
2153
- /**
2154
- * 发起流式请求
2155
- * @param module 模块名
2156
- * @param action 动作名
2157
- * @param data 请求数据
2158
- * @param options 请求选项
2159
- */
2160
- async stream(module2, action, data, options = {}) {
2161
- const endpoint = this.getEndpoint(module2, action);
2162
- if (!endpoint) {
2163
- logger9.warn(`\u672A\u627E\u5230 API \u5B9A\u4E49: ${module2}.${action}\uFF0C\u8DF3\u8FC7\u6D41\u5F0F\u8BF7\u6C42\u3002`);
2164
- return;
2165
- }
2166
- if (!this.adapter.stream) {
2167
- logger9.warn("\u5F53\u524D API \u9002\u914D\u5668\u4E0D\u652F\u6301\u6D41\u5F0F\u4F20\u8F93\u3002");
2168
- return;
2169
- }
2170
- const requestConfig = await this.prepareRequestConfig(endpoint, data, options);
2171
- const callbacks = {
2172
- onMessage: options.onMessage,
2173
- onError: options.onError,
2174
- onFinish: options.onFinish
2175
- };
2176
- await this.adapter.stream(requestConfig, callbacks, endpoint);
2177
- }
2178
- /**
2179
- * 准备请求配置,应用 URL 参数替换和拦截器
2180
- */
2181
- async prepareRequestConfig(endpoint, data, options) {
2182
- let url = endpoint.url;
2183
- const pathParams = options.params || {};
2184
- url = url.replace(/:([a-zA-Z0-9_]+)/g, (_, key) => {
2185
- if (pathParams[key] !== void 0) return String(pathParams[key]);
2186
- if (data && typeof data === "object" && data[key] !== void 0) return String(data[key]);
2187
- return `:${key}`;
2188
- });
2189
- const method = endpoint.method;
2190
- let requestConfig = {
2191
- ...options,
2192
- url,
2193
- method
2194
- };
2195
- if (method === "GET" || method === "DELETE") {
2196
- requestConfig.params = data;
2197
- } else {
2198
- requestConfig.data = data;
2199
- }
2200
- if (this.interceptors.length > 0) {
2201
- for (const interceptor of this.interceptors) {
2202
- if (interceptor.interceptRequest) {
2203
- requestConfig = await interceptor.interceptRequest(requestConfig);
2204
- }
2205
- }
2206
- }
2207
- return requestConfig;
2208
- }
2209
- /**
2210
- * 判断是否为 BaseResponse
2211
- */
2212
- isBaseResponse(data) {
2213
- return data && typeof data === "object" && "code" in data && ("message" in data || "data" in data);
2214
- }
2215
- /**
2216
- * 严格判断是否为 AxiosResponse
2217
- */
2218
- isAxiosResponse(res) {
2219
- return res && typeof res === "object" && "data" in res && "status" in res && "headers" in res;
2220
- }
2221
- /**
2222
- * 创建拦截上下文
2223
- */
2224
- createInterceptorContext(response, config) {
2225
- if (response && typeof response === "object" && "status" in response && "headers" in response) {
2226
- return {
2227
- response,
2228
- status: response.status,
2229
- headers: response.headers,
2230
- data: response.data,
2231
- config
2232
- };
2233
- }
2234
- return {
2235
- response,
2236
- status: 200,
2237
- headers: {},
2238
- data: response,
2239
- config
2240
- };
2241
- }
2242
- };
2243
- var apiEngine = new ApiEngine();
2244
-
2245
- // src/utils/url.ts
2246
- function normalizeParams(strategy = "last") {
2247
- if (typeof window === "undefined") return new URLSearchParams();
2248
- const { search, hash } = window.location;
2249
- const searchParams = new URLSearchParams(search);
2250
- const hashParams = new URLSearchParams(hash.split("?")[1] || "");
2251
- const entries = [];
2252
- searchParams.forEach((v, k) => entries.push([k, v, "search"]));
2253
- hashParams.forEach((v, k) => entries.push([k, v, "hash"]));
2254
- const keeper = /* @__PURE__ */ new Map();
2255
- if (strategy === "first") {
2256
- entries.forEach(([k, v]) => {
2257
- if (!keeper.has(k)) keeper.set(k, v);
2258
- });
2259
- } else if (strategy === "last") {
2260
- entries.forEach(([k, v]) => keeper.set(k, v));
2261
- } else if (strategy === "search") {
2262
- entries.forEach(([k, v, src]) => {
2263
- if (src === "search") keeper.set(k, v);
2264
- });
2265
- hashParams.forEach((v, k) => {
2266
- if (!keeper.has(k)) keeper.set(k, v);
2267
- });
2268
- } else if (strategy === "hash") {
2269
- entries.forEach(([k, v, src]) => {
2270
- if (src === "hash") keeper.set(k, v);
2271
- });
2272
- searchParams.forEach((v, k) => {
2273
- if (!keeper.has(k)) keeper.set(k, v);
2274
- });
2275
- }
2276
- return new URLSearchParams(Array.from(keeper.entries()));
2277
- }
2278
- function cleanUrlParams(keysToRemove) {
2279
- if (typeof window === "undefined") return "";
2280
- const { pathname, search, hash } = window.location;
2281
- const searchParams = new URLSearchParams(search);
2282
- keysToRemove.forEach((key) => searchParams.delete(key));
2283
- const newSearch = searchParams.toString();
2284
- const hashParts = hash.split("?");
2285
- const hashPath = hashParts[0];
2286
- const hashQuery = hashParts[1] || "";
2287
- const hashParams = new URLSearchParams(hashQuery);
2288
- keysToRemove.forEach((key) => hashParams.delete(key));
2289
- const newHashQuery = hashParams.toString();
2290
- const newHash = hashPath + (newHashQuery ? "?" + newHashQuery : "");
2291
- return pathname + (newSearch ? "?" + newSearch : "") + newHash;
2292
- }
2293
-
2294
- // src/api/utils.ts
2295
- var mergeMockData = (def, mock) => {
2296
- const merged = JSON.parse(JSON.stringify(def));
2297
- Object.keys(mock).forEach((key) => {
2298
- if (merged[key]) {
2299
- merged[key] = {
2300
- ...merged[key],
2301
- ...mock[key]
2302
- };
2303
- }
2304
- });
2305
- return merged;
2306
- };
2307
- function isMockMode() {
2308
- const envMock = typeof process !== "undefined" && process.env.VITE_USE_MOCK === "true" || typeof window !== "undefined" && window.VITE_USE_MOCK === "true";
2309
- if (typeof window !== "undefined") {
2310
- const params = normalizeParams();
2311
- const mockParam = params.get("mock");
2312
- if (mockParam === "true") return true;
2313
- if (mockParam === "false") return false;
2314
- }
2315
- return envMock;
2316
- }
2317
- function resolveApiModules(definitionsMap, mocksMap = {}) {
2318
- const config = {};
2319
- const getNamespace = (path) => {
2320
- const fileName = path.split("/").pop() || "";
2321
- return fileName.replace(/\.mock\.(ts|js|tsx|jsx|json)$/, "").replace(/\.(ts|js|tsx|jsx|json)$/, "");
2322
- };
2323
- Object.entries(definitionsMap).forEach(([path, module2]) => {
2324
- if (path.includes(".mock.")) return;
2325
- const namespace = getNamespace(path);
2326
- if (!namespace || !module2.default) return;
2327
- let apiDef = module2.default;
2328
- const mockEntry = Object.entries(mocksMap).find(([mockPath]) => {
2329
- return getNamespace(mockPath) === namespace && mockPath.includes(".mock.");
2330
- });
2331
- if (mockEntry) {
2332
- const mockModule = mockEntry[1];
2333
- const mockData = mockModule.default || mockModule;
2334
- if (mockData) {
2335
- apiDef = mergeMockData(apiDef, mockData);
2336
- }
2337
- }
2338
- config[namespace] = apiDef;
2339
- });
2340
- return config;
2341
- }
2342
-
2343
- // src/utils/date.ts
2344
- var import_dayjs = __toESM(require_dayjs_min());
2345
- var import_relativeTime = __toESM(require_relativeTime());
2346
- var import_zh_cn = __toESM(require_zh_cn());
2347
- import_dayjs.default.extend(import_relativeTime.default);
2348
- import_dayjs.default.locale("zh-cn");
2349
- var dateUtils = {
2350
- /**
2351
- * 格式化日期为 YYYY-MM-DD
2352
- */
2353
- formatDate(date) {
2354
- return (0, import_dayjs.default)(date).format("YYYY-MM-DD");
2355
- },
2356
- /**
2357
- * 格式化时间为 HH:mm:ss
2358
- */
2359
- formatTime(date) {
2360
- return (0, import_dayjs.default)(date).format("HH:mm:ss");
2361
- },
2362
- /**
2363
- * 格式化日期时间为 YYYY-MM-DD HH:mm:ss
2364
- */
2365
- formatDateTime(date) {
2366
- return (0, import_dayjs.default)(date).format("YYYY-MM-DD HH:mm:ss");
2367
- },
2368
- /**
2369
- * 获取当前时间戳(毫秒)
2370
- */
2371
- now() {
2372
- return (0, import_dayjs.default)().valueOf();
2373
- },
2374
- /**
2375
- * 获取相对时间(例如:几分钟前)
2376
- */
2377
- fromNow(date) {
2378
- return (0, import_dayjs.default)(date).fromNow();
2379
- },
2380
- /**
2381
- * 原始 dayjs 对象,用于更复杂的场景
2382
- */
2383
- dayjs: import_dayjs.default
2384
- };
2385
-
2386
- // src/utils/index.ts
2387
- var version = "1.0.0";
2388
-
2389
- // src/hooks/use-storage-state.ts
2390
- var import_react5 = require("react");
2391
- function useStorageState(pluginId, key, options = {}) {
2392
- const { defaultValue, scope = "plugin" } = options;
2393
- const storageManager = pluginManager.getStorageManager();
2394
- const getStorage = (0, import_react5.useCallback)(() => {
2395
- const contextStorage = storageManager.getContextStorage(pluginId);
2396
- return scope === "shared" ? contextStorage.shared : contextStorage;
2397
- }, [pluginId, scope, storageManager]);
2398
- const [state, setState] = (0, import_react5.useState)(() => {
2399
- try {
2400
- if (typeof window === "undefined") return defaultValue;
2401
- const storage = getStorage();
2402
- const val = storage.get(key);
2403
- return val !== null ? val : defaultValue;
2404
- } catch (e) {
2405
- console.warn(`[useStorageState] Error reading key "${key}"`, e);
2406
- return defaultValue;
2407
- }
2408
- });
2409
- const setValue = (0, import_react5.useCallback)((value) => {
2410
- try {
2411
- const valueToStore = value instanceof Function ? value(state) : value;
2412
- setState(valueToStore);
2413
- const storage = getStorage();
2414
- storage.set(key, valueToStore);
2415
- } catch (error) {
2416
- console.warn(`[useStorageState] Error setting key "${key}":`, error);
2417
- }
2418
- }, [key, state, getStorage]);
2419
- return [state, setValue];
2420
- }
2421
-
2422
- // src/hooks/use-plugin-loader.ts
2423
- var import_react6 = require("react");
2424
- var logger10 = createLogger("PluginLoader");
2425
- var usePluginLoader = (options) => {
2426
- const [pluginsLoaded, setPluginsLoaded] = (0, import_react6.useState)(false);
2427
- const [pluginVersion, setPluginVersion] = (0, import_react6.useState)(0);
2428
- const loadingRef = (0, import_react6.useRef)(false);
2429
- (0, import_react6.useEffect)(() => {
2430
- const unsubscribe = pluginManager.subscribe(() => {
2431
- logger10.debug("Plugin state changed, refreshing UI...");
2432
- setPluginVersion((v) => v + 1);
2433
- });
2434
- const load = async () => {
2435
- if (loadingRef.current || pluginsLoaded) return;
2436
- loadingRef.current = true;
2437
- try {
2438
- const {
2439
- discoveryRules = [],
2440
- modules = {},
2441
- registry: manualRegistry = {},
2442
- pluginConfigs,
2443
- sharedContext = {},
2444
- baseUrl = window.location.origin
2445
- } = options;
2446
- logger10.info("Starting to load plugins...");
2447
- const discoveredRegistry = Object.keys(modules).length > 0 ? resolvePluginRegistry({
2448
- modules,
2449
- rules: discoveryRules.length > 0 ? discoveryRules : void 0
2450
- }) : {};
2451
- const finalRegistry = { ...discoveredRegistry, ...manualRegistry };
2452
- if (options.systemConfig) {
2453
- const { configManager: configManager2 } = await Promise.resolve().then(() => (init_config_manager(), config_manager_exports));
2454
- configManager2.set("system", options.systemConfig);
2455
- }
2456
- await pluginManager.loadPlugins(pluginConfigs, finalRegistry);
2457
- await pluginManager.initPlugins(sharedContext);
2458
- setPluginsLoaded(true);
2459
- logger10.info("Plugins loaded successfully");
2460
- } catch (error) {
2461
- logger10.error("Failed to load plugins:", error);
2462
- } finally {
2463
- loadingRef.current = false;
2464
- }
2465
- };
2466
- load();
2467
- return () => {
2468
- unsubscribe();
2469
- };
2470
- }, []);
2471
- return {
2472
- pluginsLoaded,
2473
- pluginVersion
2474
- };
2475
- };
2476
- // Annotate the CommonJS export names for ESM import in node:
2477
- 0 && (module.exports = {
2478
- ApiEngine,
2479
- ApiProvider,
2480
- AvatarSkeleton,
2481
- AxiosAdapter,
2482
- BasePlugin,
2483
- BlockSkeleton,
2484
- ConfigManager,
2485
- DefaultEventBus,
2486
- LocalStorageAdapter,
2487
- LogLevel,
2488
- Logger,
2489
- PLUGIN_TYPES,
2490
- PluginErrorBoundary,
2491
- PluginManager,
2492
- PluginProvider,
2493
- PluginRuntime,
2494
- PluginSandbox,
2495
- PluginSlot,
2496
- SUCCESS_CODE,
2497
- ScopedStorageAdapter,
2498
- ServiceRegistry,
2499
- SidebarIconSkeleton,
2500
- Slot,
2501
- StatusBarItemSkeleton,
2502
- StorageManager,
2503
- apiEngine,
2504
- cleanUrlParams,
2505
- configManager,
2506
- createLogger,
2507
- dateUtils,
2508
- definePlugin,
2509
- isMockMode,
2510
- logger,
2511
- normalizeParams,
2512
- pluginManager,
2513
- resolveApiModules,
2514
- resolvePluginRegistry,
2515
- serviceRegistry,
2516
- useApi,
2517
- usePluginLoader,
2518
- usePluginManager,
2519
- useStorageState,
2520
- version
2521
- });