@oxog/utils 1.0.0 → 1.1.0

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 (43) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +101 -43
  3. package/dist/chunk-25WW2FCA.js +34 -0
  4. package/dist/chunk-25WW2FCA.js.map +1 -0
  5. package/dist/chunk-DEVWOLUI.cjs +112 -0
  6. package/dist/chunk-DEVWOLUI.cjs.map +1 -0
  7. package/dist/chunk-IUDFQZIP.js +99 -0
  8. package/dist/chunk-IUDFQZIP.js.map +1 -0
  9. package/dist/chunk-PZ5AY32C.js +9 -0
  10. package/dist/chunk-PZ5AY32C.js.map +1 -0
  11. package/dist/chunk-Q7SFCCGT.cjs +11 -0
  12. package/dist/chunk-Q7SFCCGT.cjs.map +1 -0
  13. package/dist/chunk-SWG777R6.cjs +40 -0
  14. package/dist/chunk-SWG777R6.cjs.map +1 -0
  15. package/dist/index.cjs +482 -191
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +288 -15
  18. package/dist/index.d.ts +288 -15
  19. package/dist/index.js +428 -186
  20. package/dist/index.js.map +1 -1
  21. package/dist/plugins/async.cjs +90 -107
  22. package/dist/plugins/async.cjs.map +1 -1
  23. package/dist/plugins/async.d.cts +19 -6
  24. package/dist/plugins/async.d.ts +19 -6
  25. package/dist/plugins/async.js +89 -106
  26. package/dist/plugins/async.js.map +1 -1
  27. package/dist/plugins/deep.cjs +183 -59
  28. package/dist/plugins/deep.cjs.map +1 -1
  29. package/dist/plugins/deep.d.cts +25 -7
  30. package/dist/plugins/deep.d.ts +25 -7
  31. package/dist/plugins/deep.js +183 -59
  32. package/dist/plugins/deep.js.map +1 -1
  33. package/dist/plugins/guard.cjs +2 -0
  34. package/dist/plugins/guard.cjs.map +1 -1
  35. package/dist/plugins/guard.js +2 -0
  36. package/dist/plugins/guard.js.map +1 -1
  37. package/dist/plugins/transform.cjs +6 -3
  38. package/dist/plugins/transform.cjs.map +1 -1
  39. package/dist/plugins/transform.js +6 -3
  40. package/dist/plugins/transform.js.map +1 -1
  41. package/dist/{types-XmRC5wYO.d.cts → types-B-i5UbJo.d.cts} +24 -7
  42. package/dist/{types-XmRC5wYO.d.ts → types-B-i5UbJo.d.ts} +24 -7
  43. package/package.json +15 -10
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
1
+ import { InvalidPathError, PluginAlreadyRegisteredError, PluginDependencyMissingError, PluginInitializationError, PluginNotFoundError, CircularDependencyError } from './chunk-IUDFQZIP.js';
2
+ export { CircularDependencyError, CircularReferenceError, InvalidPathError, KernelAlreadyInitializedError, KernelInitializingError, MaxRetriesExceededError, PluginAlreadyRegisteredError, PluginDependencyMissingError, PluginInitializationError, PluginNotFoundError, TimeoutError, UtilsError } from './chunk-IUDFQZIP.js';
3
+ import { parsePath, UNSAFE_KEYS, hasOwn, hasUnsafeSegment, assignOwn } from './chunk-25WW2FCA.js';
4
+ import { __export } from './chunk-PZ5AY32C.js';
6
5
 
7
6
  // src/plugins/core/object.ts
8
7
  var object_exports = {};
