@chatbi-v/core 1.0.2

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