@chatbi-v/core 2.0.1 → 2.0.3

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