@@ -23,12 +22,14 @@ function get(obj, path, defaultValue) {
23
22
  if (obj == null) {
24
23
  return defaultValue;
25
24
  }
26
- const keys2 = path.toString().split(/[\.\[]/g).map((k) => k.replace(/[\]']/g, "")).filter((k) => k !== "");
27
25
  let result = obj;
28
- for (const key of keys2) {
26
+ for (const { key } of parsePath(path)) {
29
27
  if (result == null) {
30
28
  return defaultValue;
31
29
  }
30
+ if (UNSAFE_KEYS.has(key) && !hasOwn(Object(result), key)) {
31
+ return defaultValue;
32
+ }
32
33
  result = result[key];
33
34
  }
34
35
  if (typeof result === "function") {
@@ -40,35 +41,24 @@ function set(obj, path, value) {
40
41
  if (obj == null || typeof obj !== "object") {
41
42
  return obj;
42
43
  }
43
- const keys2 = path.toString().split(".");
44
- const deepSet = (current, keyIndex) => {
45
- if (keyIndex === keys2.length) {
46
- return value;
47
- }
48
- const key = keys2[keyIndex];
49
- const isLast = keyIndex === keys2.length - 1;
50
- if (isLast) {
51
- const arrayMatch = key.match(/^(.+)\[(\d+)\]$/);
52
- if (arrayMatch) {
53
- const [, arrayPath, index] = arrayMatch;
54
- const arrayIndex = parseInt(index, 10);
55
- const arrayValue = current?.[arrayPath];
56
- if (Array.isArray(arrayValue)) {
57
- return {
58
- ...current,
59
- [arrayPath]: [
60
- ...arrayValue.slice(0, arrayIndex),
61
- value,
62
- ...arrayValue.slice(arrayIndex + 1)
63
- ]
64
- };
65
- }
66
- }
67
- return { ...current, [key]: value };
44
+ const segments = parsePath(path);
45
+ if (segments.length === 0) {
46
+ return obj;
47
+ }
48
+ if (hasUnsafeSegment(segments)) {
49
+ throw new InvalidPathError(String(path));
50
+ }
51
+ const deepSet = (current, index) => {
52
+ const { key } = segments[index];
53
+ const copy = Array.isArray(current) ? current.slice() : { ...current };
54
+ if (index === segments.length - 1) {
55
+ copy[key] = value;
56
+ return copy;
68
57
  }
69
- const nextValue = current?.[key];
70
- const nestedObj = nextValue != null && typeof nextValue === "object" ? nextValue : {};
71
- return { ...current, [key]: deepSet(nestedObj, keyIndex + 1) };
58
+ const next = current[key];
59
+ const child = next != null && typeof next === "object" ? next : segments[index + 1].index ? [] : {};
60
+ copy[key] = deepSet(child, index + 1);
61
+ return copy;
72
62
  };
73
63
  return deepSet(obj, 0);
74
64
  }
@@ -76,29 +66,31 @@ function setMut(obj, path, value) {
76
66
  if (obj == null || typeof obj !== "object") {
77
67
  return obj;
78
68
  }
79
- const keys2 = path.toString().split(".");
80
- let result = obj;
81
- for (let i = 0; i < keys2.length - 1; i++) {
82
- const key = keys2[i];
83
- if (result[key] == null || typeof result[key] !== "object") {
84
- result[key] = {};
69
+ const segments = parsePath(path);
70
+ if (segments.length === 0) {
71
+ return obj;
72
+ }
73
+ if (hasUnsafeSegment(segments)) {
74
+ throw new InvalidPathError(String(path));
75
+ }
76
+ let current = obj;
77
+ for (let i = 0; i < segments.length - 1; i++) {
78
+ const { key } = segments[i];
79
+ if (current[key] == null || typeof current[key] !== "object") {
80
+ current[key] = segments[i + 1].index ? [] : {};
85
81
  }
86
- result = result[key];
82
+ current = current[key];
87
83
  }
88
- result[keys2[keys2.length - 1]] = value;
84
+ current[segments[segments.length - 1].key] = value;
89
85
  return obj;
90
86
  }
91
87
  function has(obj, path) {
92
88
  if (obj == null) {
93
89
  return false;
94
90
  }
95
- const keys2 = path.toString().split(/[\.\[]/g).map((k) => k.replace(/[\]']/g, "")).filter((k) => k !== "");
96
91
  let result = obj;
97
- for (const key of keys2) {
98
- if (Array.isArray(result) && /^\d+$/.test(key)) {
99
- return true;
100
- }
101
- if (result == null || !(key in result)) {
92
+ for (const { key } of parsePath(path)) {
93
+ if (result == null || !hasOwn(Object(result), key)) {
102
94
  return false;
103
95
  }
104
96
  result = result[key];
@@ -109,7 +101,7 @@ function pick(obj, keys2) {
109
101
  const result = {};
110
102
  for (const key of keys2) {
111
103
  if (key in obj) {
112
- result[key] = obj[key];
104
+ assignOwn(result, key, obj[key]);
113
105
  }
114
106
  }
115
107
  return result;
@@ -122,11 +114,11 @@ function omit(obj, keys2) {
122
114
  return result;
123
115
  }
124
116
  function merge(target, ...sources) {
125
- const DANGEROUS_KEYS = ["__proto__", "constructor", "prototype"];
126
117
  const result = { ...target };
127
118
  for (const source of sources) {
119
+ if (source == null) continue;
128
120
  for (const key of Object.keys(source)) {
129
- if (DANGEROUS_KEYS.includes(key)) continue;
121
+ if (UNSAFE_KEYS.has(key)) continue;
130
122
  result[key] = source[key];
131
123
  }
132
124
  }
@@ -163,10 +155,11 @@ function groupBy(arr, key) {
163
155
  const result = {};
164
156
  for (const item of arr) {
165
157
  const groupKey = typeof key === "function" ? key(item) : String(item[key]);
166
- if (!result[groupKey]) {
167
- result[groupKey] = [];
158
+ if (hasOwn(result, groupKey)) {
159
+ result[groupKey].push(item);
160
+ } else {
161
+ assignOwn(result, groupKey, [item]);
168
162
  }
169
- result[groupKey].push(item);
170
163
  }
171
164
  return result;
172
165
  }
@@ -174,12 +167,16 @@ function keyBy(arr, key) {
174
167
  const result = {};
175
168
  for (const item of arr) {
176
169
  const keyValue = typeof key === "function" ? key(item) : String(item[key]);
177
- result[keyValue] = item;
170
+ assignOwn(result, keyValue, item);
178
171
  }
179
172
  return result;
180
173
  }
181
174
  function chunk(arr, size) {
182
175
  const result = [];
176
+ size = Math.trunc(size);
177
+ if (!(size >= 1)) {
178
+ return result;
179
+ }
183
180
  for (let i = 0; i < arr.length; i += size) {
184
181
  result.push(arr.slice(i, i + size));
185
182
  }
@@ -215,18 +212,19 @@ function compact(arr) {
215
212
  return arr.filter(Boolean);
216
213
  }
217
214
  function first(arr, n = 1) {
218
- if (arr.length === 0) return void 0;
219
215
  if (n === 1) return arr[0];
220
- const result = arr.slice(0, n);
221
- return result.length === 1 ? result[0] : result;
216
+ if (arr.length === 0) return void 0;
217
+ return arr.slice(0, Math.max(0, Math.trunc(n) || 0));
222
218
  }
223
219
  function last(arr, n = 1) {
224
- if (arr.length === 0) return void 0;
225
220
  if (n === 1) return arr[arr.length - 1];
226
- return arr.slice(-n);
221
+ if (arr.length === 0) return void 0;
222
+ const count = Math.max(0, Math.trunc(n) || 0);
223
+ return count === 0 ? [] : arr.slice(-count);
227
224
  }
228
225
  function sample(arr, n = 1) {
229
- if (arr.length === 0) return [];
226
+ n = Math.max(0, Math.trunc(n) || 0);
227
+ if (arr.length === 0 || n === 0) return [];
230
228
  if (n >= arr.length) return [...arr];
231
229
  const shuffled = [...arr];
232
230
  for (let i = shuffled.length - 1; i > 0; i--) {
@@ -268,91 +266,99 @@ function capitalize(str) {
268
266
  }
269
267
  function truncate(str, length, suffix = "...") {
270
268
  if (str.length <= length) return str;
271
- return str.slice(0, length) + suffix;
269
+ let end = Math.max(0, Math.trunc(length) || 0);
270
+ if (end > 0 && isHighSurrogate(str.charCodeAt(end - 1)) && isLowSurrogate(str.charCodeAt(end))) {
271
+ end--;
272
+ }
273
+ return str.slice(0, end) + suffix;
272
274
  }
275
+ var isHighSurrogate = (code) => code >= 55296 && code <= 56319;
276
+ var isLowSurrogate = (code) => code >= 56320 && code <= 57343;
273
277
  function slugify(str) {
274
- const charMap = {
275
- // Turkish
276
- "\u015F": "s",
277
- "\u015E": "s",
278
- "\u0131": "i",
279
- "\u0130": "i",
280
- "\u011F": "g",
281
- "\u011E": "g",
282
- "\xFC": "u",
283
- "\xDC": "u",
284
- "\xF6": "o",
285
- "\xD6": "o",
286
- "\xE7": "c",
287
- "\xC7": "c",
288
- // Russian (Cyrillic to Latin - basic transliteration)
289
- "\u0430": "a",
290
- "\u0431": "b",
291
- "\u0432": "v",
292
- "\u0433": "g",
293
- "\u0434": "d",
294
- "\u0435": "e",
295
- "\u0451": "yo",
296
- "\u0436": "zh",
297
- "\u0437": "z",
298
- "\u0438": "i",
299
- "\u0439": "y",
300
- "\u043A": "k",
301
- "\u043B": "l",
302
- "\u043C": "m",
303
- "\u043D": "n",
304
- "\u043E": "o",
305
- "\u043F": "p",
306
- "\u0440": "r",
307
- "\u0441": "s",
308
- "\u0442": "t",
309
- "\u0443": "u",
310
- "\u0444": "f",
311
- "\u0445": "h",
312
- "\u0446": "ts",
313
- "\u0447": "ch",
314
- "\u0448": "sh",
315
- "\u0449": "shch",
316
- "\u044A": "",
317
- "\u044B": "y",
318
- "\u044C": "",
319
- "\u044D": "e",
320
- "\u044E": "yu",
321
- "\u044F": "ya",
322
- // Greek (basic)
323
- "\u03B1": "a",
324
- "\u03B2": "b",
325
- "\u03B3": "g",
326
- "\u03B4": "d",
327
- "\u03B5": "e",
328
- "\u03B6": "z",
329
- "\u03B7": "i",
330
- "\u03B8": "th",
331
- "\u03B9": "i",
332
- "\u03BA": "k",
333
- "\u03BB": "l",
334
- "\u03BC": "m",
335
- "\u03BD": "n",
336
- "\u03BE": "x",
337
- "\u03BF": "o",
338
- "\u03C0": "p",
339
- "\u03C1": "r",
340
- "\u03C3": "s",
341
- "\u03C4": "t",
342
- "\u03C5": "y",
343
- "\u03C6": "f",
344
- "\u03C7": "ch",
345
- "\u03C8": "ps",
346
- "\u03C9": "o"
278
+ const transliterate = (input) => {
279
+ let out = "";
280
+ for (const char of input) {
281
+ out += hasOwn(SLUG_CHAR_MAP, char) ? SLUG_CHAR_MAP[char] : char;
282
+ }
283
+ return out;
347
284
  };
348
- return str.split("").map((char) => charMap[char] || char).join("").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[\s\-_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
285
+ return transliterate(transliterate(str.toLowerCase()).normalize("NFD").replace(/[\u0300-\u036f]/g, "")).replace(/[\s\-_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
349
286
  }
287
+ var SLUG_CHAR_MAP = {
288
+ // Turkish
289
+ "\u015F": "s",
290
+ "\u0131": "i",
291
+ "\u011F": "g",
292
+ "\xFC": "u",
293
+ "\xF6": "o",
294
+ "\xE7": "c",
295
+ // Russian (Cyrillic to Latin - basic transliteration)
296
+ "\u0430": "a",
297
+ "\u0431": "b",
298
+ "\u0432": "v",
299
+ "\u0433": "g",
300
+ "\u0434": "d",
301
+ "\u0435": "e",
302
+ "\u0451": "yo",
303
+ "\u0436": "zh",
304
+ "\u0437": "z",
305
+ "\u0438": "i",
306
+ "\u0439": "y",
307
+ "\u043A": "k",
308
+ "\u043B": "l",
309
+ "\u043C": "m",
310
+ "\u043D": "n",
311
+ "\u043E": "o",
312
+ "\u043F": "p",
313
+ "\u0440": "r",
314
+ "\u0441": "s",
315
+ "\u0442": "t",
316
+ "\u0443": "u",
317
+ "\u0444": "f",
318
+ "\u0445": "h",
319
+ "\u0446": "ts",
320
+ "\u0447": "ch",
321
+ "\u0448": "sh",
322
+ "\u0449": "shch",
323
+ "\u044A": "",
324
+ "\u044B": "y",
325
+ "\u044C": "",
326
+ "\u044D": "e",
327
+ "\u044E": "yu",
328
+ "\u044F": "ya",
329
+ // Greek (basic)
330
+ "\u03B1": "a",
331
+ "\u03B2": "b",
332
+ "\u03B3": "g",
333
+ "\u03B4": "d",
334
+ "\u03B5": "e",
335
+ "\u03B6": "z",
336
+ "\u03B7": "i",
337
+ "\u03B8": "th",
338
+ "\u03B9": "i",
339
+ "\u03BA": "k",
340
+ "\u03BB": "l",
341
+ "\u03BC": "m",
342
+ "\u03BD": "n",
343
+ "\u03BE": "x",
344
+ "\u03BF": "o",
345
+ "\u03C0": "p",
346
+ "\u03C1": "r",
347
+ "\u03C3": "s",
348
+ "\u03C2": "s",
349
+ "\u03C4": "t",
350
+ "\u03C5": "y",
351
+ "\u03C6": "f",
352
+ "\u03C7": "ch",
353
+ "\u03C8": "ps",
354
+ "\u03C9": "o"
355
+ };
350
356
  function template(str, data) {
351
357
  return str.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
352
358
  const keys2 = path.trim().split(".");
353
359
  let value = data;
354
360
  for (const key of keys2) {
355
- if (value == null) {
361
+ if (value == null || !hasOwn(Object(value), key)) {
356
362
  return "";
357
363
  }
358
364
  value = value[key];
@@ -364,6 +370,7 @@ function template(str, data) {
364
370
  // src/utils/eventBus.ts
365
371
  var EventBus = class {
366
372
  listeners = /* @__PURE__ */ new Map();
373
+ scopedHandlers = /* @__PURE__ */ new Map();
367
374
  /**
368
375
  * Register an event listener.
369
376
  *
@@ -430,45 +437,98 @@ var EventBus = class {
430
437
  listenerCount(event) {
431
438
  return this.listeners.get(event)?.size ?? 0;
432
439
  }
433
- };
434
-
435
- // src/errors.ts
436
- var UtilsError = class extends Error {
437
- code;
438
- constructor(message, code) {
439
- super(message);
440
- this.name = "UtilsError";
441
- this.code = code;
442
- Error.captureStackTrace(this, this.constructor);
440
+ /**
441
+ * Register an event listener with a scope (e.g., plugin name).
442
+ * Scoped listeners can be removed all at once using removeScope().
443
+ *
444
+ * @param scope - Scope identifier (e.g., plugin name)
445
+ * @param event - Event name to listen for
446
+ * @param handler - Function to call when event is emitted
447
+ */
448
+ onScoped(scope, event, handler) {
449
+ this.on(event, handler);
450
+ if (!this.scopedHandlers.has(scope)) {
451
+ this.scopedHandlers.set(scope, /* @__PURE__ */ new Map());
452
+ }
453
+ const scopeMap = this.scopedHandlers.get(scope);
454
+ if (!scopeMap.has(event)) {
455
+ scopeMap.set(event, /* @__PURE__ */ new Set());
456
+ }
457
+ scopeMap.get(event).add(handler);
443
458
  }
444
- };
445
- var PluginAlreadyRegisteredError = class extends UtilsError {
446
- constructor(name) {
447
- super(`Plugin "${name}" already registered`, "PLUGIN_ALREADY_REGISTERED");
448
- this.name = "PluginAlreadyRegisteredError";
459
+ /**
460
+ * Remove all listeners registered under a specific scope.
461
+ * Useful for cleanup when a plugin is unregistered.
462
+ *
463
+ * @param scope - Scope identifier to remove
464
+ */
465
+ removeScope(scope) {
466
+ const scopeMap = this.scopedHandlers.get(scope);
467
+ if (!scopeMap) return;
468
+ for (const [event, handlers] of scopeMap) {
469
+ for (const handler of handlers) {
470
+ this.off(event, handler);
471
+ }
472
+ }
473
+ this.scopedHandlers.delete(scope);
449
474
  }
450
- };
451
- var PluginNotFoundError = class extends UtilsError {
452
- constructor(name) {
453
- super(`Plugin "${name}" not found`, "PLUGIN_NOT_FOUND");
454
- this.name = "PluginNotFoundError";
475
+ /**
476
+ * Check if a scope has any registered listeners.
477
+ *
478
+ * @param scope - Scope identifier
479
+ * @returns True if scope has listeners
480
+ */
481
+ hasScope(scope) {
482
+ return this.scopedHandlers.has(scope);
455
483
  }
456
484
  };
457
- var PluginDependencyMissingError = class extends UtilsError {
458
- constructor(plugin, dependency) {
459
- super(`Plugin "${plugin}" requires "${dependency}" to be registered first`, "PLUGIN_DEPENDENCY_MISSING");
460
- this.name = "PluginDependencyMissingError";
485
+ var ScopedEventBus = class {
486
+ constructor(eventBus, scope) {
487
+ this.eventBus = eventBus;
488
+ this.scope = scope;
489
+ }
490
+ /**
491
+ * Register an event listener (automatically scoped).
492
+ */
493
+ on(event, handler) {
494
+ this.eventBus.onScoped(this.scope, event, handler);
495
+ }
496
+ /**
497
+ * Unregister an event listener.
498
+ */
499
+ off(event, handler) {
500
+ this.eventBus.off(event, handler);
501
+ }
502
+ /**
503
+ * Emit an event.
504
+ */
505
+ emit(event, ...args) {
506
+ this.eventBus.emit(event, ...args);
507
+ }
508
+ /**
509
+ * Remove all listeners registered by this scoped bus.
510
+ */
511
+ destroy() {
512
+ this.eventBus.removeScope(this.scope);
461
513
  }
462
514
  };
463
515
 
464
516
  // src/kernel.ts
465
517
  var Kernel = class {
466
518
  plugins = /* @__PURE__ */ new Map();
467
- context = {};
519
+ context;
468
520
  eventBus = new EventBus();
521
+ state = "idle";
522
+ initPromise = null;
523
+ constructor(options) {
524
+ this.context = options?.context ?? {};
525
+ }
469
526
  /**
470
527
  * Register a plugin with the kernel.
471
528
  *
529
+ * If the kernel is already initialized, the plugin will be
530
+ * automatically initialized after registration.
531
+ *
472
532
  * @param plugin - Plugin to register
473
533
  * @throws {PluginAlreadyRegisteredError} If plugin name already exists
474
534
  * @throws {PluginDependencyMissingError} If plugin dependencies are not met
@@ -484,51 +544,187 @@ var Kernel = class {
484
544
  }
485
545
  }
486
546
  }
487
- this.plugins.set(plugin.name, plugin);
547
+ const scopedBus = new ScopedEventBus(this.eventBus, plugin.name);
548
+ const entry = {
549
+ plugin,
550
+ state: "registered",
551
+ scopedBus
552
+ };
553
+ this.plugins.set(plugin.name, entry);
488
554
  try {
489
555
  plugin.install(this);
490
556
  } catch (error) {
491
557
  this.plugins.delete(plugin.name);
558
+ scopedBus.destroy();
492
559
  throw error;
493
560
  }
494
561
  this.eventBus.emit("plugin:registered", { name: plugin.name, version: plugin.version });
562
+ if (this.state === "initialized") {
563
+ this.initPlugin(entry).catch((error) => {
564
+ entry.state = "error";
565
+ this.eventBus.emit("plugin:error", { name: plugin.name, error });
566
+ });
567
+ }
495
568
  }
496
569
  /**
497
570
  * Initialize all registered plugins.
498
571
  *
499
- * Calls onInit() for each plugin that has it.
500
- * Plugins are initialized in the order they were registered.
572
+ * Plugins are initialized in topological order based on dependencies.
573
+ * If initialization fails, already initialized plugins are rolled back.
574
+ *
575
+ * @throws {CircularDependencyError} If circular dependency detected
576
+ * @throws {PluginInitializationError} If a plugin fails to initialize
501
577
  */
502
578
  async init() {
503
- for (const plugin of this.plugins.values()) {
504
- if (plugin.onInit) {
505
- try {
506
- await plugin.onInit(this.context);
507
- } catch (error) {
508
- if (plugin.onError) {
509
- plugin.onError(error);
579
+ if (this.state === "initialized") {
580
+ return;
581
+ }
582
+ if (this.state === "initializing") {
583
+ return this.initPromise;
584
+ }
585
+ if (this.state === "destroyed") {
586
+ throw new Error("Cannot initialize destroyed kernel");
587
+ }
588
+ this.state = "initializing";
589
+ this.initPromise = this.doInit();
590
+ try {
591
+ await this.initPromise;
592
+ } catch (error) {
593
+ if (this.state === "initializing") {
594
+ this.state = "idle";
595
+ }
596
+ throw error;
597
+ } finally {
598
+ this.initPromise = null;
599
+ }
600
+ }
601
+ async doInit() {
602
+ const sortedEntries = this.topologicalSort();
603
+ const initializedStack = [];
604
+ for (const entry of sortedEntries) {
605
+ if (entry.state === "error" || entry.state === "destroyed") {
606
+ entry.state = "registered";
607
+ }
608
+ }
609
+ for (const entry of sortedEntries) {
610
+ try {
611
+ await this.initPlugin(entry);
612
+ initializedStack.push(entry);
613
+ } catch (error) {
614
+ entry.state = "error";
615
+ for (const initialized of initializedStack.reverse()) {
616
+ try {
617
+ await this.destroyPlugin(initialized);
618
+ } catch (destroyError) {
619
+ console.error(
620
+ `Error during rollback of plugin "${initialized.plugin.name}":`,
621
+ destroyError
622
+ );
510
623
  }
511
- throw error;
512
624
  }
625
+ this.state = "idle";
626
+ throw new PluginInitializationError(
627
+ entry.plugin.name,
628
+ error instanceof Error ? error : new Error(String(error))
629
+ );
513
630
  }
514
631
  }
632
+ this.state = "initialized";
515
633
  this.eventBus.emit("kernel:initialized");
516
634
  }
635
+ /**
636
+ * Initialize a single plugin.
637
+ */
638
+ async initPlugin(entry) {
639
+ if (entry.state !== "registered") {
640
+ return;
641
+ }
642
+ entry.state = "initializing";
643
+ this.eventBus.emit("plugin:initializing", { name: entry.plugin.name });
644
+ if (entry.plugin.onInit) {
645
+ try {
646
+ await entry.plugin.onInit(this.context);
647
+ } catch (error) {
648
+ if (entry.plugin.onError) {
649
+ entry.plugin.onError(error);
650
+ }
651
+ throw error;
652
+ }
653
+ }
654
+ entry.state = "active";
655
+ this.eventBus.emit("plugin:initialized", { name: entry.plugin.name });
656
+ }
657
+ /**
658
+ * Destroy a single plugin.
659
+ */
660
+ async destroyPlugin(entry) {
661
+ if (entry.state === "destroyed") {
662
+ return;
663
+ }
664
+ entry.scopedBus.destroy();
665
+ if (entry.plugin.onDestroy) {
666
+ await entry.plugin.onDestroy();
667
+ }
668
+ entry.state = "destroyed";
669
+ }
670
+ /**
671
+ * Topological sort of plugins based on dependencies.
672
+ * Detects circular dependencies.
673
+ *
674
+ * @returns Plugins sorted in dependency order
675
+ * @throws {CircularDependencyError} If circular dependency detected
676
+ */
677
+ topologicalSort() {
678
+ const result = [];
679
+ const visited = /* @__PURE__ */ new Set();
680
+ const visiting = /* @__PURE__ */ new Set();
681
+ const visit = (name, path) => {
682
+ if (visited.has(name)) return;
683
+ if (visiting.has(name)) {
684
+ const cycleStart = path.indexOf(name);
685
+ const cycle = [...path.slice(cycleStart), name];
686
+ throw new CircularDependencyError(cycle);
687
+ }
688
+ const entry = this.plugins.get(name);
689
+ if (!entry) return;
690
+ visiting.add(name);
691
+ const currentPath = [...path, name];
692
+ if (entry.plugin.dependencies) {
693
+ for (const dep of entry.plugin.dependencies) {
694
+ visit(dep, currentPath);
695
+ }
696
+ }
697
+ visiting.delete(name);
698
+ visited.add(name);
699
+ result.push(entry);
700
+ };
701
+ for (const name of this.plugins.keys()) {
702
+ visit(name, []);
703
+ }
704
+ return result;
705
+ }
517
706
  /**
518
707
  * Unregister a plugin.
519
708
  *
709
+ * Automatically cleans up event listeners registered by this plugin.
710
+ *
520
711
  * @param name - Plugin name to unregister
521
712
  * @throws {PluginNotFoundError} If plugin doesn't exist
522
713
  */
523
- unregister(name) {
524
- const plugin = this.plugins.get(name);
525
- if (!plugin) {
714
+ async unregister(name) {
715
+ const entry = this.plugins.get(name);
716
+ if (!entry) {
526
717
  throw new PluginNotFoundError(name);
527
718
  }
528
- this.plugins.delete(name);
529
- if (plugin.onDestroy) {
530
- plugin.onDestroy();
719
+ for (const [otherName, otherEntry] of this.plugins) {
720
+ if (otherName !== name && otherEntry.plugin.dependencies?.includes(name)) {
721
+ throw new Error(
722
+ `Cannot unregister plugin "${name}": plugin "${otherName}" depends on it`
723
+ );
724
+ }
531
725
  }
726
+ await this.destroyPlugin(entry);
727
+ this.plugins.delete(name);
532
728
  this.eventBus.emit("plugin:unregistered", { name });
533
729
  }
534
730
  /**
@@ -546,7 +742,16 @@ var Kernel = class {
546
742
  * @returns Plugin instance or undefined
547
743
  */
548
744
  getPlugin(name) {
549
- return this.plugins.get(name);
745
+ return this.plugins.get(name)?.plugin;
746
+ }
747
+ /**
748
+ * Get the state of a registered plugin.
749
+ *
750
+ * @param name - Plugin name
751
+ * @returns Plugin state or undefined if not found
752
+ */
753
+ getPluginState(name) {
754
+ return this.plugins.get(name)?.state;
550
755
  }
551
756
  /**
552
757
  * Check if a plugin is registered.
@@ -565,6 +770,33 @@ var Kernel = class {
565
770
  listPlugins() {
566
771
  return Array.from(this.plugins.keys());
567
772
  }
773
+ /**
774
+ * Get the kernel's current state.
775
+ *
776
+ * @returns Current kernel state
777
+ */
778
+ getState() {
779
+ return this.state;
780
+ }
781
+ /**
782
+ * Check if kernel is initialized.
783
+ *
784
+ * @returns True if kernel is initialized
785
+ */
786
+ isInitialized() {
787
+ return this.state === "initialized";
788
+ }
789
+ /**
790
+ * Get the scoped event bus for a plugin.
791
+ * Listeners registered through this bus are automatically
792
+ * cleaned up when the plugin is unregistered.
793
+ *
794
+ * @param pluginName - Plugin name
795
+ * @returns Scoped event bus or undefined
796
+ */
797
+ getScopedEventBus(pluginName) {
798
+ return this.plugins.get(pluginName)?.scopedBus;
799
+ }
568
800
  /**
569
801
  * Register an event listener.
570
802
  *
@@ -595,17 +827,27 @@ var Kernel = class {
595
827
  /**
596
828
  * Destroy the kernel and all plugins.
597
829
  *
598
- * Unregisters all plugins and cleans up resources.
830
+ * Unregisters all plugins in reverse dependency order and cleans up resources.
599
831
  */
600
832
  async destroy() {
601
- const pluginNames = Array.from(this.plugins.keys());
602
- for (const name of pluginNames) {
603
- this.unregister(name);
833
+ if (this.state === "destroyed") {
834
+ return;
835
+ }
836
+ const sortedEntries = this.topologicalSort().reverse();
837
+ for (const entry of sortedEntries) {
838
+ try {
839
+ await this.destroyPlugin(entry);
840
+ } catch (error) {
841
+ console.error(`Error destroying plugin "${entry.plugin.name}":`, error);
842
+ }
604
843
  }
844
+ this.plugins.clear();
845
+ this.state = "destroyed";
846
+ this.eventBus.emit("kernel:destroyed");
605
847
  this.eventBus.removeAllListeners();
606
848
  }
607
849
  };
608
850
 
609
- export { Kernel, array_exports as array, camelCase, capitalize, chunk, compact, entries, first, flatten, fromEntries, get, groupBy, has, kebabCase, keyBy, keys, last, merge, object_exports as object, omit, pascalCase, pick, sample, set, setMut, slugify, snakeCase, string_exports as string, template, truncate, uniq, uniqBy, values };
851
+ export { EventBus, Kernel, ScopedEventBus, array_exports as array, camelCase, capitalize, chunk, compact, entries, first, flatten, fromEntries, get, groupBy, has, kebabCase, keyBy, keys, last, merge, object_exports as object, omit, pascalCase, pick, sample, set, setMut, slugify, snakeCase, string_exports as string, template, truncate, uniq, uniqBy, values };
610
852
  //# sourceMappingURL=index.js.map
611
853
  //# sourceMappingURL=index.js.map