@noormdev/sdk 1.0.0-alpha.9 → 1.0.1

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.
@@ -0,0 +1,3372 @@
1
+ import { createRequire } from 'module';
2
+
3
+ createRequire(import.meta.url);
4
+
5
+ // node_modules/@logosdx/utils/dist/esm/object-utils/index.mjs
6
+ var definePrivateProps = (target, props, configurable = false) => {
7
+ Object.entries(props).map(([prop, value]) => {
8
+ Object.defineProperty(target, prop, {
9
+ value,
10
+ writable: false,
11
+ enumerable: false,
12
+ configurable
13
+ });
14
+ });
15
+ };
16
+ var reach = (obj, val) => {
17
+ const path = val.split(".");
18
+ return path.reduce((acc, key) => {
19
+ if (acc === void 0 || acc === null) {
20
+ return null;
21
+ }
22
+ if (acc instanceof Map) {
23
+ return acc.get(key);
24
+ }
25
+ if (acc instanceof Set) {
26
+ const has = acc.has(key);
27
+ const values = Array.from(acc);
28
+ if (has) {
29
+ return values[values.indexOf(key)];
30
+ }
31
+ return values[key];
32
+ }
33
+ return acc[key];
34
+ }, obj);
35
+ };
36
+ var setDeep = (obj, path, value) => {
37
+ assert(typeof obj === "object" && obj !== null, "obj must be a non-null object");
38
+ assert(typeof path === "string" && path.length > 0, "path must be a non-empty string");
39
+ const keys = path.split(".");
40
+ const lastKey = keys[keys.length - 1];
41
+ let current = obj;
42
+ for (let i = 0; i < keys.length - 1; i++) {
43
+ const key = keys[i];
44
+ if (current === null || current === void 0) {
45
+ throw new Error(`Cannot set property '${key}' on ${current} at path: ${keys.slice(0, i).join(".")}`);
46
+ }
47
+ if (typeof current !== "object") {
48
+ throw new Error(`Cannot set property '${key}' on primitive value at path: ${keys.slice(0, i).join(".")}`);
49
+ }
50
+ if (!(key in current)) {
51
+ current[key] = {};
52
+ }
53
+ current = current[key];
54
+ }
55
+ if (current === null || current === void 0) {
56
+ throw new Error(`Cannot set property '${lastKey}' on ${current}`);
57
+ }
58
+ if (typeof current !== "object") {
59
+ throw new Error(`Cannot set property '${lastKey}' on primitive value`);
60
+ }
61
+ current[lastKey] = value;
62
+ };
63
+ var setDeepMany = (obj, entries) => {
64
+ assert(typeof obj === "object" && obj !== null, "obj must be a non-null object");
65
+ assert(Array.isArray(entries), "entries must be an array");
66
+ for (let i = 0; i < entries.length; i++) {
67
+ const entry = entries[i];
68
+ assert(Array.isArray(entry) && entry.length === 2, `entry ${i} must be a [path, value] tuple`);
69
+ const [path, value] = entry;
70
+ assert(typeof path === "string" && path.length > 0, `entry ${i} must have a non-empty string path (received: ${typeof path})`);
71
+ setDeep(obj, path, value);
72
+ }
73
+ };
74
+
75
+ // node_modules/@logosdx/utils/dist/esm/validation/assert.mjs
76
+ var AssertError = class extends Error {
77
+ };
78
+ var isOptional = (val, check) => val === void 0 || val === null || (check instanceof Function ? !!check(val) : !!check);
79
+ var assert = (test, message, ErrorClass) => {
80
+ const check = test instanceof Function ? !!test() : !!test;
81
+ if (check === false) {
82
+ throw new (ErrorClass || AssertError)(message || "assertion failed");
83
+ }
84
+ };
85
+ var assertOptional = (val, ...rest) => {
86
+ if (val !== void 0) {
87
+ assert(...rest);
88
+ }
89
+ };
90
+
91
+ // node_modules/@logosdx/utils/dist/esm/validation/type-guards.mjs
92
+ var isPrimitive = (val) => val === null || val === void 0 || typeof val === "string" || typeof val === "number" || typeof val === "boolean" || typeof val === "symbol" || typeof val === "bigint";
93
+ var hasNoConstructor = (val) => val === null || val === void 0;
94
+ var hasSameConstructor = (value, compare) => hasNoConstructor(value) === false && hasNoConstructor(compare) === false && value.constructor === compare.constructor;
95
+ var isSameLength = (a, b) => a.length === b.length && a.size === b.size;
96
+ var isFunction = (a) => a instanceof Function;
97
+ var isObject = (a) => a instanceof Object;
98
+ var commonObjects = /* @__PURE__ */ new Set([
99
+ Date,
100
+ RegExp,
101
+ Function,
102
+ Error,
103
+ EvalError,
104
+ RangeError,
105
+ ReferenceError,
106
+ SyntaxError,
107
+ TypeError,
108
+ URIError,
109
+ AggregateError,
110
+ DOMException,
111
+ Array,
112
+ Set,
113
+ Map,
114
+ WeakMap,
115
+ WeakSet,
116
+ Promise,
117
+ Proxy,
118
+ Symbol,
119
+ BigInt,
120
+ WeakRef,
121
+ FinalizationRegistry,
122
+ DataView,
123
+ ArrayBuffer,
124
+ Int8Array,
125
+ Uint8Array,
126
+ Uint8ClampedArray,
127
+ Int16Array,
128
+ Uint16Array,
129
+ Int32Array,
130
+ Uint32Array,
131
+ Float32Array,
132
+ Float64Array,
133
+ BigInt64Array,
134
+ BigUint64Array,
135
+ FormData,
136
+ URLSearchParams
137
+ ]);
138
+ var isPlainObject = (a) => !isPrimitive(a) && isObject(a) && !commonObjects.has(a.constructor);
139
+
140
+ // node_modules/@logosdx/utils/dist/esm/validation/comparisons.mjs
141
+ var allKeysValid = (item, check) => {
142
+ let isEqual;
143
+ for (const i in item) {
144
+ isEqual = check(item[i], i);
145
+ if (isEqual === false) {
146
+ break;
147
+ }
148
+ }
149
+ return isEqual;
150
+ };
151
+ var allItemsValid = (item, check) => {
152
+ let isEqual;
153
+ for (const val of item) {
154
+ isEqual = check(val);
155
+ if (isEqual === false) {
156
+ break;
157
+ }
158
+ }
159
+ return isEqual;
160
+ };
161
+
162
+ // node_modules/@logosdx/utils/dist/esm/validation/values.mjs
163
+ var ENABLED_VALUES = /* @__PURE__ */ new Set([
164
+ "true",
165
+ "yes",
166
+ true
167
+ ]);
168
+ var DISABLED_VALUES = /* @__PURE__ */ new Set([
169
+ "false",
170
+ "no",
171
+ false
172
+ ]);
173
+ var isEnabledValue = (val) => {
174
+ return ENABLED_VALUES.has(val);
175
+ };
176
+ var isDisabledValue = (val) => {
177
+ return DISABLED_VALUES.has(val);
178
+ };
179
+
180
+ // node_modules/@logosdx/utils/dist/esm/async/attempt.mjs
181
+ var attempt = async (fn) => {
182
+ assert(isFunction(fn), "fn must be a function");
183
+ try {
184
+ return [
185
+ await fn(),
186
+ null
187
+ ];
188
+ } catch (e) {
189
+ return [
190
+ null,
191
+ e
192
+ ];
193
+ }
194
+ };
195
+ var attemptSync = (fn) => {
196
+ assert(isFunction(fn), "fn must be a function");
197
+ try {
198
+ return [
199
+ fn(),
200
+ null
201
+ ];
202
+ } catch (e) {
203
+ return [
204
+ null,
205
+ e
206
+ ];
207
+ }
208
+ };
209
+
210
+ // node_modules/@logosdx/utils/dist/esm/data-structures/helpers.mjs
211
+ var cloneHandlers = /* @__PURE__ */ new Map();
212
+ var mergeHandlers = /* @__PURE__ */ new Map();
213
+ var equalityHandlers = /* @__PURE__ */ new Map();
214
+ var DANGEROUS_PROPS = /* @__PURE__ */ new Set([
215
+ "__proto__",
216
+ "constructor",
217
+ "prototype"
218
+ ]);
219
+ var isDangerousKey = (key) => {
220
+ return typeof key === "string" && DANGEROUS_PROPS.has(key);
221
+ };
222
+ var getSafeKeys = (obj) => {
223
+ return Object.keys(obj).filter((key) => !isDangerousKey(key));
224
+ };
225
+
226
+ // node_modules/@logosdx/utils/dist/esm/data-structures/clone.mjs
227
+ var prepareCloneHandlers = () => {
228
+ cloneHandlers.set(Array, (arr, seen) => arr.map((v) => clone(v, seen)));
229
+ cloneHandlers.set(Object, (obj, seen) => {
230
+ const copy = {};
231
+ const keys = Object.keys(obj);
232
+ for (const key of keys) {
233
+ if (isDangerousKey(key)) {
234
+ continue;
235
+ }
236
+ copy[key] = clone(obj[key], seen);
237
+ }
238
+ return copy;
239
+ });
240
+ cloneHandlers.set(Map, (_map, seen) => {
241
+ const copy = /* @__PURE__ */ new Map();
242
+ for (const entry of _map.entries()) {
243
+ const [key, val] = entry;
244
+ copy.set(key, clone(val, seen));
245
+ }
246
+ return copy;
247
+ });
248
+ cloneHandlers.set(Set, (_set, seen) => {
249
+ const copy = /* @__PURE__ */ new Set();
250
+ for (const original of _set) {
251
+ copy.add(clone(original, seen));
252
+ }
253
+ return copy;
254
+ });
255
+ const TYPED_ARRAYS = [
256
+ Int8Array,
257
+ Uint8Array,
258
+ Uint8ClampedArray,
259
+ Int16Array,
260
+ Uint16Array,
261
+ Int32Array,
262
+ Uint32Array,
263
+ Float32Array,
264
+ Float64Array,
265
+ BigInt64Array,
266
+ BigUint64Array
267
+ ];
268
+ TYPED_ARRAYS.forEach((TypedArrayConstructor) => {
269
+ cloneHandlers.set(TypedArrayConstructor, (arr) => {
270
+ return new TypedArrayConstructor(arr);
271
+ });
272
+ });
273
+ cloneHandlers.set(ArrayBuffer, (buffer) => {
274
+ return buffer.slice(0);
275
+ });
276
+ cloneHandlers.set(DataView, (view) => {
277
+ const clonedBuffer = view.buffer.slice(0);
278
+ return new DataView(clonedBuffer, view.byteOffset, view.byteLength);
279
+ });
280
+ cloneHandlers.set(Error, (error, seen) => {
281
+ const cloned = typeof structuredClone === "function" ? structuredClone(error) : new error.constructor(error.message);
282
+ if (error.name) {
283
+ cloned.name = error.name;
284
+ }
285
+ if (error.stack) {
286
+ cloned.stack = error.stack;
287
+ }
288
+ const keys = Object.keys(error);
289
+ for (const key of keys) {
290
+ if (key !== "name" && key !== "message" && key !== "stack" && !isDangerousKey(key)) {
291
+ cloned[key] = clone(error[key], seen);
292
+ }
293
+ }
294
+ return cloned;
295
+ });
296
+ cloneHandlers.set(Date, (date) => {
297
+ return new Date(date.getTime());
298
+ });
299
+ cloneHandlers.set(RegExp, (regex) => {
300
+ return new RegExp(regex.source, regex.flags);
301
+ });
302
+ };
303
+ var cloneHandlersInitialized = false;
304
+ var useRawHandler = /* @__PURE__ */ new Set([
305
+ ArrayBuffer,
306
+ DataView,
307
+ Int8Array,
308
+ Uint8Array,
309
+ Uint8ClampedArray,
310
+ Int16Array,
311
+ Uint16Array,
312
+ Int32Array,
313
+ Uint32Array,
314
+ Float32Array,
315
+ Float64Array,
316
+ BigInt64Array,
317
+ BigUint64Array,
318
+ Error,
319
+ Date,
320
+ RegExp
321
+ ]);
322
+ var clone = (original, seen = /* @__PURE__ */ new WeakMap()) => {
323
+ if (!cloneHandlersInitialized) {
324
+ prepareCloneHandlers();
325
+ cloneHandlersInitialized = true;
326
+ }
327
+ if (isPrimitive(original)) {
328
+ return original;
329
+ }
330
+ if (seen.has(original)) {
331
+ return seen.get(original);
332
+ }
333
+ if (original instanceof Error) {
334
+ const cloneType2 = cloneHandlers.get(Error);
335
+ return cloneType2(original, seen);
336
+ }
337
+ const actualConstructor = Object.getPrototypeOf(original)?.constructor || original.constructor;
338
+ const cloneType = cloneHandlers.get(actualConstructor);
339
+ if (!cloneType) {
340
+ return original;
341
+ }
342
+ if (useRawHandler.has(actualConstructor)) {
343
+ return cloneType(original, seen);
344
+ }
345
+ let placeholder;
346
+ if (Array.isArray(original)) {
347
+ placeholder = [];
348
+ seen.set(original, placeholder);
349
+ const cloned2 = cloneType(original, seen);
350
+ placeholder.push(...cloned2);
351
+ return placeholder;
352
+ }
353
+ if (original instanceof Map) {
354
+ placeholder = /* @__PURE__ */ new Map();
355
+ seen.set(original, placeholder);
356
+ const cloned2 = cloneType(original, seen);
357
+ for (const [key, value] of cloned2) {
358
+ placeholder.set(key, value);
359
+ }
360
+ return placeholder;
361
+ }
362
+ if (original instanceof Set) {
363
+ placeholder = /* @__PURE__ */ new Set();
364
+ seen.set(original, placeholder);
365
+ const cloned2 = cloneType(original, seen);
366
+ for (const value of cloned2) {
367
+ placeholder.add(value);
368
+ }
369
+ return placeholder;
370
+ }
371
+ placeholder = {};
372
+ seen.set(original, placeholder);
373
+ const cloned = cloneType(original, seen);
374
+ Object.assign(placeholder, cloned);
375
+ return placeholder;
376
+ };
377
+
378
+ // node_modules/@logosdx/utils/dist/esm/data-structures/equals.mjs
379
+ var prepareEqualsHandlers = () => {
380
+ equalityHandlers.set(Array, (_a, _b, seen) => {
381
+ const a = _a;
382
+ const b = _b;
383
+ if (!isSameLength(a, b)) return false;
384
+ return allKeysValid(a, (val, i) => equals(val, b[i], seen));
385
+ });
386
+ equalityHandlers.set(Object, (_a, _b, seen) => {
387
+ const a = _a;
388
+ const b = _b;
389
+ if (a === b) return true;
390
+ if (hasNoConstructor(a) || hasNoConstructor(b)) return false;
391
+ const aSafeKeys = getSafeKeys(a);
392
+ const bSafeKeys = getSafeKeys(b);
393
+ const aKeys = new Set(aSafeKeys);
394
+ const bKeys = new Set(bSafeKeys);
395
+ if (!isSameLength(aKeys, bKeys)) return false;
396
+ const bHasAKeys = allItemsValid(aKeys, (val) => bKeys.has(val));
397
+ const aHasBKeys = allItemsValid(bKeys, (val) => aKeys.has(val));
398
+ if (!aHasBKeys || !bHasAKeys) return false;
399
+ return aSafeKeys.every((key) => equals(a[key], b[key], seen));
400
+ });
401
+ equalityHandlers.set(Map, (_a, _b, seen) => {
402
+ const a = _a;
403
+ const b = _b;
404
+ if (a.size !== b.size) return false;
405
+ const aKeys = new Set(a.keys());
406
+ const bKeys = new Set(b.keys());
407
+ const bHasAKeys = allItemsValid(aKeys, (val) => bKeys.has(val));
408
+ const aHasBKeys = allItemsValid(bKeys, (val) => aKeys.has(val));
409
+ if (!aHasBKeys || !bHasAKeys) return false;
410
+ return allItemsValid(a.keys(), (key) => equals(a.get(key), b.get(key), seen));
411
+ });
412
+ equalityHandlers.set(Set, (_a, _b) => {
413
+ const a = _a;
414
+ const b = _b;
415
+ if (a.size !== b.size) return false;
416
+ return allItemsValid(a, (val) => b.has(val));
417
+ });
418
+ equalityHandlers.set(Date, (a, b) => a.getTime() === b.getTime());
419
+ equalityHandlers.set(RegExp, (a, b) => {
420
+ return a.source === b.source && a.flags === b.flags;
421
+ });
422
+ equalityHandlers.set(Function, (a, b) => a.toString() === b.toString());
423
+ equalityHandlers.set(Error, (a, b) => a.toString() === b.toString());
424
+ const TYPED_ARRAYS = [
425
+ Int8Array,
426
+ Uint8Array,
427
+ Uint8ClampedArray,
428
+ Int16Array,
429
+ Uint16Array,
430
+ Int32Array,
431
+ Uint32Array,
432
+ Float32Array,
433
+ Float64Array,
434
+ BigInt64Array,
435
+ BigUint64Array
436
+ ];
437
+ TYPED_ARRAYS.forEach((TypedArrayConstructor) => {
438
+ equalityHandlers.set(TypedArrayConstructor, (_a, _b) => {
439
+ const a = _a;
440
+ const b = _b;
441
+ if (a.length !== b.length) return false;
442
+ for (let i = 0; i < a.length; i++) {
443
+ if (a[i] !== b[i]) return false;
444
+ }
445
+ return true;
446
+ });
447
+ });
448
+ equalityHandlers.set(ArrayBuffer, (_a, _b) => {
449
+ const a = _a;
450
+ const b = _b;
451
+ if (a.byteLength !== b.byteLength) return false;
452
+ const aView = new Uint8Array(a);
453
+ const bView = new Uint8Array(b);
454
+ for (let i = 0; i < aView.length; i++) {
455
+ if (aView[i] !== bView[i]) return false;
456
+ }
457
+ return true;
458
+ });
459
+ equalityHandlers.set(DataView, (_a, _b, seen) => {
460
+ const a = _a;
461
+ const b = _b;
462
+ if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) {
463
+ return false;
464
+ }
465
+ return equalityHandlers.get(ArrayBuffer)(a.buffer, b.buffer, seen);
466
+ });
467
+ const ERROR_TYPES = [
468
+ Error,
469
+ TypeError,
470
+ ReferenceError,
471
+ SyntaxError,
472
+ RangeError,
473
+ EvalError,
474
+ URIError
475
+ ];
476
+ ERROR_TYPES.forEach((ErrorConstructor) => {
477
+ equalityHandlers.set(ErrorConstructor, (_a, _b, seen) => {
478
+ const a = _a;
479
+ const b = _b;
480
+ if (a.name !== b.name || a.message !== b.message) {
481
+ return false;
482
+ }
483
+ const aKeys = [
484
+ ...Object.keys(a),
485
+ ...Object.getOwnPropertyNames(a)
486
+ ].filter((key) => {
487
+ const descriptor = Object.getOwnPropertyDescriptor(a, key);
488
+ return descriptor && descriptor.enumerable && !isDangerousKey(key);
489
+ });
490
+ const bKeys = [
491
+ ...Object.keys(b),
492
+ ...Object.getOwnPropertyNames(b)
493
+ ].filter((key) => {
494
+ const descriptor = Object.getOwnPropertyDescriptor(b, key);
495
+ return descriptor && descriptor.enumerable && !isDangerousKey(key);
496
+ });
497
+ const builtInProps = /* @__PURE__ */ new Set([
498
+ "name",
499
+ "message",
500
+ "stack"
501
+ ]);
502
+ const aCustomKeys = aKeys.filter((key) => !builtInProps.has(key));
503
+ const bCustomKeys = bKeys.filter((key) => !builtInProps.has(key));
504
+ if (aCustomKeys.length !== bCustomKeys.length) {
505
+ return false;
506
+ }
507
+ for (const key of aCustomKeys) {
508
+ if (!bCustomKeys.includes(key)) {
509
+ return false;
510
+ }
511
+ }
512
+ for (const key of aCustomKeys) {
513
+ if (!equals(a[key], b[key], seen)) {
514
+ return false;
515
+ }
516
+ }
517
+ return true;
518
+ });
519
+ });
520
+ };
521
+ var equalityHandlersInitialized = false;
522
+ var equals = (change, current, seen = /* @__PURE__ */ new WeakMap()) => {
523
+ if (equalityHandlersInitialized === false) {
524
+ prepareEqualsHandlers();
525
+ equalityHandlersInitialized = true;
526
+ }
527
+ if (isPrimitive(change) || isPrimitive(current)) return change === current;
528
+ if (change === current) return true;
529
+ if (change && typeof change === "object" && current && typeof current === "object") {
530
+ if (seen.has(change) && seen.get(change) === current) {
531
+ return true;
532
+ }
533
+ if (change === current) {
534
+ return true;
535
+ }
536
+ seen.set(change, current);
537
+ }
538
+ if (!hasSameConstructor(change, current)) return false;
539
+ const cur = current;
540
+ const actualConstructor = Object.getPrototypeOf(cur)?.constructor || cur.constructor;
541
+ let typeequalsFunc = equalityHandlers.get(actualConstructor);
542
+ if (!typeequalsFunc && isFunction(change) && isFunction(current)) {
543
+ typeequalsFunc = equalityHandlers.get(Function);
544
+ }
545
+ if (!typeequalsFunc) {
546
+ return change === current;
547
+ }
548
+ const result = typeequalsFunc(change, current, seen);
549
+ return result;
550
+ };
551
+
552
+ // node_modules/@logosdx/utils/dist/esm/data-structures/merge.mjs
553
+ var mergeArrays = (target, source) => {
554
+ for (const value of source) {
555
+ target.push(value);
556
+ }
557
+ return target;
558
+ };
559
+ var mergeSets = (target, source) => {
560
+ for (const value of source) {
561
+ if (!target.has(value)) {
562
+ target.add(value);
563
+ }
564
+ }
565
+ return target;
566
+ };
567
+ var overwriteArrays = (target, source) => {
568
+ target.length = 0;
569
+ for (const value of source) {
570
+ target.push(value);
571
+ }
572
+ return target;
573
+ };
574
+ var overwriteSets = (target, source) => {
575
+ target.clear();
576
+ for (const value of source) {
577
+ target.add(value);
578
+ }
579
+ return target;
580
+ };
581
+ var prepareMergeHandlers = () => {
582
+ mergeHandlers.set(Array, (target, source, options) => {
583
+ if (options?.mergeArrays) {
584
+ return mergeArrays(target, source);
585
+ }
586
+ return overwriteArrays(target, source);
587
+ });
588
+ mergeHandlers.set(Set, (target, source, options) => {
589
+ if (options?.mergeSets) {
590
+ return mergeSets(target, source);
591
+ }
592
+ return overwriteSets(target, source);
593
+ });
594
+ mergeHandlers.set(Object, (_target, _source, options) => {
595
+ const target = _target;
596
+ const source = _source;
597
+ const sourceKeys = Object.keys(source);
598
+ for (const key of sourceKeys) {
599
+ if (isDangerousKey(key)) {
600
+ continue;
601
+ }
602
+ if (target[key] === void 0 || hasNoConstructor(target[key]) || hasNoConstructor(source[key])) {
603
+ target[key] = source[key];
604
+ continue;
605
+ }
606
+ if (hasSameConstructor(target[key], source[key])) {
607
+ target[key] = merge(target[key], source[key], options);
608
+ continue;
609
+ }
610
+ target[key] = source[key];
611
+ }
612
+ return target;
613
+ });
614
+ mergeHandlers.set(Map, (_target, _source, options) => {
615
+ const target = _target;
616
+ const source = _source;
617
+ for (const [key, bValue] of source.entries()) {
618
+ if (!target.has(key)) {
619
+ target.set(key, bValue);
620
+ continue;
621
+ }
622
+ const aValue = target.get(key);
623
+ if (hasNoConstructor(aValue) || hasNoConstructor(bValue)) {
624
+ target.set(key, bValue);
625
+ continue;
626
+ }
627
+ if (hasSameConstructor(bValue, aValue)) {
628
+ target.set(key, merge(aValue, bValue, options));
629
+ continue;
630
+ }
631
+ target.set(key, bValue);
632
+ }
633
+ return target;
634
+ });
635
+ mergeHandlers.set(Error, (_target, _source, options) => {
636
+ const target = _target;
637
+ const source = _source;
638
+ const sourceKeys = getSafeKeys(source);
639
+ for (const key of sourceKeys) {
640
+ if (target[key] === void 0) {
641
+ target[key] = source[key];
642
+ continue;
643
+ }
644
+ if (hasSameConstructor(target[key], source[key])) {
645
+ target[key] = merge(target[key], source[key], options);
646
+ continue;
647
+ }
648
+ target[key] = source[key];
649
+ }
650
+ return target;
651
+ });
652
+ const TYPED_ARRAYS = [
653
+ Int8Array,
654
+ Uint8Array,
655
+ Uint8ClampedArray,
656
+ Int16Array,
657
+ Uint16Array,
658
+ Int32Array,
659
+ Uint32Array,
660
+ Float32Array,
661
+ Float64Array,
662
+ BigInt64Array,
663
+ BigUint64Array
664
+ ];
665
+ TYPED_ARRAYS.forEach((TypedArrayConstructor) => {
666
+ mergeHandlers.set(TypedArrayConstructor, (_target, source) => {
667
+ return new TypedArrayConstructor(source);
668
+ });
669
+ });
670
+ mergeHandlers.set(ArrayBuffer, (_target, source) => {
671
+ return source.slice(0);
672
+ });
673
+ mergeHandlers.set(DataView, (_target, source) => {
674
+ const sourceView = source;
675
+ const clonedBuffer = sourceView.buffer.slice(0);
676
+ return new DataView(clonedBuffer, sourceView.byteOffset, sourceView.byteLength);
677
+ });
678
+ const ERROR_TYPES = [
679
+ Error,
680
+ TypeError,
681
+ ReferenceError,
682
+ SyntaxError,
683
+ RangeError,
684
+ EvalError,
685
+ URIError
686
+ ];
687
+ ERROR_TYPES.forEach((ErrorConstructor) => {
688
+ mergeHandlers.set(ErrorConstructor, (_target, source) => {
689
+ const sourceError = source;
690
+ const cloned = new sourceError.constructor(sourceError.message);
691
+ if (sourceError.name) {
692
+ cloned.name = sourceError.name;
693
+ }
694
+ if (sourceError.stack) {
695
+ cloned.stack = sourceError.stack;
696
+ }
697
+ const keys = Object.keys(sourceError);
698
+ for (const key of keys) {
699
+ if (key !== "name" && key !== "message" && key !== "stack" && !isDangerousKey(key)) {
700
+ cloned[key] = sourceError[key];
701
+ }
702
+ }
703
+ return cloned;
704
+ });
705
+ });
706
+ };
707
+ var mergeHandlersInitialized = false;
708
+ var mergeDefaults = {
709
+ mergeArrays: true,
710
+ mergeSets: true
711
+ };
712
+ var merge = (target, source, options = {}) => {
713
+ if (!mergeHandlersInitialized) {
714
+ prepareMergeHandlers();
715
+ mergeHandlersInitialized = true;
716
+ }
717
+ options = {
718
+ ...mergeDefaults,
719
+ ...options
720
+ };
721
+ if (isPrimitive(source) || source instanceof Date) {
722
+ return source;
723
+ }
724
+ if (hasSameConstructor(source, target)) {
725
+ const actualConstructor = Object.getPrototypeOf(target)?.constructor || target.constructor;
726
+ const mergeType = mergeHandlers.get(actualConstructor);
727
+ if (!mergeType) {
728
+ return target;
729
+ }
730
+ return mergeType(target, source, options);
731
+ }
732
+ return source;
733
+ };
734
+
735
+ // node_modules/@logosdx/utils/dist/esm/data-structures/priority-queue.mjs
736
+ var fifoCompare = (a, b) => {
737
+ if (a.priority === b.priority) {
738
+ return a.order - b.order;
739
+ }
740
+ return a.priority - b.priority;
741
+ };
742
+ var lifoCompare = (a, b) => {
743
+ if (a.priority === b.priority) {
744
+ return b.order - a.order;
745
+ }
746
+ return a.priority - b.priority;
747
+ };
748
+ var PriorityQueue = class _PriorityQueue {
749
+ #heap = [];
750
+ #insertionCounter = 0;
751
+ #compare;
752
+ #options;
753
+ constructor(options = {}) {
754
+ this.#compare = options.lifo ? lifoCompare : fifoCompare;
755
+ if (options.compare) {
756
+ this.#compare = options.compare;
757
+ }
758
+ if (options.maxHeap) {
759
+ const originalCompare = this.#compare;
760
+ this.#compare = (a, b) => -originalCompare(a, b);
761
+ }
762
+ this.#options = options;
763
+ }
764
+ /**
765
+ * Adds a new item into the queue.
766
+ * @param value The payload associated with the item
767
+ * @param priority Numeric priority (lower = higher priority)
768
+ *
769
+ * Time Complexity: O(log n)
770
+ * Space Complexity: O(1)
771
+ */
772
+ push(value, priority = 0) {
773
+ const node = {
774
+ value,
775
+ priority,
776
+ order: this.#insertionCounter++
777
+ };
778
+ this.#heap.push(node);
779
+ this.#bubbleUp(this.#heap.length - 1);
780
+ }
781
+ /**
782
+ * Removes and returns the highest-priority item.
783
+ * Returns null if the queue is empty.
784
+ *
785
+ * Time Complexity: O(log n)
786
+ * Space Complexity: O(1)
787
+ */
788
+ pop() {
789
+ if (this.#heap.length === 0) return null;
790
+ const top = this.#heap[0];
791
+ const last = this.#heap.pop();
792
+ if (this.#heap.length > 0) {
793
+ this.#heap[0] = last;
794
+ this.#bubbleDown(0);
795
+ }
796
+ return top.value;
797
+ }
798
+ /**
799
+ * Removes and returns many items from the queue.
800
+ * Returns an empty array if the queue is empty.
801
+ */
802
+ popMany(count = 1) {
803
+ const items = [];
804
+ if (count === 0) {
805
+ return items;
806
+ }
807
+ if (count > this.#heap.length) {
808
+ count = this.#heap.length;
809
+ }
810
+ for (let i = count; i > 0; i--) {
811
+ items.push(this.pop());
812
+ }
813
+ return items;
814
+ }
815
+ /**
816
+ * Returns the next item to be dequeued without removing it.
817
+ */
818
+ peek() {
819
+ return this.isEmpty() ? null : this.#heap[0].value;
820
+ }
821
+ /**
822
+ * Returns the next item to be dequeued without removing it.
823
+ */
824
+ peekMany(count = 1) {
825
+ return this.#heap.slice(0, count).map((node) => node.value);
826
+ }
827
+ /**
828
+ * Find an item in the queue by predicate.
829
+ */
830
+ find(predicate) {
831
+ return this.#heap.find((node) => predicate(node.value))?.value ?? null;
832
+ }
833
+ /**
834
+ * Heapify the queue.
835
+ *
836
+ * Time Complexity: O(n)
837
+ * Space Complexity: O(n)
838
+ */
839
+ heapify(items) {
840
+ this.#heap = items.slice(0);
841
+ this.#insertionCounter = items.length;
842
+ for (let i = Math.floor(this.#heap.length / 2); i >= 0; i--) {
843
+ this.#bubbleDown(i);
844
+ }
845
+ }
846
+ clone() {
847
+ const clone2 = new _PriorityQueue(this.#options);
848
+ clone2.heapify(this.#heap);
849
+ return clone2;
850
+ }
851
+ /**
852
+ * Returns a sorted array of the queue.
853
+ */
854
+ toSortedArray() {
855
+ const clone2 = this.clone();
856
+ const sorted = [];
857
+ while (clone2.#heap.length > 0) {
858
+ sorted.push(clone2.pop());
859
+ }
860
+ return sorted;
861
+ }
862
+ /**
863
+ * Returns an iterator over the queue.
864
+ */
865
+ *[Symbol.iterator]() {
866
+ const clone2 = this.clone();
867
+ while (clone2.#heap.length > 0) {
868
+ yield clone2.pop();
869
+ }
870
+ }
871
+ /**
872
+ * Returns the number of items in the queue.
873
+ */
874
+ size() {
875
+ return this.#heap.length;
876
+ }
877
+ /**
878
+ * Returns true if the queue is empty.
879
+ */
880
+ isEmpty() {
881
+ return this.#heap.length === 0;
882
+ }
883
+ /**
884
+ * Clears all items and resets the insertion counter.
885
+ */
886
+ clear() {
887
+ this.#heap = [];
888
+ this.#insertionCounter = 0;
889
+ }
890
+ /**
891
+ * Moves the node at index up to restore heap invariant.
892
+ *
893
+ * Time Complexity: O(log n)
894
+ * Space Complexity: O(1)
895
+ */
896
+ #bubbleUp(index) {
897
+ let idx = index;
898
+ while (idx > 0) {
899
+ const parentIdx = idx - 1 >> 1;
900
+ if (this.#compare(this.#heap[idx], this.#heap[parentIdx]) < 0) {
901
+ this.#swap(idx, parentIdx);
902
+ idx = parentIdx;
903
+ } else {
904
+ break;
905
+ }
906
+ }
907
+ }
908
+ /**
909
+ * Moves the node at index down to restore heap invariant.
910
+ *
911
+ * Time Complexity: O(log n)
912
+ * Space Complexity: O(1)
913
+ */
914
+ #bubbleDown(index) {
915
+ const length = this.#heap.length;
916
+ let idx = index;
917
+ while (true) {
918
+ const left = (idx << 1) + 1;
919
+ const right = left + 1;
920
+ let smallest = idx;
921
+ if (left < length && this.#compare(this.#heap[left], this.#heap[smallest]) < 0) {
922
+ smallest = left;
923
+ }
924
+ if (right < length && this.#compare(this.#heap[right], this.#heap[smallest]) < 0) {
925
+ smallest = right;
926
+ }
927
+ if (smallest === idx) {
928
+ break;
929
+ }
930
+ this.#swap(idx, smallest);
931
+ idx = smallest;
932
+ }
933
+ }
934
+ /**
935
+ * Swaps two nodes in the heap.
936
+ */
937
+ #swap(i, j) {
938
+ [this.#heap[i], this.#heap[j]] = [
939
+ this.#heap[j],
940
+ this.#heap[i]
941
+ ];
942
+ }
943
+ };
944
+
945
+ // node_modules/@logosdx/utils/dist/esm/flow-control/misc.mjs
946
+ var Deferred = class {
947
+ promise;
948
+ resolve;
949
+ reject;
950
+ constructor() {
951
+ this.promise = new Promise((resolve, reject) => {
952
+ this.resolve = resolve;
953
+ this.reject = reject;
954
+ });
955
+ }
956
+ };
957
+ if (typeof Promise.withResolvers !== "function") {
958
+ Promise.withResolvers = () => {
959
+ return new Deferred();
960
+ };
961
+ }
962
+ var TimeoutPromise = class extends Promise {
963
+ clear;
964
+ };
965
+ var wait = (ms, value = true) => {
966
+ let timeout;
967
+ const promise = new TimeoutPromise((resolve) => {
968
+ timeout = setTimeout(() => {
969
+ timeout = null;
970
+ resolve(value);
971
+ }, ms);
972
+ });
973
+ promise.clear = () => {
974
+ if (!timeout) return;
975
+ clearTimeout(timeout);
976
+ timeout = null;
977
+ };
978
+ return promise;
979
+ };
980
+ if (typeof setImmediate !== "function") {
981
+ let nextHandle = 0;
982
+ const tasks = /* @__PURE__ */ new Map();
983
+ const channel = new MessageChannel();
984
+ channel.port1.onmessage = async (event) => {
985
+ const handle = event.data;
986
+ const fn = tasks.get(handle);
987
+ if (!fn) return;
988
+ const [, error] = await attempt(fn);
989
+ if (error) console.error("Error in setImmediate", error);
990
+ };
991
+ globalThis.setImmediate = (fn, ...args) => {
992
+ const handle = nextHandle++;
993
+ tasks.set(handle, () => fn(...args));
994
+ channel.port2.postMessage(handle);
995
+ return handle;
996
+ };
997
+ globalThis.clearImmediate = (handle) => {
998
+ tasks.delete(handle);
999
+ };
1000
+ }
1001
+
1002
+ // node_modules/@logosdx/utils/dist/esm/_helpers.mjs
1003
+ var maps = {
1004
+ retry: /* @__PURE__ */ new WeakMap(),
1005
+ circuitBreaker: /* @__PURE__ */ new WeakMap(),
1006
+ rateLimit: /* @__PURE__ */ new WeakMap(),
1007
+ throttle: /* @__PURE__ */ new WeakMap(),
1008
+ debounce: /* @__PURE__ */ new WeakMap(),
1009
+ memoize: /* @__PURE__ */ new WeakMap(),
1010
+ withTimeout: /* @__PURE__ */ new WeakMap(),
1011
+ inflight: /* @__PURE__ */ new WeakMap()
1012
+ };
1013
+ var assertNotWrapped = (fn, name) => {
1014
+ if (maps[name].has(fn)) {
1015
+ throw new Error(`Function is already wrapped with ${name}`);
1016
+ }
1017
+ };
1018
+
1019
+ // node_modules/@logosdx/utils/dist/esm/async/retry.mjs
1020
+ var RetryError = class extends Error {
1021
+ constructor(message) {
1022
+ super(message);
1023
+ this.name = "RetryError";
1024
+ }
1025
+ };
1026
+ var validateOpts = (opts) => {
1027
+ assert(isPlainObject(opts), "opts must be an object");
1028
+ assertOptional(opts.retries, typeof opts.retries === "number" && opts.retries > 0, "retries must be a positive number");
1029
+ assertOptional(opts.delay, typeof opts.delay === "number" && opts.delay >= 0, "delay must be a positive number");
1030
+ assertOptional(opts.backoff, typeof opts.backoff === "number" && opts.backoff > 0, "backoff must be a positive number");
1031
+ assertOptional(opts.shouldRetry, isFunction(opts.shouldRetry), "shouldRetry must be a function");
1032
+ assertOptional(opts.signal, opts.signal instanceof AbortSignal, "signal must be an AbortSignal");
1033
+ };
1034
+ var retry = async (fn, opts) => {
1035
+ assert(isFunction(fn), "fn must be a function");
1036
+ assertNotWrapped(fn, "retry");
1037
+ validateOpts(opts);
1038
+ const { delay = 0, retries = 3, backoff = 1, jitterFactor = 0, shouldRetry = () => true, signal, throwLastError = false, onRetryExhausted, onRetry } = opts;
1039
+ let attempts = 0;
1040
+ let lastError = null;
1041
+ while (attempts < retries) {
1042
+ signal?.throwIfAborted();
1043
+ if (attempts > 0 && onRetry && lastError) {
1044
+ await onRetry(lastError, attempts);
1045
+ }
1046
+ const [result, error] = await attempt(fn);
1047
+ signal?.throwIfAborted();
1048
+ if (error === null) {
1049
+ return result;
1050
+ }
1051
+ lastError = error;
1052
+ if (error && shouldRetry(error)) {
1053
+ await wait(delay * backoff * (1 + jitterFactor * Math.random()));
1054
+ attempts++;
1055
+ signal?.throwIfAborted();
1056
+ continue;
1057
+ }
1058
+ throw error;
1059
+ }
1060
+ if (onRetryExhausted) {
1061
+ return onRetryExhausted(lastError);
1062
+ }
1063
+ if (throwLastError) {
1064
+ throw lastError;
1065
+ }
1066
+ throw new RetryError("Max retries reached");
1067
+ };
1068
+
1069
+ // node_modules/@logosdx/utils/dist/esm/misc/index.mjs
1070
+ var noop = () => {
1071
+ };
1072
+ var generateId = () => "_" + Math.random().toString(36).slice(2, 9);
1073
+ var unserializableIds = /* @__PURE__ */ new WeakMap();
1074
+ var getUnserializableId = (value) => {
1075
+ if (!unserializableIds.has(value)) {
1076
+ unserializableIds.set(value, generateId());
1077
+ }
1078
+ return unserializableIds.get(value);
1079
+ };
1080
+ var serializer = (args) => {
1081
+ const seen = /* @__PURE__ */ new WeakSet();
1082
+ const stringify = (value) => {
1083
+ if (value === null) return "null";
1084
+ if (value === void 0) return "undefined";
1085
+ if (typeof value === "string") return `${value}`;
1086
+ if (typeof value === "number") {
1087
+ if (Object.is(value, -0)) return "-0";
1088
+ return String(value);
1089
+ }
1090
+ if (typeof value === "boolean") return String(value);
1091
+ if (typeof value === "bigint") return `bi:${value}`;
1092
+ if (typeof value === "symbol") return `sym:${getUnserializableId(value)}`;
1093
+ if (typeof value === "function") return `fn:${getUnserializableId(value)}`;
1094
+ if (value instanceof Date) return `d:${value.getTime()}`;
1095
+ if (value instanceof RegExp) return `r:${value.toString()}`;
1096
+ if (value instanceof Error) return `e:${getUnserializableId(value)}`;
1097
+ if (value instanceof WeakMap) return `wm:${getUnserializableId(value)}`;
1098
+ if (value instanceof WeakSet) return `ws:${getUnserializableId(value)}`;
1099
+ if (typeof value === "object") {
1100
+ if (seen.has(value)) return `circ:${getUnserializableId(value)}`;
1101
+ seen.add(value);
1102
+ if (value instanceof Map) {
1103
+ const pairs2 = Array.from(value.entries()).map(([k, v]) => `${stringify(k)}:${stringify(v)}`).sort();
1104
+ const result2 = `map:${pairs2.join(",")}`;
1105
+ seen.delete(value);
1106
+ return result2;
1107
+ }
1108
+ if (value instanceof Set) {
1109
+ const values = Array.from(value).map(stringify).sort();
1110
+ const result2 = `set:${values.join(",")}`;
1111
+ seen.delete(value);
1112
+ return result2;
1113
+ }
1114
+ if (Array.isArray(value)) {
1115
+ const result2 = `[${value.map(stringify).join(",")}]`;
1116
+ seen.delete(value);
1117
+ return result2;
1118
+ }
1119
+ const keys = Object.keys(value).sort();
1120
+ const pairs = keys.map((key2) => `"${key2}":${stringify(value[key2])}`);
1121
+ const result = `{${pairs.join(",")}}`;
1122
+ seen.delete(value);
1123
+ return result;
1124
+ }
1125
+ return `u:${String(value)}`;
1126
+ };
1127
+ const key = args.map(stringify).join("|");
1128
+ return key || "0";
1129
+ };
1130
+
1131
+ // node_modules/@logosdx/utils/dist/esm/flow-control/memo/helpers.mjs
1132
+ var unwrapValue = (value) => {
1133
+ if (value instanceof WeakRef) {
1134
+ const deref = value.deref();
1135
+ return [
1136
+ deref,
1137
+ deref === void 0
1138
+ ];
1139
+ }
1140
+ return [
1141
+ value,
1142
+ false
1143
+ ];
1144
+ };
1145
+ var createCacheItem = (value, createdAt, expiresAt, useWeakRef, accessSequence) => {
1146
+ const storedValue = useWeakRef && isObject(value) && value !== null ? new WeakRef(value) : value;
1147
+ return {
1148
+ value: storedValue,
1149
+ createdAt,
1150
+ expiresAt,
1151
+ accessCount: 1,
1152
+ lastAccessed: createdAt,
1153
+ accessSequence
1154
+ };
1155
+ };
1156
+ var isExpired = (item) => {
1157
+ return Date.now() >= item.expiresAt;
1158
+ };
1159
+ var updateAccessMetadata = (item, sequence) => {
1160
+ const now = Date.now();
1161
+ item.lastAccessed = now;
1162
+ item.accessCount = (item.accessCount ?? 0) + 1;
1163
+ item.accessSequence = sequence;
1164
+ };
1165
+ var evictLRU = (cache) => {
1166
+ let lruKey = null;
1167
+ let lruTime = Infinity;
1168
+ let lruSequence = Infinity;
1169
+ for (const [key, item] of cache.entries()) {
1170
+ const itemLastAccessed = item.lastAccessed ?? 0;
1171
+ const itemAccessSequence = item.accessSequence ?? 0;
1172
+ const isLessRecent = itemLastAccessed < lruTime || itemLastAccessed === lruTime && itemAccessSequence < lruSequence;
1173
+ if (isLessRecent) {
1174
+ lruTime = itemLastAccessed;
1175
+ lruSequence = itemAccessSequence;
1176
+ lruKey = key;
1177
+ }
1178
+ }
1179
+ if (lruKey) {
1180
+ cache.delete(lruKey);
1181
+ }
1182
+ return lruKey;
1183
+ };
1184
+
1185
+ // node_modules/@logosdx/utils/dist/esm/flow-control/memo/memoizeSync.mjs
1186
+ var memoizedFunctions = /* @__PURE__ */ new WeakSet();
1187
+ var memoizeSync = (fn, opts = {}) => {
1188
+ assert(isFunction(fn), "fn must be a function");
1189
+ assert(!memoizedFunctions.has(fn), "Function is already wrapped by memoize");
1190
+ const { ttl = 6e4, maxSize = 1e3, generateKey, onError, cleanupInterval = 6e4, useWeakRef = false, shouldCache } = opts;
1191
+ const { staleIn, staleTimeout, adapter } = opts;
1192
+ assert(ttl > 0, "ttl must be greater than 0");
1193
+ assert(maxSize > 0, "maxSize must be greater than 0");
1194
+ assert(isOptional(cleanupInterval, (val) => typeof val === "number" && val >= 0), "cleanupInterval must be >= 0");
1195
+ assertOptional(generateKey, isFunction(generateKey), "generateKey must be a function");
1196
+ assertOptional(onError, isFunction(onError), "onError must be a function");
1197
+ assert(adapter === void 0, "memoizeSync does not support custom cache adapters (use memoize for async adapters like Redis)");
1198
+ assert(staleTimeout === void 0, "memoizeSync does not support staleTimeout (sync functions execute instantly)");
1199
+ assert(staleIn === void 0, "memoizeSync does not support staleIn (sync functions execute instantly, use ttl instead)");
1200
+ const cache = /* @__PURE__ */ new Map();
1201
+ let accessSequence = 0;
1202
+ let hits = 0;
1203
+ let misses = 0;
1204
+ let evictions = 0;
1205
+ let cleanupTimer;
1206
+ const getNextSequence = () => {
1207
+ if (accessSequence >= Number.MAX_SAFE_INTEGER - 1) {
1208
+ accessSequence = 0;
1209
+ }
1210
+ return ++accessSequence;
1211
+ };
1212
+ const recordHit = () => hits++;
1213
+ const recordMiss = () => misses++;
1214
+ const cleanupExpired = () => {
1215
+ const now = Date.now();
1216
+ for (const [key, item] of cache.entries()) {
1217
+ if (now >= item.expiresAt) {
1218
+ cache.delete(key);
1219
+ }
1220
+ }
1221
+ };
1222
+ if (cleanupInterval > 0) {
1223
+ cleanupTimer = setInterval(() => cleanupExpired(), cleanupInterval);
1224
+ if (typeof cleanupTimer.unref === "function") {
1225
+ cleanupTimer.unref();
1226
+ }
1227
+ }
1228
+ const memoized = function(...args) {
1229
+ if (shouldCache) {
1230
+ const [shouldCacheResult, shouldCacheError] = attemptSync(() => shouldCache(...args));
1231
+ if (!shouldCacheError && !shouldCacheResult) {
1232
+ return fn(...args);
1233
+ }
1234
+ }
1235
+ const [key, keyError] = attemptSync(() => generateKey ? generateKey(...args) : serializer(args));
1236
+ if (keyError) {
1237
+ onError?.(keyError, args);
1238
+ recordMiss();
1239
+ return fn(...args);
1240
+ }
1241
+ const cached = cache.get(key);
1242
+ if (cached && !isExpired(cached)) {
1243
+ updateAccessMetadata(cached, getNextSequence());
1244
+ const [unwrapped, wasGC] = unwrapValue(cached.value);
1245
+ if (wasGC) {
1246
+ cache.delete(key);
1247
+ recordMiss();
1248
+ const [value2, error2] = attemptSync(() => fn(...args));
1249
+ if (error2) {
1250
+ onError?.(error2, args);
1251
+ throw error2;
1252
+ }
1253
+ const now2 = Date.now();
1254
+ const item2 = createCacheItem(value2, now2, now2 + ttl, useWeakRef, getNextSequence());
1255
+ if (cache.size >= maxSize) {
1256
+ evictLRU(cache);
1257
+ evictions++;
1258
+ }
1259
+ cache.set(key, item2);
1260
+ return value2;
1261
+ }
1262
+ recordHit();
1263
+ return unwrapped;
1264
+ }
1265
+ recordMiss();
1266
+ const [value, error] = attemptSync(() => fn(...args));
1267
+ if (error) {
1268
+ onError?.(error, args);
1269
+ throw error;
1270
+ }
1271
+ const now = Date.now();
1272
+ const item = createCacheItem(value, now, now + ttl, useWeakRef, getNextSequence());
1273
+ if (cache.size >= maxSize) {
1274
+ evictLRU(cache);
1275
+ evictions++;
1276
+ }
1277
+ cache.set(key, item);
1278
+ return value;
1279
+ };
1280
+ memoized.cache = {
1281
+ clear: () => {
1282
+ cache.clear();
1283
+ hits = 0;
1284
+ misses = 0;
1285
+ evictions = 0;
1286
+ accessSequence = 0;
1287
+ if (cleanupTimer !== void 0) {
1288
+ clearInterval(cleanupTimer);
1289
+ cleanupTimer = void 0;
1290
+ }
1291
+ },
1292
+ delete: (key) => {
1293
+ return cache.delete(key);
1294
+ },
1295
+ has: (key) => {
1296
+ const item = cache.get(key);
1297
+ if (!item) {
1298
+ return false;
1299
+ }
1300
+ if (isExpired(item)) {
1301
+ cache.delete(key);
1302
+ return false;
1303
+ }
1304
+ return true;
1305
+ },
1306
+ get size() {
1307
+ return cache.size;
1308
+ },
1309
+ stats: () => {
1310
+ return {
1311
+ hits,
1312
+ misses,
1313
+ evictions,
1314
+ hitRate: hits + misses > 0 ? hits / (hits + misses) : 0,
1315
+ size: cache.size
1316
+ };
1317
+ },
1318
+ keys: () => {
1319
+ return cache.keys();
1320
+ },
1321
+ entries: () => {
1322
+ const results = [];
1323
+ for (const [key, item] of cache.entries()) {
1324
+ if (!isExpired(item)) {
1325
+ const [unwrapped] = unwrapValue(item.value);
1326
+ results.push([
1327
+ key,
1328
+ unwrapped
1329
+ ]);
1330
+ }
1331
+ }
1332
+ return results;
1333
+ }
1334
+ };
1335
+ memoizedFunctions.add(memoized);
1336
+ return memoized;
1337
+ };
1338
+
1339
+ // node_modules/@logosdx/utils/dist/esm/flow-control/rate-limit.mjs
1340
+ var RateLimitTokenBucket = class {
1341
+ #tokens;
1342
+ #lastRefill;
1343
+ #stats;
1344
+ #save;
1345
+ #load;
1346
+ capacity;
1347
+ refillIntervalMs;
1348
+ constructor(config) {
1349
+ assert(isPlainObject(config), "config must be an object");
1350
+ assert(typeof config.capacity === "number" && config.capacity > 0, "capacity must be a positive number");
1351
+ assert(typeof config.refillIntervalMs === "number" && config.refillIntervalMs > 0, "refillIntervalMs must be a positive number");
1352
+ assertOptional(config.save, isFunction(config.save), "save must be a function");
1353
+ assertOptional(config.load, isFunction(config.load), "load must be a function");
1354
+ assertOptional(config.initialState, isPlainObject(config.initialState), "initialState must be an object");
1355
+ this.capacity = config.capacity;
1356
+ this.refillIntervalMs = config.refillIntervalMs;
1357
+ this.#save = config.save;
1358
+ this.#load = config.load;
1359
+ if (config.initialState) {
1360
+ this.#tokens = config.initialState.tokens ?? config.capacity;
1361
+ this.#lastRefill = config.initialState.lastRefill ?? Date.now();
1362
+ this.#stats = {
1363
+ totalRequests: config.initialState.stats?.totalRequests ?? 0,
1364
+ rejectedRequests: config.initialState.stats?.rejectedRequests ?? 0,
1365
+ totalWaitTime: config.initialState.stats?.totalWaitTime ?? 0,
1366
+ waitCount: config.initialState.stats?.waitCount ?? 0,
1367
+ createdAt: config.initialState.stats?.createdAt ?? Date.now()
1368
+ };
1369
+ } else {
1370
+ this.#tokens = config.capacity;
1371
+ this.#lastRefill = Date.now();
1372
+ this.#stats = {
1373
+ totalRequests: 0,
1374
+ rejectedRequests: 0,
1375
+ totalWaitTime: 0,
1376
+ waitCount: 0,
1377
+ createdAt: Date.now()
1378
+ };
1379
+ }
1380
+ }
1381
+ /**
1382
+ * Whether save and load functions are configured for persistence.
1383
+ */
1384
+ get isSaveable() {
1385
+ return isFunction(this.#save) && isFunction(this.#load);
1386
+ }
1387
+ /**
1388
+ * Get the current state for persistence.
1389
+ * This is the minimal data structure needed to restore the bucket.
1390
+ */
1391
+ get state() {
1392
+ this.#refill();
1393
+ return {
1394
+ tokens: this.#tokens,
1395
+ lastRefill: this.#lastRefill,
1396
+ stats: {
1397
+ ...this.#stats
1398
+ }
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Save the current state using the configured save function.
1403
+ * @throws If no save function is configured
1404
+ */
1405
+ async save() {
1406
+ const saveFn = this.#save;
1407
+ if (!isFunction(saveFn)) {
1408
+ throw new Error("No save function configured");
1409
+ }
1410
+ await saveFn(this.state);
1411
+ }
1412
+ /**
1413
+ * Load state from the configured load function.
1414
+ * If the load function returns undefined/null, the bucket state is not modified.
1415
+ * @throws If no load function is configured
1416
+ */
1417
+ async load() {
1418
+ const loadFn = this.#load;
1419
+ if (!isFunction(loadFn)) {
1420
+ throw new Error("No load function configured");
1421
+ }
1422
+ const loadedState = await loadFn();
1423
+ if (loadedState) {
1424
+ this.#tokens = loadedState.tokens ?? this.capacity;
1425
+ this.#lastRefill = loadedState.lastRefill ?? Date.now();
1426
+ if (loadedState.stats) {
1427
+ this.#stats = {
1428
+ totalRequests: loadedState.stats.totalRequests ?? 0,
1429
+ rejectedRequests: loadedState.stats.rejectedRequests ?? 0,
1430
+ totalWaitTime: loadedState.stats.totalWaitTime ?? 0,
1431
+ waitCount: loadedState.stats.waitCount ?? 0,
1432
+ createdAt: loadedState.stats.createdAt ?? Date.now()
1433
+ };
1434
+ }
1435
+ }
1436
+ }
1437
+ /**
1438
+ * Check if there are enough tokens available without consuming them.
1439
+ *
1440
+ * @param count - Number of tokens to check for (default: 1)
1441
+ * @returns true if tokens are available, false otherwise
1442
+ *
1443
+ * @example
1444
+ * if (bucket.hasTokens()) {
1445
+ * // We're within rate limit, proceed
1446
+ * bucket.consume();
1447
+ * }
1448
+ */
1449
+ hasTokens(count = 1) {
1450
+ this.#refill();
1451
+ return this.#tokens >= count;
1452
+ }
1453
+ #refill() {
1454
+ const now = Date.now();
1455
+ const elapsed = now - this.#lastRefill;
1456
+ const refillRate = 1 / this.refillIntervalMs;
1457
+ if (elapsed < 0 || elapsed > this.refillIntervalMs * this.capacity * 2) {
1458
+ this.#lastRefill = now;
1459
+ this.#tokens = this.capacity;
1460
+ return;
1461
+ }
1462
+ if (elapsed > 0) {
1463
+ const tokensToAdd = elapsed * refillRate;
1464
+ this.#tokens = Math.min(this.capacity, this.#tokens + tokensToAdd);
1465
+ this.#lastRefill = now;
1466
+ }
1467
+ }
1468
+ reset() {
1469
+ this.#tokens = this.capacity;
1470
+ this.#lastRefill = Date.now();
1471
+ }
1472
+ get tokens() {
1473
+ return Math.floor(this.#tokens);
1474
+ }
1475
+ consume(count = 1) {
1476
+ this.#refill();
1477
+ this.#stats.totalRequests++;
1478
+ if (this.#tokens >= count) {
1479
+ this.#tokens -= count;
1480
+ return true;
1481
+ }
1482
+ this.#stats.rejectedRequests++;
1483
+ return false;
1484
+ }
1485
+ getWaitTimeMs(count = 1) {
1486
+ this.#refill();
1487
+ const deficit = count - this.#tokens;
1488
+ if (deficit <= 0) return 0;
1489
+ const refillRate = 1 / this.refillIntervalMs;
1490
+ const waitTime = Math.ceil(deficit / refillRate) + 1;
1491
+ return waitTime;
1492
+ }
1493
+ getNextAvailable(count = 1) {
1494
+ return new Date(Date.now() + this.getWaitTimeMs(count));
1495
+ }
1496
+ /**
1497
+ * Get a snapshot of current statistics and state.
1498
+ *
1499
+ * @returns Object containing usage statistics and current state
1500
+ */
1501
+ get snapshot() {
1502
+ this.#refill();
1503
+ const now = Date.now();
1504
+ const uptime = now - this.#stats.createdAt;
1505
+ return {
1506
+ currentTokens: this.tokens,
1507
+ capacity: this.capacity,
1508
+ refillIntervalMs: this.refillIntervalMs,
1509
+ totalRequests: this.#stats.totalRequests,
1510
+ rejectedRequests: this.#stats.rejectedRequests,
1511
+ successfulRequests: this.#stats.totalRequests - this.#stats.rejectedRequests,
1512
+ rejectionRate: this.#stats.totalRequests > 0 ? this.#stats.rejectedRequests / this.#stats.totalRequests : 0,
1513
+ totalWaitTime: this.#stats.totalWaitTime,
1514
+ waitCount: this.#stats.waitCount,
1515
+ averageWaitTime: this.#stats.waitCount > 0 ? this.#stats.totalWaitTime / this.#stats.waitCount : 0,
1516
+ uptime,
1517
+ createdAt: this.#stats.createdAt
1518
+ };
1519
+ }
1520
+ /**
1521
+ * Waits for the next token to be available before
1522
+ * allowing the caller to proceed.
1523
+ *
1524
+ * @param onRateLimit - Callback to invoke when the rate limit is exceeded
1525
+ *
1526
+ * @example
1527
+ * const bucket = new RateLimitTokenBucket({
1528
+ * capacity: 10,
1529
+ * refillIntervalMs: 1000
1530
+ * });
1531
+ *
1532
+ * await bucket.waitForToken(() => {
1533
+ * console.log('Rate limit exceeded');
1534
+ * });
1535
+ * console.log('Token available');
1536
+ *
1537
+ * bucket.consume();
1538
+ * console.log('Token consumed');
1539
+ */
1540
+ async waitForToken(count = 1, opts = {}) {
1541
+ const { onRateLimit, abortController, jitterFactor = 0 } = opts;
1542
+ this.#refill();
1543
+ if (this.#tokens >= count) return;
1544
+ const waitStart = Date.now();
1545
+ this.#stats.waitCount++;
1546
+ while (this.#tokens < count) {
1547
+ if (abortController?.signal?.aborted) return;
1548
+ await onRateLimit?.(new RateLimitError("Rate limit exceeded", this.capacity), this.getNextAvailable(count));
1549
+ await wait(this.getWaitTimeMs(count) + Math.random() * jitterFactor);
1550
+ this.#refill();
1551
+ }
1552
+ const waitEnd = Date.now();
1553
+ this.#stats.totalWaitTime += waitEnd - waitStart;
1554
+ }
1555
+ /**
1556
+ * Waits for tokens to be available and consumes them atomically.
1557
+ *
1558
+ * @param onRateLimit - Callback to invoke when the rate limit is exceeded
1559
+ *
1560
+ * @example
1561
+ * const bucket = new RateLimitTokenBucket({
1562
+ * capacity: 10,
1563
+ * refillIntervalMs: 1000
1564
+ * });
1565
+ *
1566
+ * await bucket.waitAndConsume(() => {
1567
+ * console.log('Rate limit exceeded');
1568
+ * });
1569
+ * console.log('Token acquired and consumed');
1570
+ */
1571
+ async waitAndConsume(count = 1, opts = {}) {
1572
+ const { onRateLimit, abortController, jitterFactor = 0 } = opts;
1573
+ this.#refill();
1574
+ this.#stats.totalRequests++;
1575
+ if (this.#tokens >= count) {
1576
+ this.#tokens -= count;
1577
+ return true;
1578
+ }
1579
+ const waitStart = Date.now();
1580
+ this.#stats.waitCount++;
1581
+ while (this.#tokens < count) {
1582
+ if (abortController?.signal?.aborted) {
1583
+ this.#stats.rejectedRequests++;
1584
+ return false;
1585
+ }
1586
+ await onRateLimit?.(new RateLimitError("Rate limit exceeded", this.capacity), this.getNextAvailable(count));
1587
+ await wait(this.getWaitTimeMs(count) + Math.random() * jitterFactor);
1588
+ this.#refill();
1589
+ }
1590
+ this.#tokens -= count;
1591
+ const waitEnd = Date.now();
1592
+ this.#stats.totalWaitTime += waitEnd - waitStart;
1593
+ return true;
1594
+ }
1595
+ };
1596
+ var RateLimitError = class extends Error {
1597
+ maxCalls;
1598
+ constructor(message, maxCalls) {
1599
+ super(message);
1600
+ this.name = "RateLimitError";
1601
+ this.maxCalls = maxCalls;
1602
+ }
1603
+ };
1604
+
1605
+ // node_modules/@logosdx/utils/dist/esm/flow-control/with-timeout.mjs
1606
+ var TimeoutError = class extends Error {
1607
+ constructor(message) {
1608
+ super(message);
1609
+ }
1610
+ };
1611
+ var isTimeoutError = (error) => {
1612
+ return error?.constructor?.name === TimeoutError.name;
1613
+ };
1614
+ var runWithTimeout = async (func, opts) => {
1615
+ const timeoutError = wait(opts.timeout, [
1616
+ null,
1617
+ new TimeoutError("Function timed out")
1618
+ ]);
1619
+ const [result, error] = await Promise.race([
1620
+ attempt(func),
1621
+ timeoutError
1622
+ ]);
1623
+ if (isTimeoutError(error)) {
1624
+ opts.abortController?.abort();
1625
+ opts.onError?.(error, true);
1626
+ opts.onTimeout?.(error);
1627
+ throw error;
1628
+ }
1629
+ timeoutError.clear();
1630
+ if (error) {
1631
+ opts.onError?.(error, false);
1632
+ if (opts.throws) throw error;
1633
+ }
1634
+ return result;
1635
+ };
1636
+
1637
+ // node_modules/@logosdx/utils/dist/esm/units/time.mjs
1638
+ var timeUnits = {
1639
+ sec: 1e3,
1640
+ min: 60 * 1e3,
1641
+ min15: 15 * 60 * 1e3,
1642
+ min30: 30 * 60 * 1e3,
1643
+ hour: 60 * 60 * 1e3,
1644
+ hour2: 2 * 60 * 60 * 1e3,
1645
+ hour4: 4 * 60 * 60 * 1e3,
1646
+ hour8: 8 * 60 * 60 * 1e3,
1647
+ hour12: 12 * 60 * 60 * 1e3,
1648
+ day: 24 * 60 * 60 * 1e3,
1649
+ week: 7 * 24 * 60 * 60 * 1e3,
1650
+ secs(n) {
1651
+ return n * this.sec;
1652
+ },
1653
+ mins(n) {
1654
+ return n * this.min;
1655
+ },
1656
+ hours(n) {
1657
+ return n * this.hour;
1658
+ },
1659
+ days(n) {
1660
+ return n * this.day;
1661
+ },
1662
+ weeks(n) {
1663
+ return n * this.week;
1664
+ },
1665
+ months(n) {
1666
+ return Math.round(n * 30.4 * this.day);
1667
+ },
1668
+ years(n) {
1669
+ return n * 365 * this.day;
1670
+ }
1671
+ };
1672
+ var seconds = (n) => timeUnits.secs(n);
1673
+ var minutes = (n) => timeUnits.mins(n);
1674
+ var hours = (n) => timeUnits.hours(n);
1675
+ var days = (n) => timeUnits.days(n);
1676
+ var weeks = (n) => timeUnits.weeks(n);
1677
+ var months = (n) => timeUnits.months(n);
1678
+ var years = (n) => timeUnits.years(n);
1679
+ var parseTimeDuration = (str) => {
1680
+ const match = str.match(/^(\d+(?:\.\d+)?)\s*(s|sec|secs?|seconds?|m|min|mins?|minutes?|h|hr|hrs?|hour|hours?|d|day|days?|w|wk|wks?|week|weeks?|mo|mon|mons?|month|months?|y|yr|yrs?|year|years?)$/i);
1681
+ if (!match) {
1682
+ throw new Error(`Invalid time duration: ${str}`);
1683
+ }
1684
+ const [, num, unit] = match;
1685
+ const n = parseFloat(num);
1686
+ const unitLower = unit.toLowerCase();
1687
+ if (unitLower.startsWith("s")) return seconds(n);
1688
+ if (unitLower.startsWith("m") && !unitLower.startsWith("mo")) return minutes(n);
1689
+ if (unitLower.startsWith("h")) return hours(n);
1690
+ if (unitLower.startsWith("d")) return days(n);
1691
+ if (unitLower.startsWith("w")) return weeks(n);
1692
+ if (unitLower.startsWith("mo")) return months(n);
1693
+ if (unitLower.startsWith("y")) return years(n);
1694
+ throw new Error(`Unknown unit: ${unit}`);
1695
+ };
1696
+
1697
+ // node_modules/@logosdx/utils/dist/esm/units/bytes.mjs
1698
+ var byteUnits = {
1699
+ kb: 1024,
1700
+ mb: 1024 ** 2,
1701
+ gb: 1024 ** 3,
1702
+ tb: 1024 ** 4,
1703
+ kbs(n) {
1704
+ return n * this.kb;
1705
+ },
1706
+ mbs(n) {
1707
+ return n * this.mb;
1708
+ },
1709
+ gbs(n) {
1710
+ return n * this.gb;
1711
+ },
1712
+ tbs(n) {
1713
+ return n * this.tb;
1714
+ }
1715
+ };
1716
+ var kilobytes = (n) => byteUnits.kbs(n);
1717
+ var megabytes = (n) => byteUnits.mbs(n);
1718
+ var gigabytes = (n) => byteUnits.gbs(n);
1719
+ var terabytes = (n) => byteUnits.tbs(n);
1720
+ var parseByteSize = (str) => {
1721
+ const match = str.match(/^(\d+(?:\.\d+)?)\s*(kb|kbs?|kilobytes?|mb|mbs?|megabytes?|gb|gbs?|gigabytes?|tb|tbs?|terabytes?)$/i);
1722
+ if (!match) {
1723
+ throw new Error(`Invalid byte size: ${str}`);
1724
+ }
1725
+ const [, num, unit] = match;
1726
+ const n = parseFloat(num);
1727
+ const unitLower = unit.toLowerCase();
1728
+ if (unitLower.startsWith("k")) return kilobytes(n);
1729
+ if (unitLower.startsWith("m")) return megabytes(n);
1730
+ if (unitLower.startsWith("g")) return gigabytes(n);
1731
+ if (unitLower.startsWith("t")) return terabytes(n);
1732
+ throw new Error(`Unknown unit: ${unit}`);
1733
+ };
1734
+
1735
+ // node_modules/@logosdx/utils/dist/esm/config/index.mjs
1736
+ var onlyNumRegex = /^\d+$/;
1737
+ var castValuesToTypes = (obj, opts = {}) => {
1738
+ const { parseUnits = false, skipConversion } = opts;
1739
+ for (const key in obj) {
1740
+ const k = key;
1741
+ const val = obj[k];
1742
+ if (skipConversion?.(key, val)) {
1743
+ continue;
1744
+ }
1745
+ const isObject2 = typeof val === "object" && val !== null;
1746
+ if (isObject2) {
1747
+ castValuesToTypes(val, opts);
1748
+ continue;
1749
+ }
1750
+ if (parseUnits && typeof val === "string") {
1751
+ const [timeDuration, timeErr] = attemptSync(() => parseTimeDuration(val));
1752
+ if (!timeErr && typeof timeDuration === "number") {
1753
+ obj[k] = timeDuration;
1754
+ continue;
1755
+ }
1756
+ const [byteSize, bytesErr] = attemptSync(() => parseByteSize(val));
1757
+ if (!bytesErr && typeof byteSize === "number") {
1758
+ obj[k] = byteSize;
1759
+ continue;
1760
+ }
1761
+ }
1762
+ const truthy = isEnabledValue(obj[k]);
1763
+ const falsy = isDisabledValue(obj[k]);
1764
+ if (truthy || falsy) {
1765
+ obj[k] = truthy;
1766
+ continue;
1767
+ }
1768
+ if (typeof val === "string" && onlyNumRegex.test(val)) {
1769
+ obj[k] = Number(val);
1770
+ continue;
1771
+ }
1772
+ }
1773
+ };
1774
+ var makeNestedConfig = (_flatConfig, opts = {}) => {
1775
+ assert(typeof _flatConfig === "object" && _flatConfig !== null, "flatConfig must be a non-null object");
1776
+ assert(typeof opts === "object" && opts !== null, "opts must be a non-null object");
1777
+ assert(opts.filter === void 0 || typeof opts.filter === "function", "filter must be a function");
1778
+ assert(opts.forceAllCapToLower === void 0 || typeof opts.forceAllCapToLower === "boolean", "forceAllCapToLower must be a boolean");
1779
+ assert(opts.separator === void 0 || typeof opts.separator === "string", "separator must be a string");
1780
+ assert(opts.stripPrefix === void 0 || typeof opts.stripPrefix === "string" || typeof opts.stripPrefix === "number", "stripPrefix must be a string or number");
1781
+ assert(opts.parseUnits === void 0 || typeof opts.parseUnits === "boolean", "parseUnits must be a boolean");
1782
+ assert(opts.skipConversion === void 0 || typeof opts.skipConversion === "function", "skipConversion must be a function");
1783
+ assert(opts.memoizeOpts === void 0 || typeof opts.memoizeOpts === "object" || opts.memoizeOpts === false, "memoizeOpts must be an object or false");
1784
+ const { filter, forceAllCapToLower = true, separator = "_", stripPrefix, parseUnits = false, skipConversion, memoizeOpts = false } = opts;
1785
+ const isAllCaps = (str) => /^[A-Z0-9_]+$/.test(str);
1786
+ const handleCasing = (str) => {
1787
+ let processedStr = str;
1788
+ if (stripPrefix !== void 0) {
1789
+ if (typeof stripPrefix === "number") {
1790
+ processedStr = str.slice(stripPrefix);
1791
+ } else {
1792
+ processedStr = str.startsWith(stripPrefix) ? str.slice(stripPrefix.length) : str;
1793
+ }
1794
+ }
1795
+ const split = processedStr.split(separator);
1796
+ return split.map((s) => {
1797
+ if (isAllCaps(s) && forceAllCapToLower) return s.toLowerCase();
1798
+ return s;
1799
+ }).join(".");
1800
+ };
1801
+ function allConfigs() {
1802
+ const flatConfig = clone(_flatConfig);
1803
+ const config = {};
1804
+ const keys = Object.entries(flatConfig).filter(([key, val]) => filter?.(key, val) ?? true).map(([key]) => key).sort();
1805
+ const [, err] = attemptSync(() => {
1806
+ setDeepMany(config, keys.map((k) => [
1807
+ handleCasing(k),
1808
+ flatConfig[k]
1809
+ ]));
1810
+ castValuesToTypes(config, {
1811
+ parseUnits,
1812
+ skipConversion
1813
+ });
1814
+ });
1815
+ if (err instanceof Error && err.message.includes("on primitive value")) {
1816
+ const key = (k) => k.split("_").join(separator);
1817
+ const eq = (k, v) => `${key(k)}=${v}`;
1818
+ const message = [
1819
+ "Failed to load flatmap variables.",
1820
+ "You're likely trying to set a nested property on a non-object value.",
1821
+ `For example, if you have ${eq("APP_DB_NAME", "foo")}, and then you try to set`,
1822
+ `${eq("APP_DB_NAME_TEST", "bar")}, you'll get this error because ${key("APP_DB_NAME")} is a string.`,
1823
+ "The correct way is to designate each namespace (separated by underscores) as ",
1824
+ `an object. For example, ${eq("APP_DB_NAME", "foo")} becomes { db: { name: "foo" } }, and,`,
1825
+ `${eq("APP_DB_NAME_TEST", "bar")} becomes { db: { name: { test: "bar" } } }, but both cannot coexist.`,
1826
+ `
1827
+
1828
+ You can either \`unset ${key("APP_PROBLEMATIC")}\` or scope all vars to \`${key("APP_NAMESPACE_NAME")}\` to`,
1829
+ "make it a nested object.",
1830
+ "\n\n"
1831
+ ];
1832
+ console.error(message.join(" "));
1833
+ }
1834
+ if (err) throw err;
1835
+ return config;
1836
+ }
1837
+ function getConfig(path, defaultValue) {
1838
+ const config = allConfigs();
1839
+ const value = reach(config, path);
1840
+ if (value === void 0 || value === null) {
1841
+ return defaultValue;
1842
+ }
1843
+ return value;
1844
+ }
1845
+ if (!memoizeOpts) return {
1846
+ allConfigs,
1847
+ getConfig
1848
+ };
1849
+ return {
1850
+ allConfigs: memoizeSync(allConfigs, memoizeOpts),
1851
+ getConfig: memoizeSync(getConfig, memoizeOpts)
1852
+ };
1853
+ };
1854
+
1855
+ // node_modules/@logosdx/observer/dist/esm/helpers.mjs
1856
+ var EventTrace = class extends Error {
1857
+ listener;
1858
+ data;
1859
+ func;
1860
+ event;
1861
+ stack;
1862
+ };
1863
+ var traceStackFilterRgx = new RegExp(`(${[
1864
+ "node_modules",
1865
+ "node:internal",
1866
+ "$spy",
1867
+ "makeEventTracer",
1868
+ "sendToSpy",
1869
+ "Function.spy",
1870
+ "Observable.Engine"
1871
+ ].join("|")})`);
1872
+ var EventError = class extends Error {
1873
+ event;
1874
+ listener;
1875
+ data;
1876
+ constructor(message, opts) {
1877
+ super(message);
1878
+ this.event = opts?.event;
1879
+ this.listener = opts?.listener;
1880
+ this.data = opts?.data;
1881
+ }
1882
+ };
1883
+ var makeEventTracer = (event, caller, listenerOrData) => {
1884
+ const err = new Error();
1885
+ const split = err.stack.split("\n");
1886
+ split.shift();
1887
+ const filtered = split.filter((line) => !traceStackFilterRgx.test(line));
1888
+ const message = `EventStack (${event} ${caller.toString()}):`;
1889
+ filtered.unshift(message);
1890
+ const stack = filtered.join("\n");
1891
+ const tracer = new EventTrace(message);
1892
+ tracer.name = message;
1893
+ tracer.func = caller;
1894
+ tracer.event = event;
1895
+ tracer.stack = stack;
1896
+ tracer.listener = null;
1897
+ tracer.data = null;
1898
+ if (typeof listenerOrData === "function") {
1899
+ tracer.listener = listenerOrData;
1900
+ } else {
1901
+ tracer.data = listenerOrData;
1902
+ }
1903
+ return tracer;
1904
+ };
1905
+ var rgxStrToRgx = (rgxStr) => {
1906
+ const split = rgxStr?.replace(/^\//, "").split("/");
1907
+ const flags = split.pop();
1908
+ const expr = split.join("/");
1909
+ return RegExp(expr, flags);
1910
+ };
1911
+ var arrOfMatchingValues = (vals, map) => {
1912
+ const listeners = [];
1913
+ for (const key of vals) {
1914
+ for (const fn of map.get(key) || /* @__PURE__ */ new Set()) {
1915
+ listeners.push({
1916
+ event: key,
1917
+ func: fn
1918
+ });
1919
+ }
1920
+ }
1921
+ return listeners;
1922
+ };
1923
+ var InternalEvs = /* @__PURE__ */ (function(InternalEvs2) {
1924
+ InternalEvs2["on"] = "on";
1925
+ InternalEvs2["off"] = "off";
1926
+ InternalEvs2["emit"] = "emit";
1927
+ InternalEvs2["clear"] = "clear";
1928
+ return InternalEvs2;
1929
+ })({});
1930
+ var InternalEvent = class extends Event {
1931
+ type;
1932
+ data;
1933
+ constructor(ev, data) {
1934
+ super(ev);
1935
+ this.data = data;
1936
+ this.type = ev;
1937
+ }
1938
+ };
1939
+ var validateEvent = (fn, opts) => {
1940
+ if (opts.event === void 0 || typeof opts.event !== "string" && opts.event instanceof RegExp === false) {
1941
+ throw new EventError(`observer.${fn}: Event must be a string or RegExp`, opts);
1942
+ }
1943
+ };
1944
+ var validateListener = (fn, opts) => {
1945
+ if (opts.listener !== void 0 && typeof opts.listener !== "function") {
1946
+ throw new EventError(`observer.${fn}: Listener must be a function`, opts);
1947
+ }
1948
+ };
1949
+
1950
+ // node_modules/@logosdx/observer/dist/esm/generator.mjs
1951
+ var DeferredEvent = class extends Deferred {
1952
+ cleanup;
1953
+ };
1954
+ var EventGenerator = class {
1955
+ #observer;
1956
+ #event;
1957
+ #buffer;
1958
+ #waiting = null;
1959
+ #done = false;
1960
+ #listener = null;
1961
+ #lastValue = null;
1962
+ #assertNotDestroyed = () => {
1963
+ if (this.#done === true) {
1964
+ throw new EventError(`Event generator for ${this.#event.toString()} has been destroyed`, {
1965
+ event: this.#event,
1966
+ listener: this.#listener,
1967
+ data: null
1968
+ });
1969
+ }
1970
+ };
1971
+ cleanup;
1972
+ next;
1973
+ constructor(observer2, event, options) {
1974
+ this.#observer = observer2;
1975
+ this.#event = event;
1976
+ this.#buffer = new PriorityQueue();
1977
+ this.#listener = (data) => {
1978
+ this.#lastValue = data;
1979
+ if (this.#waiting) {
1980
+ const defer = this.#waiting;
1981
+ this.#waiting = null;
1982
+ defer.resolve(data);
1983
+ } else {
1984
+ this.#buffer.push(data);
1985
+ }
1986
+ };
1987
+ const off = observer2.on(event, this.#listener);
1988
+ let generatorAbortCtrl;
1989
+ this.next = () => {
1990
+ this.#assertNotDestroyed();
1991
+ const buffered = this.#buffer.pop();
1992
+ if (buffered !== null) {
1993
+ return Promise.resolve(buffered);
1994
+ }
1995
+ if (!this.#waiting) {
1996
+ this.#waiting = new DeferredEvent();
1997
+ this.#waiting.promise.cleanup = this.cleanup;
1998
+ this.#waiting.promise.resolve = this.#waiting.resolve;
1999
+ this.#waiting.promise.reject = this.#waiting.reject;
2000
+ }
2001
+ return this.#waiting.promise;
2002
+ };
2003
+ this.cleanup = () => {
2004
+ if (this.#done) return;
2005
+ off();
2006
+ this.#done = true;
2007
+ const abortError = new EventError("Aborted", {
2008
+ event: this.#event,
2009
+ listener: this.#listener,
2010
+ data: null
2011
+ });
2012
+ if (this.#waiting) {
2013
+ this.#waiting.reject(abortError);
2014
+ this.#waiting = null;
2015
+ }
2016
+ this.#_iterPromise.forEach((promise) => {
2017
+ promise.reject?.(abortError);
2018
+ });
2019
+ this.#_iterPromise.clear();
2020
+ this.#buffer.clear();
2021
+ this.#lastValue = null;
2022
+ generatorAbortCtrl?.abort();
2023
+ };
2024
+ const userSignal = options?.signal;
2025
+ if (userSignal) {
2026
+ if (userSignal.aborted) {
2027
+ this.#done = true;
2028
+ return;
2029
+ }
2030
+ generatorAbortCtrl = new AbortController();
2031
+ userSignal.addEventListener("abort", this.cleanup, {
2032
+ signal: generatorAbortCtrl.signal
2033
+ });
2034
+ }
2035
+ }
2036
+ /**
2037
+ * Store iterator's last promise. Handles multiple promises
2038
+ * for when the generator is used in multiple places.
2039
+ */
2040
+ #_iterPromise = /* @__PURE__ */ new Set();
2041
+ async *[Symbol.asyncIterator]() {
2042
+ while (!this.#done) {
2043
+ const promise = this.next();
2044
+ this.#_iterPromise.add(promise);
2045
+ yield await promise;
2046
+ this.#_iterPromise.delete(promise);
2047
+ }
2048
+ return Promise.resolve(void 0);
2049
+ }
2050
+ get lastValue() {
2051
+ return this.#lastValue;
2052
+ }
2053
+ get done() {
2054
+ return this.#done;
2055
+ }
2056
+ emit(data) {
2057
+ this.#assertNotDestroyed();
2058
+ this.#observer.emit(this.#event, data);
2059
+ }
2060
+ };
2061
+
2062
+ // node_modules/@logosdx/observer/dist/esm/queue/state.mjs
2063
+ var QueueStateManager = class {
2064
+ status = "stopped";
2065
+ #allowedTransitions = {
2066
+ ["running"]: [
2067
+ "paused",
2068
+ "draining",
2069
+ "stopped"
2070
+ ],
2071
+ ["draining"]: [
2072
+ "stopped",
2073
+ "paused"
2074
+ ],
2075
+ ["paused"]: [
2076
+ "running",
2077
+ "draining",
2078
+ "stopped"
2079
+ ],
2080
+ ["stopped"]: [
2081
+ "running",
2082
+ "draining"
2083
+ ]
2084
+ };
2085
+ transition(to) {
2086
+ assert(this.#allowedTransitions[this.status].includes(to), `Invalid transition from ${this.status} to ${to}`);
2087
+ this.status = to;
2088
+ }
2089
+ is(...states) {
2090
+ return states.includes(this.status);
2091
+ }
2092
+ get state() {
2093
+ return this.status;
2094
+ }
2095
+ };
2096
+
2097
+ // node_modules/@logosdx/observer/dist/esm/queue/statistics.mjs
2098
+ var QueueStats = class {
2099
+ observer;
2100
+ queueName;
2101
+ #processing;
2102
+ #processed;
2103
+ #avgProcessingTime;
2104
+ #success;
2105
+ #error;
2106
+ #rejected;
2107
+ constructor(observer2, queueName) {
2108
+ this.observer = observer2;
2109
+ this.queueName = queueName;
2110
+ this.#processing = 0;
2111
+ this.#processed = 0;
2112
+ this.#avgProcessingTime = 0;
2113
+ this.#success = 0;
2114
+ this.#error = 0;
2115
+ this.#rejected = 0;
2116
+ this.observer.on(`queue:${this.queueName}:processing`, () => {
2117
+ this.#processing++;
2118
+ });
2119
+ this.observer.on(`queue:${this.queueName}:success`, (wrapped) => {
2120
+ this.#processed++;
2121
+ this.#success++;
2122
+ this.#processing--;
2123
+ this.#calculateAvg(wrapped.data.elapsed);
2124
+ });
2125
+ this.observer.on(`queue:${this.queueName}:error`, () => {
2126
+ this.#processed++;
2127
+ this.#error++;
2128
+ this.#processing--;
2129
+ });
2130
+ this.observer.on(`queue:${this.queueName}:rejected`, () => this.#rejected++);
2131
+ }
2132
+ #calculateAvg(elapsed) {
2133
+ this.#avgProcessingTime = (this.#avgProcessingTime * (this.#success - 1) + elapsed) / this.#success;
2134
+ }
2135
+ get stats() {
2136
+ return {
2137
+ processed: this.#processed,
2138
+ processing: this.#processing,
2139
+ avgProcessingTime: this.#avgProcessingTime,
2140
+ success: this.#success,
2141
+ error: this.#error,
2142
+ rejected: this.#rejected
2143
+ };
2144
+ }
2145
+ };
2146
+
2147
+ // node_modules/@logosdx/observer/dist/esm/queue/helpers.mjs
2148
+ var InternalQueueEvent = class {
2149
+ data;
2150
+ constructor(data) {
2151
+ this.data = data;
2152
+ }
2153
+ };
2154
+ var QueueRejectionReason = /* @__PURE__ */ (function(QueueRejectionReason2) {
2155
+ QueueRejectionReason2["full"] = "Queue is full";
2156
+ QueueRejectionReason2["notRunning"] = "Queue is not running";
2157
+ return QueueRejectionReason2;
2158
+ })({});
2159
+
2160
+ // node_modules/@logosdx/observer/dist/esm/queue/queue.mjs
2161
+ var EventQueue = class {
2162
+ opts;
2163
+ #queue;
2164
+ #priorites;
2165
+ #off;
2166
+ #state;
2167
+ #stats;
2168
+ #rateLimiter;
2169
+ #idle;
2170
+ #waiting;
2171
+ #listening;
2172
+ #debugging;
2173
+ #generation;
2174
+ #activeRunners;
2175
+ #runningNodes;
2176
+ constructor(opts) {
2177
+ this.opts = opts;
2178
+ this.#priorites = /* @__PURE__ */ new Map();
2179
+ this.#off = noop;
2180
+ this.#state = new QueueStateManager();
2181
+ this.#idle = true;
2182
+ this.#waiting = false;
2183
+ this.#listening = false;
2184
+ this.#debugging = false;
2185
+ this.#generation = 0;
2186
+ this.#activeRunners = 0;
2187
+ this.#runningNodes = /* @__PURE__ */ new Set();
2188
+ const { observer: observer2 = new ObserverEngine(), event, process: process2, name, type = "fifo", concurrency = 1, pollIntervalMs = 100, jitterFactor = 0, rateLimitIntervalMs = 1e3, processIntervalMs = 0, taskTimeoutMs = 0, autoStart = true, debug = false } = this.opts;
2189
+ let { maxQueueSize = 999999999, rateLimitCapacity = 999999999 } = this.opts;
2190
+ assert(isPlainObject(this.opts), "Options is required to be an object");
2191
+ assert(isFunction(observer2?.on), "ObserverEngine is required");
2192
+ assert(typeof event === "string" && event.length > 0 || event instanceof RegExp, "Event is required to be a string or RegExp");
2193
+ assert(isFunction(process2), "Process is required to be a function");
2194
+ assert(name && typeof name === "string" && name.length > 0, "Name is required");
2195
+ assert(concurrency > 0, "Concurrency must be greater than 0");
2196
+ assert(pollIntervalMs > 0, "pollIntervalMs must be a number greater than 0");
2197
+ assert(jitterFactor >= 0 && jitterFactor <= 1, "Jitter must be a number greater than or equal to 0 and less than or equal to 1");
2198
+ assert(maxQueueSize > 0, "MaxQueueSize must be a number greater than 0");
2199
+ assert(rateLimitIntervalMs > 0, "rateLimitIntervalMs must be a number greater than 0");
2200
+ assert(rateLimitCapacity > 0, "rateLimitCapacity must be a number greater than 0");
2201
+ assert(processIntervalMs >= 0, "processIntervalMs must be a number greater than or equal to 0");
2202
+ assert(taskTimeoutMs >= 0, "taskTimeoutMs must be a number greater than or equal to 0");
2203
+ assert(type === "fifo" || type === "lifo", 'Type must be either "fifo" or "lifo"');
2204
+ assert(typeof autoStart === "boolean", "AutoStart must be a boolean");
2205
+ if (maxQueueSize === Infinity) {
2206
+ maxQueueSize = 999999999;
2207
+ }
2208
+ if (rateLimitCapacity === Infinity) {
2209
+ rateLimitCapacity = 999999999;
2210
+ }
2211
+ Object.assign(this.opts, {
2212
+ observer: observer2,
2213
+ type,
2214
+ concurrency,
2215
+ maxQueueSize,
2216
+ pollIntervalMs,
2217
+ jitterFactor,
2218
+ processIntervalMs,
2219
+ taskTimeoutMs
2220
+ });
2221
+ this.#debugging = debug;
2222
+ this.#stats = new QueueStats(observer2, name);
2223
+ this.#rateLimiter = new RateLimitTokenBucket({
2224
+ capacity: rateLimitCapacity,
2225
+ refillIntervalMs: rateLimitIntervalMs
2226
+ });
2227
+ this.#queue = new PriorityQueue({
2228
+ lifo: type === "lifo"
2229
+ });
2230
+ if (autoStart) {
2231
+ this.start();
2232
+ }
2233
+ }
2234
+ #listen() {
2235
+ if (this.#listening) return;
2236
+ this.#listening = true;
2237
+ const off = this.opts.observer.on(this.opts.event, (payload) => {
2238
+ const maybeInternal = payload?.data ?? payload;
2239
+ if (maybeInternal instanceof InternalQueueEvent) {
2240
+ return;
2241
+ }
2242
+ const data = payload;
2243
+ const item = {
2244
+ data,
2245
+ _taskId: generateId(),
2246
+ priority: this.#priorites.get(data) ?? 0
2247
+ };
2248
+ this.#priorites.delete(data);
2249
+ if (this.#queue.size() >= this.opts.maxQueueSize) {
2250
+ this.#emit("rejected", {
2251
+ ...item,
2252
+ reason: QueueRejectionReason.full
2253
+ });
2254
+ return;
2255
+ }
2256
+ this.#emit("added", item);
2257
+ this.#idle = false;
2258
+ this.#queue.push(item, item.priority);
2259
+ });
2260
+ this.#off = () => {
2261
+ off();
2262
+ this.#listening = false;
2263
+ };
2264
+ }
2265
+ #emit(event, payload) {
2266
+ if (this.#debugging) {
2267
+ const args = [
2268
+ `[${this.name}] ${event}`,
2269
+ payload?._taskId ?? "",
2270
+ payload?.data ?? ""
2271
+ ];
2272
+ if (this.#debugging === "verbose") {
2273
+ args[1] = payload;
2274
+ }
2275
+ console.log(...args);
2276
+ }
2277
+ this.opts.observer.emit(`queue:${this.name}:${event}`, new InternalQueueEvent(payload));
2278
+ }
2279
+ /**
2280
+ * Setups concurrency and begins processing items
2281
+ */
2282
+ #launchRunners() {
2283
+ const generation = ++this.#generation;
2284
+ for (let i = 0; i < this.opts.concurrency; i++) {
2285
+ this.#workerLoop(generation, i);
2286
+ }
2287
+ }
2288
+ /**
2289
+ * Loops and processes items in the queue until the queue is stopped
2290
+ */
2291
+ async #workerLoop(generation, instance) {
2292
+ const { pollIntervalMs, jitterFactor } = this.opts;
2293
+ this.#activeRunners++;
2294
+ while (this.#state.is("running") && this.#generation === generation) {
2295
+ if (!this.pending) {
2296
+ if (!this.#idle && !this.pending && this.#runningNodes.size === 0) {
2297
+ this.#idle = true;
2298
+ this.#emit("idle");
2299
+ }
2300
+ this.#waiting = true;
2301
+ await wait(pollIntervalMs * (1 + Math.random() * jitterFactor));
2302
+ this.#waiting = false;
2303
+ continue;
2304
+ }
2305
+ const data = this.#queue.pop();
2306
+ if (!data) continue;
2307
+ this.#runningNodes.add(`${generation}-${instance}`);
2308
+ await this.#processNext(data);
2309
+ if (this.opts.processIntervalMs > 0) {
2310
+ await wait(this.opts.processIntervalMs);
2311
+ }
2312
+ this.#runningNodes.delete(`${generation}-${instance}`);
2313
+ }
2314
+ this.#activeRunners--;
2315
+ }
2316
+ /**
2317
+ * Processes the next item in the queue, if the queue is not
2318
+ * in a state that prevents it from processing the item.
2319
+ */
2320
+ async #processNext(item) {
2321
+ if (!this.#state.is("running", "draining")) {
2322
+ this.#queue.push(item);
2323
+ return;
2324
+ }
2325
+ let rateLimited = false;
2326
+ if (!this.#state.is("draining")) {
2327
+ await this.#rateLimiter.waitAndConsume(1, {
2328
+ onRateLimit: () => {
2329
+ this.#emit("rate-limited", item);
2330
+ rateLimited = true;
2331
+ }
2332
+ });
2333
+ }
2334
+ const startedAt = Date.now();
2335
+ this.#emit("processing", {
2336
+ ...item,
2337
+ startedAt,
2338
+ rateLimited
2339
+ });
2340
+ const [, err] = await attempt(async () => {
2341
+ if (this.opts.taskTimeoutMs === 0) {
2342
+ return this.opts.process(item.data);
2343
+ }
2344
+ const result = await Promise.race([
2345
+ this.opts.process(item.data),
2346
+ wait(this.opts.taskTimeoutMs, new TimeoutError("Task timed out"))
2347
+ ]);
2348
+ if (isTimeoutError(result)) {
2349
+ this.#emit("timeout", {
2350
+ ...item,
2351
+ error: result
2352
+ });
2353
+ throw result;
2354
+ }
2355
+ return result;
2356
+ });
2357
+ const elapsed = Date.now() - startedAt;
2358
+ if (err) {
2359
+ this.#emit("error", {
2360
+ ...item,
2361
+ error: err,
2362
+ rateLimited
2363
+ });
2364
+ } else {
2365
+ this.#emit("success", {
2366
+ ...item,
2367
+ startedAt,
2368
+ elapsed,
2369
+ rateLimited
2370
+ });
2371
+ }
2372
+ if (this.#queue.size() === 0 && this.#state.is("running")) {
2373
+ this.#emit("empty");
2374
+ }
2375
+ }
2376
+ /**
2377
+ * Start the queue if it is not already started
2378
+ */
2379
+ start() {
2380
+ if (this.#state.is("running")) return;
2381
+ this.#listen();
2382
+ this.#state.transition("running");
2383
+ this.#emit("start");
2384
+ this.#launchRunners();
2385
+ this.#emit("started");
2386
+ return Promise.resolve();
2387
+ }
2388
+ /**
2389
+ * Stop the queue
2390
+ */
2391
+ stop() {
2392
+ if (this.#state.is("stopped")) return;
2393
+ this.#off();
2394
+ this.#state.transition("stopped");
2395
+ this.#emit("stopped");
2396
+ }
2397
+ /**
2398
+ * Pause the queue
2399
+ */
2400
+ pause() {
2401
+ if (this.#state.is("paused")) return;
2402
+ this.#state.transition("paused");
2403
+ this.#emit("paused");
2404
+ return Promise.resolve();
2405
+ }
2406
+ /**
2407
+ * Resume the queue
2408
+ */
2409
+ resume() {
2410
+ if (this.#state.is("running")) return;
2411
+ this.#listen();
2412
+ this.#state.transition("running");
2413
+ this.#launchRunners();
2414
+ this.#emit("resumed");
2415
+ return Promise.resolve();
2416
+ }
2417
+ /**
2418
+ * Processes a batch of items from the queue, and then
2419
+ * calls the before and after functions. Returns the
2420
+ * number of items processed.
2421
+ */
2422
+ async #processBatch(limit = Infinity, beforeFn, afterFn) {
2423
+ let count = limit === Infinity ? this.#queue.size() : limit;
2424
+ const items = this.#queue.popMany(count);
2425
+ if (count < items.length) {
2426
+ count = items.length;
2427
+ }
2428
+ beforeFn?.(count);
2429
+ if (count !== 0) {
2430
+ for (const item of items) {
2431
+ await this.#processNext(item);
2432
+ }
2433
+ }
2434
+ afterFn?.(count);
2435
+ return count;
2436
+ }
2437
+ /**
2438
+ * Empty and process all items in the queue and
2439
+ * then stop the queue. Returns the number of items
2440
+ * processed.
2441
+ */
2442
+ shutdown(force = false) {
2443
+ if (this.#state.is("draining", "stopped")) return Promise.resolve(0);
2444
+ if (force) {
2445
+ const count = this.purge();
2446
+ this.stop();
2447
+ this.#emit("shutdown", {
2448
+ force,
2449
+ pending: count
2450
+ });
2451
+ return Promise.resolve(count);
2452
+ }
2453
+ return this.#processBatch(Infinity, (pending) => {
2454
+ this.pause();
2455
+ this.#state.transition("draining");
2456
+ this.#off();
2457
+ this.#emit("drain", {
2458
+ pending
2459
+ });
2460
+ }, (drained) => {
2461
+ this.#emit("drained", force ? {
2462
+ pending: drained
2463
+ } : {
2464
+ drained
2465
+ });
2466
+ this.stop();
2467
+ this.#emit("shutdown", force ? {
2468
+ force,
2469
+ pending: drained
2470
+ } : {
2471
+ force
2472
+ });
2473
+ });
2474
+ }
2475
+ /**
2476
+ * Executes `limit` items in the queue
2477
+ * and then emits a `flush` event. Returns the number
2478
+ * of items processed.
2479
+ */
2480
+ async flush(limit = Infinity) {
2481
+ return this.#processBatch(limit, (pending) => this.#emit("flush", {
2482
+ pending
2483
+ }), (flushed) => this.#emit("flushed", {
2484
+ flushed
2485
+ }));
2486
+ }
2487
+ /**
2488
+ * Clears the queue and emits a `purge` event. Returns
2489
+ * the number of items purged.
2490
+ */
2491
+ purge() {
2492
+ const count = this.#queue.size();
2493
+ this.#queue.clear();
2494
+ this.#emit("purged", {
2495
+ count
2496
+ });
2497
+ return count;
2498
+ }
2499
+ /**
2500
+ * Emit an event to the observer, which then gets
2501
+ * picked up by the queue and processed.
2502
+ *
2503
+ * @param data The data to add to the queue
2504
+ * @param priority The priority of the data
2505
+ *
2506
+ * @note If priority is provided, it will be used to determine the order of the data in the queue.
2507
+ * The higher the priority, the sooner the data will be processed.
2508
+ *
2509
+ * @note If priority is not provided, the data will be added to the queue with a priority of 0.
2510
+ */
2511
+ add(data, priority) {
2512
+ if (!this.#state.is("running", "paused")) {
2513
+ this.#emit("rejected", {
2514
+ data,
2515
+ reason: QueueRejectionReason.notRunning
2516
+ });
2517
+ return false;
2518
+ }
2519
+ if (this.#queue.size() >= this.opts.maxQueueSize) {
2520
+ this.#emit("rejected", {
2521
+ data,
2522
+ reason: QueueRejectionReason.full
2523
+ });
2524
+ return false;
2525
+ }
2526
+ if (priority) {
2527
+ this.#priorites.set(data, priority);
2528
+ }
2529
+ this.opts.observer.emit(this.opts.event, data);
2530
+ return true;
2531
+ }
2532
+ debug(on = false) {
2533
+ this.#debugging = on;
2534
+ }
2535
+ #observerForQueue() {
2536
+ return this.opts.observer;
2537
+ }
2538
+ on(event, listener) {
2539
+ return this.#observerForQueue().on(`queue:${this.name}:${event}`, listener);
2540
+ }
2541
+ once(event, listener) {
2542
+ return this.#observerForQueue().once(`queue:${this.name}:${event}`, listener);
2543
+ }
2544
+ off(event, listener) {
2545
+ return this.#observerForQueue().off(`queue:${this.name}:${event}`, listener);
2546
+ }
2547
+ /**
2548
+ * The name of the queue
2549
+ */
2550
+ get name() {
2551
+ return this.opts.name;
2552
+ }
2553
+ /**
2554
+ * Whether the queue is waiting for the
2555
+ * the
2556
+ */
2557
+ get isWaiting() {
2558
+ return this.#waiting;
2559
+ }
2560
+ /**
2561
+ * Whether the queue is idle
2562
+ */
2563
+ get isIdle() {
2564
+ return this.#idle && this.#state.is("running");
2565
+ }
2566
+ /**
2567
+ * Whether the queue is running
2568
+ */
2569
+ get isRunning() {
2570
+ return this.#state.is("running");
2571
+ }
2572
+ /**
2573
+ * Whether the queue is paused
2574
+ */
2575
+ get isPaused() {
2576
+ return this.#state.is("paused");
2577
+ }
2578
+ /**
2579
+ * Whether the queue is stopped
2580
+ */
2581
+ get isStopped() {
2582
+ return this.#state.is("stopped");
2583
+ }
2584
+ /**
2585
+ * Whether the queue is draining
2586
+ */
2587
+ get isDraining() {
2588
+ return this.#state.is("draining");
2589
+ }
2590
+ /**
2591
+ * The current state of the queue
2592
+ */
2593
+ get state() {
2594
+ return this.#state.state;
2595
+ }
2596
+ /**
2597
+ * The number of items in the queue
2598
+ */
2599
+ get pending() {
2600
+ return this.#queue.size();
2601
+ }
2602
+ /**
2603
+ * The stats of the queue
2604
+ */
2605
+ get stats() {
2606
+ return clone(this.#stats.stats);
2607
+ }
2608
+ get snapshot() {
2609
+ return {
2610
+ name: this.name,
2611
+ state: this.state,
2612
+ pending: this.pending,
2613
+ stats: this.stats,
2614
+ rateLimiter: this.#rateLimiter.snapshot,
2615
+ activeRunners: this.#activeRunners,
2616
+ runningNodes: this.#runningNodes,
2617
+ isIdle: this.isIdle,
2618
+ isWaiting: this.isWaiting,
2619
+ isRunning: this.isRunning,
2620
+ isPaused: this.isPaused,
2621
+ isStopped: this.isStopped,
2622
+ isDraining: this.isDraining,
2623
+ isEmpty: this.pending === 0
2624
+ };
2625
+ }
2626
+ };
2627
+
2628
+ // node_modules/@logosdx/observer/dist/esm/engine.mjs
2629
+ var ObserverEngine = class _ObserverEngine {
2630
+ #listenerMap = /* @__PURE__ */ new Map();
2631
+ #rgxListenerMap = /* @__PURE__ */ new Map();
2632
+ #internalListener = new EventTarget();
2633
+ #emitValidator;
2634
+ #spy;
2635
+ // Hidden property for holding the spy function
2636
+ // when debugging is enabled. Used to restore the
2637
+ // original spy function when debugging is disabled.
2638
+ #__spy;
2639
+ // Instance-level AbortController for cleanup
2640
+ #instanceController = new AbortController();
2641
+ #instanceSignal;
2642
+ constructor(options) {
2643
+ if (options) {
2644
+ assert(!options.name || typeof options.name === "string", "Observable options.name must be a string", TypeError);
2645
+ assert(!options.spy || typeof options.spy === "function", "Observable options.spy must be a function", TypeError);
2646
+ assert(!options.emitValidator || typeof options.emitValidator === "function", "Observable options.emitValidator must be a function", TypeError);
2647
+ this.#spy = options.spy;
2648
+ }
2649
+ this.#instanceSignal = this.#instanceController.signal;
2650
+ const userSignal = options?.signal;
2651
+ const clearOnAbort = () => this.clear();
2652
+ this.#instanceSignal.addEventListener("abort", clearOnAbort, {
2653
+ once: true
2654
+ });
2655
+ if (userSignal) {
2656
+ userSignal.addEventListener("abort", clearOnAbort, {
2657
+ once: true
2658
+ });
2659
+ }
2660
+ definePrivateProps(this, {
2661
+ on: this.on,
2662
+ once: this.once,
2663
+ emit: this.emit,
2664
+ off: this.off,
2665
+ observe: this.observe,
2666
+ debug: this.debug,
2667
+ $has: this.$has,
2668
+ $facts: this.$facts,
2669
+ $internals: this.$internals,
2670
+ name: options?.name || Math.random().toString(36).substring(7)
2671
+ });
2672
+ this.#emitValidator = options?.emitValidator;
2673
+ }
2674
+ name;
2675
+ /**
2676
+ * Returns facts about the the internal state of the observable instance.
2677
+ */
2678
+ $facts() {
2679
+ const listenKeys = [
2680
+ ...this.#listenerMap.keys()
2681
+ ];
2682
+ const rgxKeys = [
2683
+ ...this.#rgxListenerMap.keys()
2684
+ ];
2685
+ const listenerCounts = Object.fromEntries([
2686
+ listenKeys.map((k) => [
2687
+ k,
2688
+ this.#listenerMap.get(k)?.size
2689
+ ]),
2690
+ rgxKeys.map((k) => [
2691
+ k,
2692
+ this.#rgxListenerMap.get(k)?.size
2693
+ ])
2694
+ ].flat());
2695
+ return {
2696
+ listeners: listenKeys,
2697
+ rgxListeners: rgxKeys,
2698
+ listenerCounts,
2699
+ hasSpy: !!this.#spy
2700
+ };
2701
+ }
2702
+ /**
2703
+ * The internals of the observable instance.
2704
+ *
2705
+ * NOTE: Do not use this to try to meddle with the
2706
+ * internals of the observable instance. This is for
2707
+ * debugging purposes only.
2708
+ */
2709
+ $internals() {
2710
+ return {
2711
+ listenerMap: clone(this.#listenerMap),
2712
+ rgxListenerMap: clone(this.#rgxListenerMap),
2713
+ internalListener: clone(this.#internalListener),
2714
+ name: this.name,
2715
+ spy: this.#spy
2716
+ };
2717
+ }
2718
+ $has(event) {
2719
+ if (event instanceof RegExp) {
2720
+ return this.#rgxListenerMap.has(event.toString());
2721
+ }
2722
+ return this.#listenerMap.has(event) || this.#rgxListenerMap.has(event);
2723
+ }
2724
+ #currentSpy(...args) {
2725
+ if (this.#spy) {
2726
+ this.#spy.apply(this, args);
2727
+ }
2728
+ }
2729
+ /**
2730
+ * Enables or disables debugging for the observable instance.
2731
+ * Works in conjunction with your spy function. Provides a
2732
+ * stack trace of events that are triggered, listened to, and
2733
+ * cleaned up.
2734
+ *
2735
+ * @param on Whether to enable or disable debugging
2736
+ */
2737
+ debug(on = true) {
2738
+ const original = this.#spy;
2739
+ const spy = (ev) => {
2740
+ const { event, fn, data, listener } = ev;
2741
+ console.info(makeEventTracer(event, fn, data || listener));
2742
+ original && original(ev);
2743
+ };
2744
+ if (on) {
2745
+ this.#spy = spy;
2746
+ this.#__spy = original;
2747
+ return;
2748
+ }
2749
+ this.#spy = this.#__spy;
2750
+ }
2751
+ /**
2752
+ * Sets the spy function for the observable instance.
2753
+ * @param spy The spy function to set
2754
+ * @param force Whether to force the spy function to be set even if one is already set
2755
+ */
2756
+ spy(spy, force = false) {
2757
+ assert(isFunction(spy), "spy must be a function", TypeError);
2758
+ assert(force || this.#spy === void 0, "you already have a spy function set", TypeError);
2759
+ this.#spy = spy;
2760
+ }
2761
+ /**
2762
+ * Observes given component as an extension of this observable instance.
2763
+ * @param component Component to wrap events around
2764
+ * @param options Optional configuration including signal for cleanup
2765
+ *
2766
+ * @example
2767
+ *
2768
+ * const obs = new ObserverEngine();
2769
+ *
2770
+ * const modal = {};
2771
+ *
2772
+ * obs.observe(modal);
2773
+ *
2774
+ * modal.on('modal-open', () => {});
2775
+ *
2776
+ * obs.trigger('modal-open'); // opens modal
2777
+ * modal.trigger('modal-open'); // opens modal
2778
+ *
2779
+ * modal.cleanup(); // clears all event listeners
2780
+ */
2781
+ observe(component, options) {
2782
+ const self = this;
2783
+ const userSignal = options?.signal;
2784
+ if (userSignal?.aborted) {
2785
+ definePrivateProps(component, {
2786
+ on: noop,
2787
+ once: noop,
2788
+ off: noop,
2789
+ emit: noop,
2790
+ clear: noop,
2791
+ cleanup: noop
2792
+ });
2793
+ return component;
2794
+ }
2795
+ const track = /* @__PURE__ */ new Map();
2796
+ const trackListener = (event, fn) => {
2797
+ const _set = track.get(event) || /* @__PURE__ */ new Set();
2798
+ _set.add(fn);
2799
+ track.set(event, _set);
2800
+ return fn;
2801
+ };
2802
+ const rmAll = () => {
2803
+ for (const entry of track.entries()) {
2804
+ const [ev, _set] = entry;
2805
+ [
2806
+ ..._set
2807
+ ].forEach((fn) => self.off(ev, fn));
2808
+ track.set(ev, /* @__PURE__ */ new Set());
2809
+ }
2810
+ };
2811
+ const afterOff = (_event) => {
2812
+ const [event, callback] = _event.data;
2813
+ const _set = track.get(event);
2814
+ _set?.delete(callback);
2815
+ };
2816
+ this.#internalListener.addEventListener(InternalEvs.off, afterOff);
2817
+ this.#internalListener.addEventListener(InternalEvs.clear, rmAll);
2818
+ const on = (ev, fn) => {
2819
+ return self.on(ev, trackListener(ev, fn));
2820
+ };
2821
+ const once = (ev, fn) => {
2822
+ return self.once(ev, trackListener(ev, fn));
2823
+ };
2824
+ const off = (ev, fn) => {
2825
+ self.off(ev, fn);
2826
+ };
2827
+ const emit = (ev, data) => {
2828
+ return self.emit(ev, data);
2829
+ };
2830
+ const clear = () => rmAll();
2831
+ let observeAbortCtrl;
2832
+ const cleanup = () => {
2833
+ rmAll();
2834
+ self.#internalListener.removeEventListener(InternalEvs.off, afterOff);
2835
+ self.#internalListener.removeEventListener(InternalEvs.clear, rmAll);
2836
+ observeAbortCtrl?.abort();
2837
+ };
2838
+ if (userSignal) {
2839
+ observeAbortCtrl = new AbortController();
2840
+ const composedSignal = AbortSignal.any([
2841
+ this.#instanceSignal,
2842
+ userSignal
2843
+ ]);
2844
+ composedSignal.addEventListener("abort", cleanup, {
2845
+ signal: observeAbortCtrl.signal
2846
+ });
2847
+ }
2848
+ definePrivateProps(component, {
2849
+ on,
2850
+ once,
2851
+ off,
2852
+ emit,
2853
+ clear,
2854
+ cleanup
2855
+ });
2856
+ return component;
2857
+ }
2858
+ /**
2859
+ * Gets information about the event, whether it's a regex or not,
2860
+ * the event name, and the regex itself.
2861
+ */
2862
+ #eventInfo(event) {
2863
+ const isRgx = event.constructor === RegExp;
2864
+ const eventName = event.toString();
2865
+ return {
2866
+ isRgx,
2867
+ eventName,
2868
+ rgx: event
2869
+ };
2870
+ }
2871
+ /**
2872
+ * Returns all event names that match the regex
2873
+ */
2874
+ #withRgxMatchKeys(rgx) {
2875
+ return [
2876
+ ...this.#listenerMap.keys()
2877
+ ].filter((k) => rgx.test(k));
2878
+ }
2879
+ /**
2880
+ * Returns all regexes that match the key
2881
+ */
2882
+ #withKeyMatchRgx(key) {
2883
+ return [
2884
+ ...this.#rgxListenerMap.keys()
2885
+ ].filter((s) => rgxStrToRgx(s).test(key)).flat();
2886
+ }
2887
+ /**
2888
+ * Returns all event names that match the regex
2889
+ */
2890
+ #matchStr(rgx) {
2891
+ const events = this.#withRgxMatchKeys(rgx);
2892
+ return arrOfMatchingValues(events, this.#listenerMap);
2893
+ }
2894
+ /**
2895
+ * Returns all regexes that match the key
2896
+ */
2897
+ #matchRgx(str) {
2898
+ const events = this.#withKeyMatchRgx(str);
2899
+ return arrOfMatchingValues(events, this.#rgxListenerMap);
2900
+ }
2901
+ /**
2902
+ * Listen for an event
2903
+ * @param event
2904
+ * @param listenerOrOptions - Either a callback function or options object
2905
+ * @param options
2906
+ */
2907
+ on(event, listenerOrOptions, options) {
2908
+ const isListenerFn = typeof listenerOrOptions === "function";
2909
+ const listener = isListenerFn ? listenerOrOptions : void 0;
2910
+ const resolvedOptions = isListenerFn ? options : listenerOrOptions;
2911
+ if (!resolvedOptions?.once) {
2912
+ validateEvent("on", {
2913
+ event,
2914
+ listener
2915
+ });
2916
+ validateListener("on", {
2917
+ event,
2918
+ listener
2919
+ });
2920
+ }
2921
+ if (listener === void 0) {
2922
+ return new EventGenerator(this, event, resolvedOptions);
2923
+ }
2924
+ const userSignal = resolvedOptions?.signal;
2925
+ if (userSignal?.aborted) {
2926
+ return () => {
2927
+ };
2928
+ }
2929
+ const { eventName, isRgx } = this.#eventInfo(event);
2930
+ const listenerMap = isRgx ? this.#rgxListenerMap : this.#listenerMap;
2931
+ this.#currentSpy({
2932
+ event,
2933
+ fn: resolvedOptions?.once ? "once" : "on",
2934
+ data: null,
2935
+ listener,
2936
+ context: this
2937
+ });
2938
+ const cbSet = listenerMap.get(eventName) || /* @__PURE__ */ new Set([
2939
+ listener
2940
+ ]);
2941
+ if (cbSet && !cbSet.has(listener)) {
2942
+ cbSet.add(listener);
2943
+ }
2944
+ if (!listenerMap.has(eventName)) {
2945
+ listenerMap.set(eventName, cbSet);
2946
+ }
2947
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.on, [
2948
+ event,
2949
+ listener
2950
+ ]));
2951
+ let cleanedUp = false;
2952
+ const cleanup = () => {
2953
+ if (cleanedUp) return;
2954
+ cleanedUp = true;
2955
+ this.#currentSpy({
2956
+ event,
2957
+ fn: "cleanup",
2958
+ data: null,
2959
+ listener,
2960
+ context: this
2961
+ });
2962
+ cbSet.delete(listener);
2963
+ if (cbSet.size === 0) {
2964
+ listenerMap.delete(eventName);
2965
+ }
2966
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.off, [
2967
+ event,
2968
+ listener
2969
+ ]));
2970
+ };
2971
+ if (userSignal) {
2972
+ const abortHandler = () => {
2973
+ cleanup();
2974
+ this.#instanceSignal.removeEventListener("abort", abortHandler);
2975
+ };
2976
+ userSignal.addEventListener("abort", abortHandler, {
2977
+ once: true
2978
+ });
2979
+ this.#instanceSignal.addEventListener("abort", abortHandler, {
2980
+ once: true
2981
+ });
2982
+ const originalCleanup = cleanup;
2983
+ const wrappedCleanup = () => {
2984
+ originalCleanup();
2985
+ userSignal.removeEventListener("abort", abortHandler);
2986
+ this.#instanceSignal.removeEventListener("abort", abortHandler);
2987
+ };
2988
+ return wrappedCleanup;
2989
+ }
2990
+ return cleanup;
2991
+ }
2992
+ /**
2993
+ * Executes a callback once when the specified
2994
+ * event is emitted, or returns a promise that
2995
+ * resolves when the event is emitted
2996
+ */
2997
+ once(event, listenerOrOptions, options) {
2998
+ const isListenerFn = typeof listenerOrOptions === "function";
2999
+ const listener = isListenerFn ? listenerOrOptions : void 0;
3000
+ const resolvedOptions = isListenerFn ? options : listenerOrOptions;
3001
+ validateEvent("once", {
3002
+ event,
3003
+ listener
3004
+ });
3005
+ validateListener("once", {
3006
+ event,
3007
+ listener
3008
+ });
3009
+ if (!listener) {
3010
+ const defer = new DeferredEvent();
3011
+ const userSignal = resolvedOptions?.signal;
3012
+ if (userSignal?.aborted) {
3013
+ defer.reject(userSignal.reason ?? new DOMException("Aborted", "AbortError"));
3014
+ defer.promise.cleanup = () => {
3015
+ };
3016
+ return defer.promise;
3017
+ }
3018
+ let promiseAbortCtrl;
3019
+ const cleanup = this.once(event, (data) => {
3020
+ defer.resolve(data);
3021
+ promiseAbortCtrl?.abort();
3022
+ }, resolvedOptions);
3023
+ if (userSignal) {
3024
+ promiseAbortCtrl = new AbortController();
3025
+ userSignal.addEventListener("abort", () => {
3026
+ cleanup();
3027
+ defer.reject(userSignal.reason ?? new DOMException("Aborted", "AbortError"));
3028
+ }, {
3029
+ signal: promiseAbortCtrl.signal
3030
+ });
3031
+ }
3032
+ defer.promise.cleanup = () => {
3033
+ cleanup();
3034
+ promiseAbortCtrl?.abort();
3035
+ };
3036
+ return defer.promise;
3037
+ }
3038
+ const self = this;
3039
+ const runOnce = function(...args) {
3040
+ const { eventName, isRgx } = self.#eventInfo(event);
3041
+ const listenerMap = isRgx ? self.#rgxListenerMap : self.#listenerMap;
3042
+ const fns = listenerMap.get(eventName);
3043
+ if (fns) {
3044
+ fns.delete(runOnce);
3045
+ if (fns.size === 0) listenerMap.delete(eventName);
3046
+ }
3047
+ listener.apply(self, args);
3048
+ };
3049
+ return this.on(event, runOnce, {
3050
+ once: true,
3051
+ ...resolvedOptions
3052
+ });
3053
+ }
3054
+ /**
3055
+ * Stop listening for an event
3056
+ * @param event
3057
+ * @param listener
3058
+ */
3059
+ off(event, listener) {
3060
+ validateEvent("off", {
3061
+ event,
3062
+ listener
3063
+ });
3064
+ this.#currentSpy({
3065
+ event,
3066
+ fn: "off",
3067
+ data: null,
3068
+ listener,
3069
+ context: this
3070
+ });
3071
+ const { eventName, isRgx, rgx } = this.#eventInfo(event);
3072
+ const matches = isRgx ? this.#withRgxMatchKeys(rgx) : [
3073
+ eventName
3074
+ ];
3075
+ matches.forEach((_ev) => {
3076
+ const ev = _ev;
3077
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.off, [
3078
+ ev,
3079
+ listener
3080
+ ]));
3081
+ if (listener) {
3082
+ const fns = this.#listenerMap.get(ev);
3083
+ if (fns) {
3084
+ fns.delete(listener);
3085
+ if (fns.size === 0) this.#listenerMap.delete(ev);
3086
+ }
3087
+ return;
3088
+ }
3089
+ this.#listenerMap.delete(ev);
3090
+ });
3091
+ }
3092
+ /** Emits an event */
3093
+ emit(event, data) {
3094
+ validateEvent("emit", {
3095
+ event,
3096
+ data
3097
+ });
3098
+ if (this.#emitValidator) {
3099
+ this.#emitValidator(event, data, this);
3100
+ }
3101
+ this.#currentSpy({
3102
+ event,
3103
+ fn: "emit",
3104
+ data,
3105
+ listener: null,
3106
+ context: this
3107
+ });
3108
+ const { eventName, isRgx, rgx } = this.#eventInfo(event);
3109
+ if (!isRgx) {
3110
+ const cbs2 = this.#listenerMap.get(eventName);
3111
+ const rgxCbs = this.#matchRgx(eventName);
3112
+ if (cbs2) cbs2.forEach((fn) => fn.apply(this, [
3113
+ data,
3114
+ {
3115
+ event,
3116
+ listener: fn
3117
+ }
3118
+ ]));
3119
+ if (rgxCbs) rgxCbs.forEach(({ func }) => func.apply(this, [
3120
+ {
3121
+ data,
3122
+ event,
3123
+ listener: func
3124
+ }
3125
+ ]));
3126
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.emit, [
3127
+ eventName,
3128
+ data
3129
+ ]));
3130
+ return;
3131
+ }
3132
+ const cbs = this.#matchStr(rgx);
3133
+ if (cbs) cbs.forEach(({ event: event2, func }) => func.apply(this, [
3134
+ data,
3135
+ {
3136
+ event: event2,
3137
+ listener: func
3138
+ }
3139
+ ]));
3140
+ this.#withRgxMatchKeys(rgx).forEach((ev) => {
3141
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.emit, [
3142
+ ev,
3143
+ data
3144
+ ]));
3145
+ });
3146
+ }
3147
+ clear() {
3148
+ this.#listenerMap.clear();
3149
+ this.#rgxListenerMap.clear();
3150
+ this.#internalListener.dispatchEvent(new InternalEvent(InternalEvs.clear, [
3151
+ "clear",
3152
+ null
3153
+ ]));
3154
+ }
3155
+ queue(event, process2, options) {
3156
+ return new EventQueue({
3157
+ ...options,
3158
+ event,
3159
+ process: process2,
3160
+ observer: this
3161
+ });
3162
+ }
3163
+ /**
3164
+ * Checks if an event key passes through the filter/exclude pipeline.
3165
+ * Filter narrows first, then exclude removes from that set.
3166
+ */
3167
+ static #passesFilter(event, options) {
3168
+ if (!options) return true;
3169
+ const { filter, exclude } = options;
3170
+ if (filter) {
3171
+ const passes = filter.some((f) => f instanceof RegExp ? f.test(event) : f === event);
3172
+ if (!passes) return false;
3173
+ }
3174
+ if (exclude) {
3175
+ const blocked = exclude.some((e) => e instanceof RegExp ? e.test(event) : e === event);
3176
+ if (blocked) return false;
3177
+ }
3178
+ return true;
3179
+ }
3180
+ /**
3181
+ * Moves or copies listeners between two ObserverEngine instances.
3182
+ * Static methods on the same class can access # private fields directly.
3183
+ */
3184
+ static #moveListeners(source, target, remove, options) {
3185
+ for (const [event, callbacks] of source.#listenerMap) {
3186
+ if (!_ObserverEngine.#passesFilter(event, options)) continue;
3187
+ const targetSet = target.#listenerMap.get(event) || /* @__PURE__ */ new Set();
3188
+ for (const cb of callbacks) {
3189
+ targetSet.add(cb);
3190
+ }
3191
+ target.#listenerMap.set(event, targetSet);
3192
+ if (remove) {
3193
+ source.#listenerMap.delete(event);
3194
+ }
3195
+ }
3196
+ for (const [event, callbacks] of source.#rgxListenerMap) {
3197
+ if (!_ObserverEngine.#passesFilter(event, options)) continue;
3198
+ const targetSet = target.#rgxListenerMap.get(event) || /* @__PURE__ */ new Set();
3199
+ for (const cb of callbacks) {
3200
+ targetSet.add(cb);
3201
+ }
3202
+ target.#rgxListenerMap.set(event, targetSet);
3203
+ if (remove) {
3204
+ source.#rgxListenerMap.delete(event);
3205
+ }
3206
+ }
3207
+ }
3208
+ /**
3209
+ * Transfers all matching listeners from source to target, removing
3210
+ * them from the source. Target's existing listeners are preserved.
3211
+ *
3212
+ * Useful when cloning an engine (e.g. FetchEngine) and carrying
3213
+ * over observability listeners to the new instance.
3214
+ *
3215
+ * @example
3216
+ *
3217
+ * const old = new ObserverEngine();
3218
+ * const next = new ObserverEngine();
3219
+ *
3220
+ * old.on('ready', handler);
3221
+ *
3222
+ * ObserverEngine.transfer(old, next);
3223
+ * // `next` now owns the 'ready' listener; `old` has none
3224
+ *
3225
+ * @example
3226
+ *
3227
+ * // Transfer only specific events
3228
+ * ObserverEngine.transfer(old, next, {
3229
+ * filter: ['ready', /^user\./]
3230
+ * });
3231
+ */
3232
+ static transfer(source, target, options) {
3233
+ _ObserverEngine.#moveListeners(source, target, true, options);
3234
+ }
3235
+ /**
3236
+ * Copies all matching listeners from source to target without
3237
+ * removing them from the source. Target's existing listeners
3238
+ * are preserved.
3239
+ *
3240
+ * Useful when forking an engine so both instances react to the
3241
+ * same events independently.
3242
+ *
3243
+ * @example
3244
+ *
3245
+ * const primary = new ObserverEngine();
3246
+ * const mirror = new ObserverEngine();
3247
+ *
3248
+ * primary.on('update', handler);
3249
+ *
3250
+ * ObserverEngine.copy(primary, mirror);
3251
+ * // Both engines now have the 'update' listener
3252
+ *
3253
+ * @example
3254
+ *
3255
+ * // Copy everything except internal events
3256
+ * ObserverEngine.copy(primary, mirror, {
3257
+ * exclude: [/^__/]
3258
+ * });
3259
+ */
3260
+ static copy(source, target, options) {
3261
+ _ObserverEngine.#moveListeners(source, target, false, options);
3262
+ }
3263
+ };
3264
+
3265
+ // node_modules/@logosdx/observer/dist/esm/relay.mjs
3266
+ var ObserverRelay = class {
3267
+ #pub;
3268
+ #sub;
3269
+ #subEmit;
3270
+ #isShutdown = false;
3271
+ emit;
3272
+ on;
3273
+ once;
3274
+ off;
3275
+ queue;
3276
+ constructor(options) {
3277
+ const name = options?.name;
3278
+ this.#pub = new ObserverEngine({
3279
+ name: name ? `${name}:pub` : void 0,
3280
+ spy: options?.spy,
3281
+ signal: options?.signal,
3282
+ emitValidator: options?.emitValidator?.pub
3283
+ });
3284
+ this.#sub = new ObserverEngine({
3285
+ name: name ? `${name}:sub` : void 0,
3286
+ spy: options?.spy,
3287
+ signal: options?.signal,
3288
+ emitValidator: options?.emitValidator?.sub
3289
+ });
3290
+ this.on = this.#sub.on.bind(this.#sub);
3291
+ this.once = this.#sub.once.bind(this.#sub);
3292
+ this.off = this.#sub.off.bind(this.#sub);
3293
+ this.queue = this.#sub.queue.bind(this.#sub);
3294
+ this.#subEmit = this.#sub.emit.bind(this.#sub);
3295
+ const pubEmit = this.#pub.emit.bind(this.#pub);
3296
+ this.emit = (event, data) => {
3297
+ if (this.#isShutdown) return;
3298
+ pubEmit(event, data);
3299
+ };
3300
+ this.#pub.on(/.+/, ({ event, data }) => this.send(event, data));
3301
+ if (options?.signal) {
3302
+ options.signal.addEventListener("abort", () => {
3303
+ this.#isShutdown = true;
3304
+ });
3305
+ }
3306
+ }
3307
+ receive(event, data, ctx) {
3308
+ if (this.#isShutdown) return;
3309
+ this.#subEmit(event, {
3310
+ data,
3311
+ ctx
3312
+ });
3313
+ }
3314
+ spy(spy) {
3315
+ if (this.#isShutdown) return;
3316
+ this.#pub.spy(spy, true);
3317
+ this.#sub.spy(spy, true);
3318
+ }
3319
+ $has(event) {
3320
+ return {
3321
+ pub: this.#pub.$has(event),
3322
+ sub: this.#sub.$has(event)
3323
+ };
3324
+ }
3325
+ $facts() {
3326
+ return {
3327
+ pub: this.#pub.$facts(),
3328
+ sub: this.#sub.$facts()
3329
+ };
3330
+ }
3331
+ $internals() {
3332
+ return {
3333
+ pub: this.#pub.$internals(),
3334
+ sub: this.#sub.$internals()
3335
+ };
3336
+ }
3337
+ get isShutdown() {
3338
+ return this.#isShutdown;
3339
+ }
3340
+ shutdown() {
3341
+ if (this.#isShutdown) return;
3342
+ this.#isShutdown = true;
3343
+ this.#pub.clear();
3344
+ this.#sub.clear();
3345
+ }
3346
+ };
3347
+
3348
+ // src/core/environment.ts
3349
+ function isDebug() {
3350
+ return isEnvTruthy(process.env["NOORM_DEBUG"]);
3351
+ }
3352
+ function isEnvTruthy(value) {
3353
+ if (!value) return false;
3354
+ const normalized = value.toLowerCase();
3355
+ return normalized !== "0" && normalized !== "false";
3356
+ }
3357
+ function shouldSkipConfirmations() {
3358
+ return isEnvTruthy(process.env["NOORM_YES"]);
3359
+ }
3360
+ function getEnvConfigName() {
3361
+ return process.env["NOORM_CONFIG"];
3362
+ }
3363
+
3364
+ // src/core/observer.ts
3365
+ var observer = new ObserverEngine({
3366
+ name: "noorm",
3367
+ spy: isDebug() ? (action) => console.error(`[noorm:${action.fn}] ${String(action.event)}`) : void 0
3368
+ });
3369
+
3370
+ export { ObserverRelay, attempt, attemptSync, clone, equals, getEnvConfigName, gigabytes, isDebug, makeNestedConfig, merge, observer, retry, runWithTimeout, shouldSkipConfirmations, wait };
3371
+ //# sourceMappingURL=chunk-QAECL4RN.js.map
3372
+ //# sourceMappingURL=chunk-QAECL4RN.js.map