@likec4/log 1.17.1 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1938 @@
1
+ 'use strict';
2
+
3
+ const LogLevels = {
4
+ silent: Number.NEGATIVE_INFINITY,
5
+ fatal: 0,
6
+ error: 0,
7
+ warn: 1,
8
+ log: 2,
9
+ info: 3,
10
+ success: 3,
11
+ fail: 3,
12
+ ready: 3,
13
+ start: 3,
14
+ box: 3,
15
+ debug: 4,
16
+ trace: 5,
17
+ verbose: Number.POSITIVE_INFINITY
18
+ };
19
+ const LogTypes = {
20
+ // Silent
21
+ silent: {
22
+ level: -1
23
+ },
24
+ // Level 0
25
+ fatal: {
26
+ level: LogLevels.fatal
27
+ },
28
+ error: {
29
+ level: LogLevels.error
30
+ },
31
+ // Level 1
32
+ warn: {
33
+ level: LogLevels.warn
34
+ },
35
+ // Level 2
36
+ log: {
37
+ level: LogLevels.log
38
+ },
39
+ // Level 3
40
+ info: {
41
+ level: LogLevels.info
42
+ },
43
+ success: {
44
+ level: LogLevels.success
45
+ },
46
+ fail: {
47
+ level: LogLevels.fail
48
+ },
49
+ ready: {
50
+ level: LogLevels.info
51
+ },
52
+ start: {
53
+ level: LogLevels.info
54
+ },
55
+ box: {
56
+ level: LogLevels.info
57
+ },
58
+ // Level 4
59
+ debug: {
60
+ level: LogLevels.debug
61
+ },
62
+ // Level 5
63
+ trace: {
64
+ level: LogLevels.trace
65
+ },
66
+ // Verbose
67
+ verbose: {
68
+ level: LogLevels.verbose
69
+ }
70
+ };
71
+
72
+ function isPlainObject$1(value) {
73
+ if (value === null || typeof value !== "object") {
74
+ return false;
75
+ }
76
+ const prototype = Object.getPrototypeOf(value);
77
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
78
+ return false;
79
+ }
80
+ if (Symbol.iterator in value) {
81
+ return false;
82
+ }
83
+ if (Symbol.toStringTag in value) {
84
+ return Object.prototype.toString.call(value) === "[object Module]";
85
+ }
86
+ return true;
87
+ }
88
+
89
+ function _defu(baseObject, defaults, namespace = ".", merger) {
90
+ if (!isPlainObject$1(defaults)) {
91
+ return _defu(baseObject, {}, namespace);
92
+ }
93
+ const object = Object.assign({}, defaults);
94
+ for (const key in baseObject) {
95
+ if (key === "__proto__" || key === "constructor") {
96
+ continue;
97
+ }
98
+ const value = baseObject[key];
99
+ if (value === null || value === void 0) {
100
+ continue;
101
+ }
102
+ if (Array.isArray(value) && Array.isArray(object[key])) {
103
+ object[key] = [...value, ...object[key]];
104
+ } else if (isPlainObject$1(value) && isPlainObject$1(object[key])) {
105
+ object[key] = _defu(
106
+ value,
107
+ object[key],
108
+ (namespace ? `${namespace}.` : "") + key.toString());
109
+ } else {
110
+ object[key] = value;
111
+ }
112
+ }
113
+ return object;
114
+ }
115
+ function createDefu(merger) {
116
+ return (...arguments_) => (
117
+ // eslint-disable-next-line unicorn/no-array-reduce
118
+ arguments_.reduce((p, c) => _defu(p, c, ""), {})
119
+ );
120
+ }
121
+ const defu = createDefu();
122
+
123
+ function isPlainObject$2(obj) {
124
+ return Object.prototype.toString.call(obj) === "[object Object]";
125
+ }
126
+ function isLogObj(arg) {
127
+ if (!isPlainObject$2(arg)) {
128
+ return false;
129
+ }
130
+ if (!arg.message && !arg.args) {
131
+ return false;
132
+ }
133
+ if (arg.stack) {
134
+ return false;
135
+ }
136
+ return true;
137
+ }
138
+
139
+ let paused = false;
140
+ const queue = [];
141
+ class Consola {
142
+ options;
143
+ _lastLog;
144
+ _mockFn;
145
+ /**
146
+ * Creates an instance of Consola with specified options or defaults.
147
+ *
148
+ * @param {Partial<ConsolaOptions>} [options={}] - Configuration options for the Consola instance.
149
+ */
150
+ constructor(options = {}) {
151
+ const types = options.types || LogTypes;
152
+ this.options = defu(
153
+ {
154
+ ...options,
155
+ defaults: { ...options.defaults },
156
+ level: _normalizeLogLevel(options.level, types),
157
+ reporters: [...options.reporters || []]
158
+ },
159
+ {
160
+ types: LogTypes,
161
+ throttle: 1e3,
162
+ throttleMin: 5,
163
+ formatOptions: {
164
+ date: true,
165
+ colors: false,
166
+ compact: true
167
+ }
168
+ }
169
+ );
170
+ for (const type in types) {
171
+ const defaults = {
172
+ type,
173
+ ...this.options.defaults,
174
+ ...types[type]
175
+ };
176
+ this[type] = this._wrapLogFn(defaults);
177
+ this[type].raw = this._wrapLogFn(
178
+ defaults,
179
+ true
180
+ );
181
+ }
182
+ if (this.options.mockFn) {
183
+ this.mockTypes();
184
+ }
185
+ this._lastLog = {};
186
+ }
187
+ /**
188
+ * Gets the current log level of the Consola instance.
189
+ *
190
+ * @returns {number} The current log level.
191
+ */
192
+ get level() {
193
+ return this.options.level;
194
+ }
195
+ /**
196
+ * Sets the minimum log level that will be output by the instance.
197
+ *
198
+ * @param {number} level - The new log level to set.
199
+ */
200
+ set level(level) {
201
+ this.options.level = _normalizeLogLevel(
202
+ level,
203
+ this.options.types,
204
+ this.options.level
205
+ );
206
+ }
207
+ /**
208
+ * Displays a prompt to the user and returns the response.
209
+ * Throw an error if `prompt` is not supported by the current configuration.
210
+ *
211
+ * @template T
212
+ * @param {string} message - The message to display in the prompt.
213
+ * @param {T} [opts] - Optional options for the prompt. See {@link PromptOptions}.
214
+ * @returns {promise<T>} A promise that infer with the prompt options. See {@link PromptOptions}.
215
+ */
216
+ prompt(message, opts) {
217
+ if (!this.options.prompt) {
218
+ throw new Error("prompt is not supported!");
219
+ }
220
+ return this.options.prompt(message, opts);
221
+ }
222
+ /**
223
+ * Creates a new instance of Consola, inheriting options from the current instance, with possible overrides.
224
+ *
225
+ * @param {Partial<ConsolaOptions>} options - Optional overrides for the new instance. See {@link ConsolaOptions}.
226
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
227
+ */
228
+ create(options) {
229
+ const instance = new Consola({
230
+ ...this.options,
231
+ ...options
232
+ });
233
+ if (this._mockFn) {
234
+ instance.mockTypes(this._mockFn);
235
+ }
236
+ return instance;
237
+ }
238
+ /**
239
+ * Creates a new Consola instance with the specified default log object properties.
240
+ *
241
+ * @param {InputLogObject} defaults - Default properties to include in any log from the new instance. See {@link InputLogObject}.
242
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
243
+ */
244
+ withDefaults(defaults) {
245
+ return this.create({
246
+ ...this.options,
247
+ defaults: {
248
+ ...this.options.defaults,
249
+ ...defaults
250
+ }
251
+ });
252
+ }
253
+ /**
254
+ * Creates a new Consola instance with a specified tag, which will be included in every log.
255
+ *
256
+ * @param {string} tag - The tag to include in each log of the new instance.
257
+ * @returns {ConsolaInstance} A new Consola instance. See {@link ConsolaInstance}.
258
+ */
259
+ withTag(tag) {
260
+ return this.withDefaults({
261
+ tag: this.options.defaults.tag ? this.options.defaults.tag + ":" + tag : tag
262
+ });
263
+ }
264
+ /**
265
+ * Adds a custom reporter to the Consola instance.
266
+ * Reporters will be called for each log message, depending on their implementation and log level.
267
+ *
268
+ * @param {ConsolaReporter} reporter - The reporter to add. See {@link ConsolaReporter}.
269
+ * @returns {Consola} The current Consola instance.
270
+ */
271
+ addReporter(reporter) {
272
+ this.options.reporters.push(reporter);
273
+ return this;
274
+ }
275
+ /**
276
+ * Removes a custom reporter from the Consola instance.
277
+ * If no reporter is specified, all reporters will be removed.
278
+ *
279
+ * @param {ConsolaReporter} reporter - The reporter to remove. See {@link ConsolaReporter}.
280
+ * @returns {Consola} The current Consola instance.
281
+ */
282
+ removeReporter(reporter) {
283
+ if (reporter) {
284
+ const i = this.options.reporters.indexOf(reporter);
285
+ if (i !== -1) {
286
+ return this.options.reporters.splice(i, 1);
287
+ }
288
+ } else {
289
+ this.options.reporters.splice(0);
290
+ }
291
+ return this;
292
+ }
293
+ /**
294
+ * Replaces all reporters of the Consola instance with the specified array of reporters.
295
+ *
296
+ * @param {ConsolaReporter[]} reporters - The new reporters to set. See {@link ConsolaReporter}.
297
+ * @returns {Consola} The current Consola instance.
298
+ */
299
+ setReporters(reporters) {
300
+ this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
301
+ return this;
302
+ }
303
+ wrapAll() {
304
+ this.wrapConsole();
305
+ this.wrapStd();
306
+ }
307
+ restoreAll() {
308
+ this.restoreConsole();
309
+ this.restoreStd();
310
+ }
311
+ /**
312
+ * Overrides console methods with Consola logging methods for consistent logging.
313
+ */
314
+ wrapConsole() {
315
+ for (const type in this.options.types) {
316
+ if (!console["__" + type]) {
317
+ console["__" + type] = console[type];
318
+ }
319
+ console[type] = this[type].raw;
320
+ }
321
+ }
322
+ /**
323
+ * Restores the original console methods, removing Consola overrides.
324
+ */
325
+ restoreConsole() {
326
+ for (const type in this.options.types) {
327
+ if (console["__" + type]) {
328
+ console[type] = console["__" + type];
329
+ delete console["__" + type];
330
+ }
331
+ }
332
+ }
333
+ /**
334
+ * Overrides standard output and error streams to redirect them through Consola.
335
+ */
336
+ wrapStd() {
337
+ this._wrapStream(this.options.stdout, "log");
338
+ this._wrapStream(this.options.stderr, "log");
339
+ }
340
+ _wrapStream(stream, type) {
341
+ if (!stream) {
342
+ return;
343
+ }
344
+ if (!stream.__write) {
345
+ stream.__write = stream.write;
346
+ }
347
+ stream.write = (data) => {
348
+ this[type].raw(String(data).trim());
349
+ };
350
+ }
351
+ /**
352
+ * Restores the original standard output and error streams, removing the Consola redirection.
353
+ */
354
+ restoreStd() {
355
+ this._restoreStream(this.options.stdout);
356
+ this._restoreStream(this.options.stderr);
357
+ }
358
+ _restoreStream(stream) {
359
+ if (!stream) {
360
+ return;
361
+ }
362
+ if (stream.__write) {
363
+ stream.write = stream.__write;
364
+ delete stream.__write;
365
+ }
366
+ }
367
+ /**
368
+ * Pauses logging, queues incoming logs until resumed.
369
+ */
370
+ pauseLogs() {
371
+ paused = true;
372
+ }
373
+ /**
374
+ * Resumes logging, processing any queued logs.
375
+ */
376
+ resumeLogs() {
377
+ paused = false;
378
+ const _queue = queue.splice(0);
379
+ for (const item of _queue) {
380
+ item[0]._logFn(item[1], item[2]);
381
+ }
382
+ }
383
+ /**
384
+ * Replaces logging methods with mocks if a mock function is provided.
385
+ *
386
+ * @param {ConsolaOptions["mockFn"]} mockFn - The function to use for mocking logging methods. See {@link ConsolaOptions["mockFn"]}.
387
+ */
388
+ mockTypes(mockFn) {
389
+ const _mockFn = mockFn || this.options.mockFn;
390
+ this._mockFn = _mockFn;
391
+ if (typeof _mockFn !== "function") {
392
+ return;
393
+ }
394
+ for (const type in this.options.types) {
395
+ this[type] = _mockFn(type, this.options.types[type]) || this[type];
396
+ this[type].raw = this[type];
397
+ }
398
+ }
399
+ _wrapLogFn(defaults, isRaw) {
400
+ return (...args) => {
401
+ if (paused) {
402
+ queue.push([this, defaults, args, isRaw]);
403
+ return;
404
+ }
405
+ return this._logFn(defaults, args, isRaw);
406
+ };
407
+ }
408
+ _logFn(defaults, args, isRaw) {
409
+ if ((defaults.level || 0) > this.level) {
410
+ return false;
411
+ }
412
+ const logObj = {
413
+ date: /* @__PURE__ */ new Date(),
414
+ args: [],
415
+ ...defaults,
416
+ level: _normalizeLogLevel(defaults.level, this.options.types)
417
+ };
418
+ if (!isRaw && args.length === 1 && isLogObj(args[0])) {
419
+ Object.assign(logObj, args[0]);
420
+ } else {
421
+ logObj.args = [...args];
422
+ }
423
+ if (logObj.message) {
424
+ logObj.args.unshift(logObj.message);
425
+ delete logObj.message;
426
+ }
427
+ if (logObj.additional) {
428
+ if (!Array.isArray(logObj.additional)) {
429
+ logObj.additional = logObj.additional.split("\n");
430
+ }
431
+ logObj.args.push("\n" + logObj.additional.join("\n"));
432
+ delete logObj.additional;
433
+ }
434
+ logObj.type = typeof logObj.type === "string" ? logObj.type.toLowerCase() : "log";
435
+ logObj.tag = typeof logObj.tag === "string" ? logObj.tag : "";
436
+ const resolveLog = (newLog = false) => {
437
+ const repeated = (this._lastLog.count || 0) - this.options.throttleMin;
438
+ if (this._lastLog.object && repeated > 0) {
439
+ const args2 = [...this._lastLog.object.args];
440
+ if (repeated > 1) {
441
+ args2.push(`(repeated ${repeated} times)`);
442
+ }
443
+ this._log({ ...this._lastLog.object, args: args2 });
444
+ this._lastLog.count = 1;
445
+ }
446
+ if (newLog) {
447
+ this._lastLog.object = logObj;
448
+ this._log(logObj);
449
+ }
450
+ };
451
+ clearTimeout(this._lastLog.timeout);
452
+ const diffTime = this._lastLog.time && logObj.date ? logObj.date.getTime() - this._lastLog.time.getTime() : 0;
453
+ this._lastLog.time = logObj.date;
454
+ if (diffTime < this.options.throttle) {
455
+ try {
456
+ const serializedLog = JSON.stringify([
457
+ logObj.type,
458
+ logObj.tag,
459
+ logObj.args
460
+ ]);
461
+ const isSameLog = this._lastLog.serialized === serializedLog;
462
+ this._lastLog.serialized = serializedLog;
463
+ if (isSameLog) {
464
+ this._lastLog.count = (this._lastLog.count || 0) + 1;
465
+ if (this._lastLog.count > this.options.throttleMin) {
466
+ this._lastLog.timeout = setTimeout(
467
+ resolveLog,
468
+ this.options.throttle
469
+ );
470
+ return;
471
+ }
472
+ }
473
+ } catch {
474
+ }
475
+ }
476
+ resolveLog(true);
477
+ }
478
+ _log(logObj) {
479
+ for (const reporter of this.options.reporters) {
480
+ reporter.log(logObj, {
481
+ options: this.options
482
+ });
483
+ }
484
+ }
485
+ }
486
+ function _normalizeLogLevel(input, types = {}, defaultLevel = 3) {
487
+ if (input === void 0) {
488
+ return defaultLevel;
489
+ }
490
+ if (typeof input === "number") {
491
+ return input;
492
+ }
493
+ if (types[input] && types[input].level !== void 0) {
494
+ return types[input].level;
495
+ }
496
+ return defaultLevel;
497
+ }
498
+ Consola.prototype.add = Consola.prototype.addReporter;
499
+ Consola.prototype.remove = Consola.prototype.removeReporter;
500
+ Consola.prototype.clear = Consola.prototype.removeReporter;
501
+ Consola.prototype.withScope = Consola.prototype.withTag;
502
+ Consola.prototype.mock = Consola.prototype.mockTypes;
503
+ Consola.prototype.pause = Consola.prototype.pauseLogs;
504
+ Consola.prototype.resume = Consola.prototype.resumeLogs;
505
+ function createConsola$1(options = {}) {
506
+ return new Consola(options);
507
+ }
508
+
509
+ class BrowserReporter {
510
+ options;
511
+ defaultColor;
512
+ levelColorMap;
513
+ typeColorMap;
514
+ constructor(options) {
515
+ this.options = { ...options };
516
+ this.defaultColor = "#7f8c8d";
517
+ this.levelColorMap = {
518
+ 0: "#c0392b",
519
+ // Red
520
+ 1: "#f39c12",
521
+ // Yellow
522
+ 3: "#00BCD4"
523
+ // Cyan
524
+ };
525
+ this.typeColorMap = {
526
+ success: "#2ecc71"
527
+ // Green
528
+ };
529
+ }
530
+ _getLogFn(level) {
531
+ if (level < 1) {
532
+ return console.__error || console.error;
533
+ }
534
+ if (level === 1) {
535
+ return console.__warn || console.warn;
536
+ }
537
+ return console.__log || console.log;
538
+ }
539
+ log(logObj) {
540
+ const consoleLogFn = this._getLogFn(logObj.level);
541
+ const type = logObj.type === "log" ? "" : logObj.type;
542
+ const tag = logObj.tag || "";
543
+ const color = this.typeColorMap[logObj.type] || this.levelColorMap[logObj.level] || this.defaultColor;
544
+ const style = `
545
+ background: ${color};
546
+ border-radius: 0.5em;
547
+ color: white;
548
+ font-weight: bold;
549
+ padding: 2px 0.5em;
550
+ `;
551
+ const badge = `%c${[tag, type].filter(Boolean).join(":")}`;
552
+ if (typeof logObj.args[0] === "string") {
553
+ consoleLogFn(
554
+ `${badge}%c ${logObj.args[0]}`,
555
+ style,
556
+ // Empty string as style resets to default console style
557
+ "",
558
+ ...logObj.args.slice(1)
559
+ );
560
+ } else {
561
+ consoleLogFn(badge, style, ...logObj.args);
562
+ }
563
+ }
564
+ }
565
+
566
+ function createConsola(options = {}) {
567
+ const consola2 = createConsola$1({
568
+ reporters: options.reporters || [new BrowserReporter({})],
569
+ prompt(message, options2 = {}) {
570
+ if (options2.type === "confirm") {
571
+ return Promise.resolve(confirm(message));
572
+ }
573
+ return Promise.resolve(prompt(message));
574
+ },
575
+ ...options
576
+ });
577
+ return consola2;
578
+ }
579
+ createConsola();
580
+
581
+ const normalizeDescriptors=(error)=>{
582
+ CORE_ERROR_PROPS.forEach((propName)=>{
583
+ normalizeDescriptor$1(error,propName);
584
+ });
585
+ };
586
+
587
+ const CORE_ERROR_PROPS=["name","message","stack","cause","errors"];
588
+
589
+ const normalizeDescriptor$1=(error,propName)=>{
590
+ const descriptor=getDescriptor(error,propName);
591
+
592
+ if(descriptor===undefined){
593
+ return
594
+ }
595
+
596
+ if(isReadonlyGetter(descriptor)){
597
+ setErrorProperty$1(error,propName,error[propName]);
598
+ return
599
+ }
600
+
601
+ if(isInvalidDescriptor(descriptor)){
602
+ setErrorDescriptor(error,propName,descriptor);
603
+ }
604
+ };
605
+
606
+
607
+ const getDescriptor=(value,propName)=>{
608
+ const descriptor=Object.getOwnPropertyDescriptor(value,propName);
609
+
610
+ if(descriptor!==undefined){
611
+ return descriptor
612
+ }
613
+
614
+ const prototype=Object.getPrototypeOf(value);
615
+ return prototype===null?undefined:getDescriptor(prototype,propName)
616
+ };
617
+
618
+
619
+ const isReadonlyGetter=({get,set})=>
620
+ get!==undefined&&set===undefined;
621
+
622
+ const isInvalidDescriptor=({enumerable,writable})=>
623
+ enumerable||!writable;
624
+
625
+
626
+ const setErrorProperty$1=(error,propName,value)=>{
627
+ setErrorDescriptor(error,propName,{value});
628
+ };
629
+
630
+
631
+ const setErrorDescriptor=(error,propName,descriptor)=>{
632
+
633
+ Object.defineProperty(error,propName,{
634
+ ...descriptor,
635
+ ...("get"in descriptor||"set"in descriptor?{}:{writable:true}),
636
+ enumerable:false,
637
+ configurable:true
638
+ });
639
+ };
640
+
641
+ const normalizeAggregate=(error,recurse)=>{
642
+ if(Array.isArray(error.errors)){
643
+ const aggregateErrors=error.errors.
644
+ filter(isDefined).
645
+ map(recurse).
646
+ filter(Boolean);
647
+ setErrorProperty$1(error,"errors",aggregateErrors);
648
+ }else if(isAggregateError(error)){
649
+ setErrorProperty$1(error,"errors",[]);
650
+ }else if(error.errors!==undefined){
651
+ deleteAggregateErrors(error);
652
+ }
653
+ };
654
+
655
+ const isDefined=(error)=>error!==undefined;
656
+
657
+ const isAggregateError=(error)=>
658
+ "AggregateError"in globalThis&&(
659
+ error.name==="AggregateError"||error instanceof AggregateError);
660
+
661
+ const deleteAggregateErrors=(error)=>{
662
+
663
+ delete error.errors;
664
+
665
+ if(error.errors!==undefined){
666
+ setErrorProperty$1(error,"errors",[]);
667
+ }
668
+ };
669
+
670
+ const normalizeCause=(error,recurse)=>{
671
+ if(!("cause"in error)){
672
+ return
673
+ }
674
+
675
+ const cause=error.cause===undefined?error.cause:recurse(error.cause);
676
+
677
+ if(cause===undefined){
678
+
679
+ delete error.cause;
680
+ }else {
681
+ setErrorProperty$1(error,"cause",cause);
682
+ }
683
+ };
684
+
685
+ const isErrorInstance$1=(value)=>
686
+ isInstanceOfError$1(value)||hasErrorTag$1(value);
687
+
688
+
689
+
690
+ const isInstanceOfError$1=(value)=>{
691
+ try{
692
+ return value instanceof Error
693
+ }catch{
694
+ return false
695
+ }
696
+ };
697
+
698
+ const hasErrorTag$1=(value)=>{
699
+ try{
700
+ return ERROR_TAGS$1.has(Object.prototype.toString.call(value))
701
+ }catch{
702
+ return false
703
+ }
704
+ };
705
+
706
+ const ERROR_TAGS$1=new Set([
707
+
708
+ "[object Error]",
709
+
710
+ "[object DOMException]",
711
+
712
+ "[object DOMError]",
713
+
714
+ "[object Exception]"]
715
+ );
716
+
717
+ function isPlainObject(value) {
718
+ if (typeof value !== 'object' || value === null) {
719
+ return false;
720
+ }
721
+
722
+ const prototype = Object.getPrototypeOf(value);
723
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
724
+ }
725
+
726
+ const isNonModifiableError=(error)=>
727
+ !Object.isExtensible(error)||
728
+ CORE_ERROR_PROPS.some(
729
+ (propName)=>
730
+ isNonConfigurableProp(error,propName)||isThrowingProp(error,propName)
731
+ );
732
+
733
+
734
+
735
+ const isNonConfigurableProp=(error,propName)=>{
736
+ const descriptor=Object.getOwnPropertyDescriptor(error,propName);
737
+ return descriptor!==undefined&&!descriptor.configurable
738
+ };
739
+
740
+
741
+ const isThrowingProp=(error,propName)=>{
742
+ try{
743
+
744
+ error[propName];
745
+ return false
746
+ }catch{
747
+ return true
748
+ }
749
+ };
750
+
751
+ const setStack=(error)=>{
752
+ const stack=getStack$3(error.message,error.name);
753
+ setErrorProperty$1(error,"stack",stack);
754
+ };
755
+
756
+
757
+
758
+
759
+
760
+
761
+
762
+ const getStack$3=(message="",name="Error")=>{
763
+ const StackError=getErrorClass(name);
764
+ const{stack}=new StackError(message);
765
+ return typeof stack==="string"&&stack!==""?
766
+ stack:
767
+ `${name}: ${message}`
768
+ };
769
+
770
+
771
+
772
+
773
+
774
+ const getErrorClass=(name)=>{
775
+ const descriptor={
776
+ value:name,
777
+ enumerable:false,
778
+ writable:true,
779
+ configurable:true
780
+ };
781
+
782
+ const StackError=Object.defineProperty(
783
+ class extends Error{},
784
+ "name",
785
+ descriptor
786
+ );
787
+
788
+ Object.defineProperty(StackError.prototype,"name",descriptor);
789
+ return StackError
790
+ };
791
+
792
+ const copyObject=(object)=>{
793
+ const objectCopy={};
794
+
795
+
796
+ for(const propName of getPropsToCopy(object)){
797
+
798
+ try{
799
+ const value=object[propName];
800
+ const{
801
+ enumerable,
802
+ configurable,
803
+ writable=true
804
+ }=getDescriptor(object,propName);
805
+
806
+ Object.defineProperty(objectCopy,propName,{
807
+ value,
808
+ enumerable,
809
+ configurable,
810
+ writable
811
+ });
812
+ }catch{}
813
+ }
814
+
815
+ return objectCopy
816
+ };
817
+
818
+
819
+
820
+
821
+
822
+ const getPropsToCopy=(object)=>{
823
+ const propNames=getOwnKeys(object);
824
+
825
+
826
+ for(const propName of CORE_ERROR_PROPS){
827
+
828
+ if(isInheritedProp(object,propName)){
829
+
830
+ propNames.push(propName);
831
+ }
832
+ }
833
+
834
+ return propNames
835
+ };
836
+
837
+
838
+ const getOwnKeys=(object)=>{
839
+ try{
840
+ return Reflect.ownKeys(object)
841
+ }catch{
842
+ return []
843
+ }
844
+ };
845
+
846
+
847
+ const isInheritedProp=(object,propName)=>{
848
+ try{
849
+ return propName in object&&!Object.hasOwn(object,propName)
850
+ }catch{
851
+ return false
852
+ }
853
+ };
854
+
855
+ const objectifyError=(object)=>{
856
+ const{name,message,stack,cause,errors,...objectA}=copyObject(object);
857
+ const messageA=getMessage$1(message,objectA);
858
+ const error=newError(name,messageA);
859
+
860
+ if(message===messageA){
861
+ assignObjectProps(error,objectA);
862
+ }
863
+
864
+ Object.entries({name,stack,cause,errors}).forEach(
865
+ ([propName,propValue])=>{
866
+ setNewErrorProperty(error,propName,propValue);
867
+ }
868
+ );
869
+
870
+ if(stack===undefined){
871
+ setStack(error);
872
+ }
873
+
874
+ return error
875
+ };
876
+
877
+
878
+ const getMessage$1=(message,object)=>
879
+ typeof message==="string"&&message!==""?
880
+ message:
881
+ truncateMessage(safeJsonStringify(object));
882
+
883
+ const safeJsonStringify=(object)=>{
884
+ try{
885
+ return JSON.stringify(object)
886
+ }catch{
887
+ return safeStringify$1(object)
888
+ }
889
+ };
890
+
891
+ const safeStringify$1=(object)=>{
892
+ try{
893
+ return String(object)
894
+ }catch{
895
+ return "Invalid error"
896
+ }
897
+ };
898
+
899
+ const truncateMessage=(message)=>
900
+ message.length<MESSAGE_MAX_SIZE?
901
+ message:
902
+ `${message.slice(0,MESSAGE_MAX_SIZE)}...`;
903
+
904
+ const MESSAGE_MAX_SIZE=1e3;
905
+
906
+ const newError=(name,message)=>{
907
+ if(name==="AggregateError"&&"AggregateError"in globalThis){
908
+ return new AggregateError([],message)
909
+ }
910
+
911
+ if(name in NATIVE_ERRORS){
912
+ return new NATIVE_ERRORS[name](message)
913
+ }
914
+
915
+ return new Error(message)
916
+ };
917
+
918
+ const NATIVE_ERRORS={
919
+ Error,
920
+ ReferenceError,
921
+ TypeError,
922
+ SyntaxError,
923
+ RangeError,
924
+ URIError,
925
+ EvalError
926
+ };
927
+
928
+
929
+ const assignObjectProps=(error,object)=>{
930
+
931
+ for(const propName in object){
932
+
933
+ if(!(propName in error)){
934
+ error[propName]=object[propName];
935
+ }
936
+ }
937
+ };
938
+
939
+ const setNewErrorProperty=(error,propName,propValue)=>{
940
+ if(propValue!==undefined){
941
+ setErrorProperty$1(error,propName,propValue);
942
+ }
943
+ };
944
+
945
+ const stringifyError=(value)=>{
946
+ try{
947
+ const error=new Error(String(value));
948
+ setStack(error);
949
+ return error
950
+ }catch(error_){
951
+ return error_
952
+ }
953
+ };
954
+
955
+ const{toString:objectToString}=Object.prototype;
956
+
957
+
958
+ const createError=(value)=>{
959
+ if(isErrorPlainObj(value)){
960
+ return objectifyError(value)
961
+ }
962
+
963
+ if(!isErrorInstance$1(value)){
964
+ return stringifyError(value)
965
+ }
966
+
967
+ if(isInvalidError(value)){
968
+ return objectifyError(value)
969
+ }
970
+
971
+ return value
972
+ };
973
+
974
+
975
+ const isErrorPlainObj=(value)=>{
976
+ try{
977
+ return isPlainObject(value)
978
+ }catch{
979
+ return false
980
+ }
981
+ };
982
+
983
+ const isInvalidError=(value)=>
984
+ isProxy(value)||isNonModifiableError(value)||hasInvalidConstructor(value);
985
+
986
+
987
+
988
+
989
+ const isProxy=(value)=>{
990
+ try{
991
+ return objectToString.call(value)==="[object Object]"
992
+ }catch{
993
+ return true
994
+ }
995
+ };
996
+
997
+
998
+
999
+ const hasInvalidConstructor=(error)=>
1000
+ typeof error.constructor!=="function"||
1001
+ typeof error.constructor.name!=="string"||
1002
+ error.constructor.name===""||
1003
+ error.constructor.prototype!==Object.getPrototypeOf(error);
1004
+
1005
+ const normalizeException=(error,{shallow=false}={})=>
1006
+ recurseException(error,[],shallow);
1007
+
1008
+ const recurseException=(error,parents,shallow)=>{
1009
+ if(parents.includes(error)){
1010
+ return
1011
+ }
1012
+
1013
+ const recurse=shallow?
1014
+ identity:
1015
+ (innerError)=>recurseException(innerError,[...parents,error],shallow);
1016
+
1017
+ const errorA=createError(error);
1018
+ normalizeProps(errorA,recurse);
1019
+ return errorA
1020
+ };
1021
+
1022
+ const identity=(error)=>error;
1023
+
1024
+ const normalizeProps=(error,recurse)=>{
1025
+ normalizeName(error);
1026
+ normalizeMessage(error);
1027
+ normalizeStack(error);
1028
+ normalizeCause(error,recurse);
1029
+ normalizeAggregate(error,recurse);
1030
+ normalizeDescriptors(error);
1031
+ };
1032
+
1033
+
1034
+
1035
+
1036
+
1037
+
1038
+ const normalizeName=(error)=>{
1039
+ if(isDefinedString$1(error.name)){
1040
+ return
1041
+ }
1042
+
1043
+ const prototypeName=Object.getPrototypeOf(error).name;
1044
+ const name=isDefinedString$1(prototypeName)?
1045
+ prototypeName:
1046
+ error.constructor.name;
1047
+ setErrorProperty$1(error,"name",name);
1048
+ };
1049
+
1050
+
1051
+ const normalizeMessage=(error)=>{
1052
+ if(!isDefinedString$1(error.message)){
1053
+ setErrorProperty$1(error,"message","");
1054
+ }
1055
+ };
1056
+
1057
+
1058
+ const normalizeStack=(error)=>{
1059
+ if(!isDefinedString$1(error.stack)){
1060
+ setStack(error);
1061
+ }
1062
+ };
1063
+
1064
+ const isDefinedString$1=(value)=>typeof value==="string"&&value!=="";
1065
+
1066
+ const normalizeArgs$1=(error,ErrorClass,currentName=error.name)=>{
1067
+ validateErrorClass(ErrorClass);
1068
+
1069
+ if(typeof currentName!=="string"){
1070
+ throw new TypeError(`currentName must be a string: ${currentName}`)
1071
+ }
1072
+
1073
+ return currentName
1074
+ };
1075
+
1076
+ const validateErrorClass=(ErrorClass)=>{
1077
+ if(!isClass(ErrorClass)){
1078
+ throw new TypeError(`ErrorClass must be a class: ${ErrorClass}`)
1079
+ }
1080
+
1081
+ if(!isErrorClass(ErrorClass.prototype)){
1082
+ throw new TypeError(`ErrorClass must inherit from Error: ${ErrorClass}`)
1083
+ }
1084
+
1085
+ if(!hasConstructor(ErrorClass)){
1086
+ throw new TypeError(
1087
+ `ErrorClass must be have a valid constructor: ${ErrorClass}`
1088
+ )
1089
+ }
1090
+ };
1091
+
1092
+ const isClass=(ErrorClass)=>
1093
+ typeof ErrorClass==="function"&&
1094
+ typeof ErrorClass.prototype==="object"&&
1095
+ ErrorClass.prototype!==null;
1096
+
1097
+
1098
+ const isErrorClass=(prototype)=>
1099
+ prototype!==null&&(
1100
+ prototype.name==="Error"||isErrorClass(Object.getPrototypeOf(prototype)));
1101
+
1102
+ const hasConstructor=(ErrorClass)=>
1103
+ typeof ErrorClass.prototype.constructor==="function";
1104
+
1105
+ const setNonEnumProp$1=(error,propName,value)=>{
1106
+
1107
+ Object.defineProperty(error,propName,{
1108
+ value,
1109
+ enumerable:false,
1110
+ writable:true,
1111
+ configurable:true
1112
+ });
1113
+ };
1114
+
1115
+ const updatePrototype=(error,ErrorClass)=>{
1116
+ if(Object.getPrototypeOf(error)===ErrorClass.prototype){
1117
+ return
1118
+ }
1119
+
1120
+ setPrototype(error,ErrorClass);
1121
+ deleteOwnProperty(error,"constructor");
1122
+ fixName(error,ErrorClass);
1123
+ };
1124
+
1125
+
1126
+
1127
+
1128
+
1129
+ const setPrototype=(error,ErrorClass)=>{
1130
+
1131
+ Object.setPrototypeOf(error,ErrorClass.prototype);
1132
+ };
1133
+
1134
+
1135
+
1136
+
1137
+
1138
+
1139
+
1140
+
1141
+
1142
+
1143
+ const fixName=(error,ErrorClass)=>{
1144
+ deleteOwnProperty(error,"name");
1145
+
1146
+ const prototypeName=getClassName(ErrorClass.prototype);
1147
+
1148
+ if(error.name!==prototypeName){
1149
+ setNonEnumProp$1(error,"name",prototypeName);
1150
+ }
1151
+ };
1152
+
1153
+ const getClassName=(prototype)=>
1154
+ getPrototypeName(prototype)??
1155
+ getConstructorName(prototype)??
1156
+ getClassName(Object.getPrototypeOf(prototype));
1157
+
1158
+ const getPrototypeName=(prototype)=>
1159
+ Object.hasOwn(prototype,"name")&&isDefinedString(prototype.name)?
1160
+ prototype.name:
1161
+ undefined;
1162
+
1163
+ const getConstructorName=(prototype)=>
1164
+ typeof prototype.constructor==="function"&&
1165
+ isDefinedString(prototype.constructor.name)?
1166
+ prototype.constructor.name:
1167
+ undefined;
1168
+
1169
+ const isDefinedString=(value)=>typeof value==="string"&&value!=="";
1170
+
1171
+
1172
+
1173
+ const deleteOwnProperty=(error,propName)=>{
1174
+ if(Object.hasOwn(error,propName)){
1175
+
1176
+ delete error[propName];
1177
+ }
1178
+ };
1179
+
1180
+ const updateStack$1=(error,currentName)=>{
1181
+ if(!shouldUpdateStack(error,currentName)){
1182
+ return
1183
+ }
1184
+
1185
+ const stack=getStack$2(error,currentName);
1186
+ setNonEnumProp$1(error,"stack",stack);
1187
+ };
1188
+
1189
+ const shouldUpdateStack=(error,currentName)=>
1190
+ currentName!==error.name&&
1191
+ currentName!==""&&
1192
+ error.stack.includes(currentName)&&
1193
+ stackIncludesName();
1194
+
1195
+
1196
+ const stackIncludesName=()=>{
1197
+
1198
+ class StackError extends Error{}
1199
+ const descriptor={
1200
+ value:EXAMPLE_NAME,
1201
+ enumerable:false,
1202
+ writable:true,
1203
+ configurable:true
1204
+ };
1205
+
1206
+ Object.defineProperty(StackError,"name",descriptor);
1207
+
1208
+ Object.defineProperty(StackError.prototype,"name",descriptor);
1209
+ const{stack}=new StackError("");
1210
+ return typeof stack==="string"&&stack.includes(EXAMPLE_NAME)
1211
+ };
1212
+
1213
+ const EXAMPLE_NAME="SetErrorClassError";
1214
+
1215
+
1216
+
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+ const getStack$2=({name,stack},currentName)=>{
1223
+ if(stack.startsWith(`${currentName}: `)){
1224
+ return stack.replace(currentName,name)
1225
+ }
1226
+
1227
+ const replacers=getReplacers$1(currentName,name);
1228
+ const[fromA,to]=replacers.find(([from])=>stack.includes(from));
1229
+ return stack.replace(fromA,to)
1230
+ };
1231
+
1232
+
1233
+
1234
+ const getReplacers$1=(currentName,newName)=>[
1235
+ [`\n${currentName}: `,`\n${newName}: `],
1236
+ [`${currentName}: `,`${newName}: `],
1237
+ [`${currentName} `,`${newName} `],
1238
+ [currentName,newName]];
1239
+
1240
+ const setErrorClass=(error,ErrorClass,currentName)=>{
1241
+ const errorA=normalizeException(error);
1242
+ const currentNameA=normalizeArgs$1(errorA,ErrorClass,currentName);
1243
+ updatePrototype(errorA,ErrorClass);
1244
+ updateStack$1(errorA,currentNameA);
1245
+ return errorA
1246
+ };
1247
+
1248
+ const mergeDescriptors=(newDescriptor,currentDescriptor)=>
1249
+ currentDescriptor.configurable===false?
1250
+ mergeNonConfig(newDescriptor,currentDescriptor):
1251
+ mergeConfig(newDescriptor,currentDescriptor);
1252
+
1253
+
1254
+
1255
+
1256
+ const mergeNonConfig=(newDescriptor,currentDescriptor)=>({
1257
+ ...currentDescriptor,
1258
+ ...getNonConfigWritable(newDescriptor,currentDescriptor),
1259
+ ...getNonConfigValue(newDescriptor,currentDescriptor)
1260
+ });
1261
+
1262
+ const getNonConfigWritable=(newDescriptor,currentDescriptor)=>
1263
+ currentDescriptor.writable===true&&newDescriptor.writable===false?
1264
+ {writable:false}:
1265
+ {};
1266
+
1267
+ const getNonConfigValue=(newDescriptor,currentDescriptor)=>
1268
+ newDescriptor.hasValue&&
1269
+ "value"in currentDescriptor&&
1270
+ currentDescriptor.writable===true?
1271
+ {value:newDescriptor.value}:
1272
+ {};
1273
+
1274
+ const mergeConfig=(newDescriptor,currentDescriptor)=>{
1275
+ const enumerable=mergeDescriptor(
1276
+ newDescriptor.enumerable,
1277
+ currentDescriptor.enumerable,
1278
+ true
1279
+ );
1280
+ const writable=mergeDescriptor(
1281
+ newDescriptor.writable,
1282
+ currentDescriptor.writable,
1283
+ true
1284
+ );
1285
+ const configurable=mergeDescriptor(
1286
+ newDescriptor.configurable,
1287
+ currentDescriptor.configurable,
1288
+ true
1289
+ );
1290
+ const valueProps=mergeValue(newDescriptor,currentDescriptor,writable);
1291
+ return {...valueProps,enumerable,configurable}
1292
+ };
1293
+
1294
+ const mergeValue=(newDescriptor,currentDescriptor,writable)=>{
1295
+ if(newDescriptor.hasValue){
1296
+ return {value:newDescriptor.value,writable}
1297
+ }
1298
+
1299
+ if(!hasGetSet(newDescriptor)&&!hasGetSet(currentDescriptor)){
1300
+ return {value:currentDescriptor.value,writable}
1301
+ }
1302
+
1303
+ return {
1304
+ get:mergeDescriptor(newDescriptor.get,currentDescriptor.get),
1305
+ set:mergeDescriptor(newDescriptor.set,currentDescriptor.set)
1306
+ }
1307
+ };
1308
+
1309
+ const hasGetSet=({get,set})=>get!==undefined||set!==undefined;
1310
+
1311
+ const mergeDescriptor=(newValue,currentValue,defaultValue)=>
1312
+ newValue??currentValue??defaultValue;
1313
+
1314
+ const normalizeInput=(input,key,newDescriptor)=>{
1315
+ if(!isAnyObj(input)){
1316
+ throw new TypeError(`Argument must be an object: ${input}`)
1317
+ }
1318
+
1319
+ if(!isValidKey(key)){
1320
+ throw new TypeError(
1321
+ `Property key must be a string, a symbol or an integer: ${key}`
1322
+ )
1323
+ }
1324
+
1325
+ return normalizeDescriptor(newDescriptor)
1326
+ };
1327
+
1328
+ const isAnyObj=(value)=>typeof value==="object"&&value!==null;
1329
+
1330
+ const isValidKey=(key)=>{
1331
+ const type=typeof key;
1332
+ return type==="string"||type==="symbol"||type==="number"
1333
+ };
1334
+
1335
+ const normalizeDescriptor=(newDescriptor)=>{
1336
+ if(!isPlainObject(newDescriptor)){
1337
+ throw new TypeError(`Descriptor must be a plain object: ${newDescriptor}`)
1338
+ }
1339
+
1340
+ const{
1341
+ enumerable,
1342
+ writable,
1343
+ configurable,
1344
+ value,
1345
+ get,
1346
+ set,
1347
+ ...unknownProps
1348
+ }=newDescriptor;
1349
+ const hasValue=("value"in newDescriptor);
1350
+ validateDescriptor({
1351
+ enumerable,
1352
+ writable,
1353
+ configurable,
1354
+ get,
1355
+ set,
1356
+ unknownProps,
1357
+ hasValue
1358
+ });
1359
+ return {enumerable,writable,configurable,value,get,set,hasValue}
1360
+ };
1361
+
1362
+ const validateDescriptor=({
1363
+ enumerable,
1364
+ writable,
1365
+ configurable,
1366
+ get,
1367
+ set,
1368
+ unknownProps,
1369
+ hasValue
1370
+ })=>{
1371
+ validateGetSet(hasValue,get,"get");
1372
+ validateGetSet(hasValue,set,"set");
1373
+ validateBoolean(enumerable,"enumerable");
1374
+ validateBoolean(writable,"writable");
1375
+ validateBoolean(configurable,"configurable");
1376
+ validateUnknownProps(unknownProps);
1377
+ };
1378
+
1379
+ const validateGetSet=(hasValue,getSet,propName)=>{
1380
+ validateFunction(getSet,propName);
1381
+
1382
+ if(hasValue&&getSet!==undefined){
1383
+ throw new TypeError(
1384
+ `Descriptor property "value" and "${propName}" must not both be defined: ${getSet}`
1385
+ )
1386
+ }
1387
+ };
1388
+
1389
+ const validateFunction=(propValue,propName)=>{
1390
+ if(propValue!==undefined&&typeof propValue!=="function"){
1391
+ throw new TypeError(
1392
+ `Descriptor property "${propName}" must be a function: ${propValue}`
1393
+ )
1394
+ }
1395
+ };
1396
+
1397
+ const validateBoolean=(propValue,propName)=>{
1398
+ if(propValue!==undefined&&typeof propValue!=="boolean"){
1399
+ throw new TypeError(
1400
+ `Descriptor property "${propName}" must be a boolean: ${propValue}`
1401
+ )
1402
+ }
1403
+ };
1404
+
1405
+ const validateUnknownProps=(unknownProps)=>{
1406
+ const[unknownProp]=Object.keys(unknownProps);
1407
+
1408
+ if(unknownProp!==undefined){
1409
+ throw new TypeError(
1410
+ `Unknown descriptor property "${unknownProp}": ${unknownProps[unknownProp]}`
1411
+ )
1412
+ }
1413
+ };
1414
+
1415
+ const redefineProperty=(input,key,newDescriptor)=>{
1416
+ const newDescriptorA=normalizeInput(input,key,newDescriptor);
1417
+ const currentDescriptor=getCurrentDescriptor(input,key);
1418
+ const finalDescriptor=mergeDescriptors(newDescriptorA,currentDescriptor);
1419
+ setProperty(input,key,finalDescriptor);
1420
+ return input
1421
+ };
1422
+
1423
+
1424
+ const getCurrentDescriptor=(input,key)=>{
1425
+ const descriptor=Object.getOwnPropertyDescriptor(input,key);
1426
+
1427
+ if(descriptor!==undefined){
1428
+ return descriptor
1429
+ }
1430
+
1431
+ const prototype=Object.getPrototypeOf(input);
1432
+ return prototype===null?{}:getCurrentDescriptor(prototype,key)
1433
+ };
1434
+
1435
+
1436
+ const setProperty=(input,key,finalDescriptor)=>{
1437
+ try{
1438
+
1439
+ Object.defineProperty(input,key,finalDescriptor);
1440
+ }catch{}
1441
+ };
1442
+
1443
+ const assignProp=(error,propName,propValue)=>{
1444
+ if(propValue!==undefined){
1445
+ return setProp(error,propName,propValue)
1446
+ }
1447
+
1448
+ try{
1449
+
1450
+ delete error[propName];
1451
+ }catch{}
1452
+
1453
+ if(error[propName]!==undefined){
1454
+ return setProp(error,propName)
1455
+ }
1456
+ };
1457
+
1458
+ const setProp=(error,propName,propValue)=>{
1459
+ const nonEnum=getNonEnum(propName);
1460
+ redefineProperty(error,propName,{value:propValue,...nonEnum});
1461
+ };
1462
+
1463
+
1464
+ const getNonEnum=(propName)=>
1465
+ typeof propName==="string"&&propName.startsWith("_")?
1466
+ {enumerable:false}:
1467
+ {};
1468
+
1469
+ const isErrorInstance=(value)=>
1470
+ isInstanceOfError(value)||hasErrorTag(value);
1471
+
1472
+
1473
+
1474
+ const isInstanceOfError=(value)=>{
1475
+ try{
1476
+ return value instanceof Error
1477
+ }catch{
1478
+ return false
1479
+ }
1480
+ };
1481
+
1482
+ const hasErrorTag=(value)=>{
1483
+ try{
1484
+ return ERROR_TAGS.has(Object.prototype.toString.call(value))
1485
+ }catch{
1486
+ return false
1487
+ }
1488
+ };
1489
+
1490
+ const ERROR_TAGS=new Set([
1491
+
1492
+ "[object Error]",
1493
+
1494
+ "[object DOMException]",
1495
+
1496
+ "[object DOMError]",
1497
+
1498
+ "[object Exception]"]
1499
+ );
1500
+
1501
+ const normalizeOptions=(error,props,opts={})=>{
1502
+ validateErrorOrObject(error,"First argument");
1503
+ validateErrorOrObject(props,"Second argument");
1504
+
1505
+ if(!isPlainObject(opts)){
1506
+ throw new TypeError(`Options must be a plain object: ${opts}`)
1507
+ }
1508
+
1509
+ const{soft=false}=opts;
1510
+
1511
+ if(typeof soft!=="boolean"){
1512
+ throw new TypeError(`Option "soft" must be a boolean: ${soft}`)
1513
+ }
1514
+
1515
+ return {soft}
1516
+ };
1517
+
1518
+ const validateErrorOrObject=(value,prefix)=>{
1519
+ if(value===undefined){
1520
+ throw new TypeError(`${prefix} is required.`)
1521
+ }
1522
+
1523
+ if(!isErrorOrObject(value)){
1524
+ throw new TypeError(
1525
+ `${prefix} must be a plain object or an error: ${value}`
1526
+ )
1527
+ }
1528
+ };
1529
+
1530
+ const isErrorOrObject=(value)=>isPlainObject(value)||isErrorInstance(value);
1531
+
1532
+ const shouldSkipProp=({error,props,propName,soft})=>
1533
+ isIgnoredPropName(propName)||
1534
+ !isEnum.call(props,propName)||
1535
+ soft&&error[propName]!==undefined;
1536
+
1537
+ const isIgnoredPropName=(propName)=>
1538
+ propName in CHECK_ERROR||IGNORED_PROPS.has(propName);
1539
+
1540
+
1541
+
1542
+
1543
+ const CHECK_ERROR=new Error("check");
1544
+
1545
+
1546
+
1547
+ const IGNORED_PROPS=new Set(["prototype","errors","cause"]);
1548
+
1549
+ const{propertyIsEnumerable:isEnum}=Object.prototype;
1550
+
1551
+ const setErrorProps=(error,props,opts)=>{
1552
+ const{soft}=normalizeOptions(error,props,opts);
1553
+
1554
+
1555
+ for(const propName of Reflect.ownKeys(props)){
1556
+ setErrorProp({error,props,propName,soft});
1557
+ }
1558
+
1559
+ return error
1560
+ };
1561
+
1562
+
1563
+
1564
+
1565
+
1566
+ const setErrorProp=({error,props,propName,soft})=>{
1567
+ if(!shouldSkipProp({error,props,propName,soft})){
1568
+ assignProp(error,propName,props[propName]);
1569
+ }
1570
+ };
1571
+
1572
+ const setErrorProperty=(error,propName,value)=>{
1573
+
1574
+ Object.defineProperty(error,propName,{
1575
+ value,
1576
+ writable:true,
1577
+ enumerable:false,
1578
+ configurable:true
1579
+ });
1580
+ };
1581
+
1582
+ const mergeAggregateCauses=(parent,recurse)=>{
1583
+ if(parent.errors===undefined){
1584
+ return
1585
+ }
1586
+
1587
+ const errors=parent.errors.
1588
+ map((error)=>recurse(error).error).
1589
+ filter(Boolean);
1590
+ setErrorProperty(parent,"errors",errors);
1591
+ };
1592
+
1593
+ const mergeAggregateErrors=({target,source,parent,child})=>{
1594
+ if(!hasErrors(target)){
1595
+ mergeSourceErrors(target,source);
1596
+ return
1597
+ }
1598
+
1599
+ if(hasErrors(source)){
1600
+ setErrorProperty(target,"errors",[...child.errors,...parent.errors]);
1601
+ }
1602
+ };
1603
+
1604
+ const mergeSourceErrors=(target,source)=>{
1605
+ if(source.errors!==undefined){
1606
+ setErrorProperty(target,"errors",source.errors);
1607
+ }
1608
+ };
1609
+
1610
+ const hasErrors=(targetOrSource)=>
1611
+ targetOrSource.errors!==undefined&&targetOrSource.errors.length!==0;
1612
+
1613
+ const normalizeArgs=(
1614
+ error,
1615
+ newMessage,
1616
+ currentMessage=error.message)=>
1617
+ {
1618
+ if(typeof newMessage!=="string"){
1619
+ throw new TypeError(`newMessage must be a string: ${newMessage}`)
1620
+ }
1621
+
1622
+ if(typeof currentMessage!=="string"){
1623
+ throw new TypeError(`currentMessage must be a string: ${currentMessage}`)
1624
+ }
1625
+
1626
+ return currentMessage
1627
+ };
1628
+
1629
+ const getStack$1=({name,stack},newMessage,currentMessage)=>
1630
+ currentMessage!==""&&stack.includes(currentMessage)?
1631
+ replaceMessage({name,stack,newMessage,currentMessage}):
1632
+ insertMessage(name,stack,newMessage);
1633
+
1634
+
1635
+
1636
+ const replaceMessage=({name,stack,newMessage,currentMessage})=>{
1637
+ const replacers=getReplacers(name,newMessage,currentMessage);
1638
+ const[fromA,to]=replacers.find(([from])=>stack.includes(from));
1639
+ return stack.replace(fromA,to)
1640
+ };
1641
+
1642
+
1643
+
1644
+ const getReplacers=(name,newMessage,currentMessage)=>[
1645
+ [`${name}: ${currentMessage}`,`${name}: ${newMessage}`],
1646
+ [`: ${currentMessage}`,`: ${newMessage}`],
1647
+ [`\n${currentMessage}`,`\n${newMessage}`],
1648
+ [` ${currentMessage}`,` ${newMessage}`],
1649
+ [currentMessage,newMessage]];
1650
+
1651
+
1652
+ const insertMessage=(name,stack,newMessage)=>{
1653
+ const nameAndColon=`${name}: `;
1654
+ const newMessageA=newMessage.trimEnd();
1655
+
1656
+ if(stack===name||stack.startsWith(`${name}\n`)){
1657
+ return stack.replace(name,`${nameAndColon}${newMessageA}`)
1658
+ }
1659
+
1660
+ return stack.startsWith(nameAndColon)?
1661
+ stack.replace(nameAndColon,`${nameAndColon}${newMessageA}\n`):
1662
+ `${nameAndColon}${newMessageA}\n${stack}`
1663
+ };
1664
+
1665
+ const setErrorMessage=(error,newMessage,currentMessage)=>{
1666
+ const errorA=normalizeException(error);
1667
+ const currentMessageA=normalizeArgs(errorA,newMessage,currentMessage);
1668
+ setNonEnumProp(errorA,"message",newMessage);
1669
+ updateStack(errorA,newMessage,currentMessageA);
1670
+ return errorA
1671
+ };
1672
+
1673
+
1674
+
1675
+ const updateStack=(error,newMessage,currentMessage)=>{
1676
+ if(newMessage===currentMessage||!stackIncludesMessage()){
1677
+ return
1678
+ }
1679
+
1680
+ const stack=getStack$1(error,newMessage,currentMessage);
1681
+ setNonEnumProp(error,"stack",stack);
1682
+ };
1683
+
1684
+
1685
+ const stackIncludesMessage=()=>{
1686
+ const{stack}=new Error(EXAMPLE_MESSAGE);
1687
+ return typeof stack==="string"&&stack.includes(EXAMPLE_MESSAGE)
1688
+ };
1689
+
1690
+ const EXAMPLE_MESSAGE="set-error-message test message";
1691
+
1692
+ const setNonEnumProp=(error,propName,value)=>{
1693
+
1694
+ Object.defineProperty(error,propName,{
1695
+ value,
1696
+ enumerable:false,
1697
+ writable:true,
1698
+ configurable:true
1699
+ });
1700
+ };
1701
+
1702
+ const wrapErrorMessage=(error,newMessage,oldMessage)=>{
1703
+ if(typeof newMessage!=="string"){
1704
+ throw new TypeError(
1705
+ `Second argument must be a message string: ${newMessage}`
1706
+ )
1707
+ }
1708
+
1709
+ const errorA=normalizeException(error);
1710
+ const message=getMessage(newMessage,errorA.message);
1711
+ return setErrorMessage(errorA,message,oldMessage)
1712
+ };
1713
+
1714
+
1715
+
1716
+
1717
+
1718
+
1719
+
1720
+
1721
+
1722
+ const getMessage=(rawNewMessage,rawCurrentMessage)=>{
1723
+ const newMessage=rawNewMessage.trim();
1724
+ const currentMessage=rawCurrentMessage.trim();
1725
+
1726
+ if(newMessage===""){
1727
+ return currentMessage
1728
+ }
1729
+
1730
+ if(currentMessage===""){
1731
+ return newMessage
1732
+ }
1733
+
1734
+ return concatMessages(newMessage,currentMessage,rawNewMessage)
1735
+ };
1736
+
1737
+ const concatMessages=(newMessage,currentMessage,rawNewMessage)=>{
1738
+ if(!newMessage.endsWith(PREPEND_CHAR)){
1739
+ return `${currentMessage}\n${newMessage}`
1740
+ }
1741
+
1742
+ return rawNewMessage.endsWith(PREPEND_NEWLINE_CHAR)?
1743
+ `${newMessage}\n${currentMessage}`:
1744
+ `${newMessage} ${currentMessage}`
1745
+ };
1746
+
1747
+ const PREPEND_CHAR=":";
1748
+ const PREPEND_NEWLINE_CHAR="\n";
1749
+
1750
+ const mergeMessage=({parent,child,target,stackError})=>{
1751
+ const parentMessage=parent.message;
1752
+
1753
+ target.message=child.message;
1754
+ return wrapErrorMessage(target,parentMessage,stackError.message)
1755
+ };
1756
+
1757
+ const hasStack=(error,stack)=>getStack(error)===stack;
1758
+
1759
+
1760
+
1761
+
1762
+ const getStack=(error)=>
1763
+ typeof error==="object"&&error!==null?error.stack:undefined;
1764
+
1765
+
1766
+
1767
+
1768
+
1769
+
1770
+
1771
+
1772
+
1773
+
1774
+ const mergeStack=({wrap,target,source,childHasStack})=>{
1775
+ if(wrap===childHasStack){
1776
+ return target
1777
+ }
1778
+
1779
+ setErrorProperty(target,"stack",source.stack);
1780
+ return source
1781
+ };
1782
+
1783
+ const getWrap=(parent)=>{
1784
+ const{wrap,name}=parent;
1785
+
1786
+ if(typeof wrap!=="boolean"){
1787
+ return name==="Error"
1788
+ }
1789
+
1790
+ if(Object.hasOwn(parent,"wrap")){
1791
+
1792
+ delete parent.wrap;
1793
+ }
1794
+
1795
+ return wrap
1796
+ };
1797
+
1798
+ const mergeErrorCause=(error)=>mergeError(error,[]).error;
1799
+
1800
+
1801
+
1802
+
1803
+
1804
+
1805
+ const mergeError=(error,parents)=>{
1806
+ if(parents.includes(error)){
1807
+ return {}
1808
+ }
1809
+
1810
+ const recurse=(innerError)=>mergeError(innerError,[...parents,error]);
1811
+ const stack=getStack(error);
1812
+ const errorA=normalizeException(error,{shallow:true});
1813
+ const parentHasStack=hasStack(errorA,stack);
1814
+
1815
+ mergeAggregateCauses(errorA,recurse);
1816
+ const{parent:errorB,childHasStack}=mergeCause(errorA,recurse);
1817
+ const errorHasStack=parentHasStack||childHasStack;
1818
+ return {error:errorB,errorHasStack}
1819
+ };
1820
+
1821
+
1822
+
1823
+ const mergeCause=(parent,recurse)=>{
1824
+ const wrap=getWrap(parent);
1825
+
1826
+ if(parent.cause===undefined){
1827
+ return {parent,childHasStack:false}
1828
+ }
1829
+
1830
+ const{error:child,errorHasStack:childHasStack}=recurse(parent.cause);
1831
+
1832
+ delete parent.cause;
1833
+ const parentA=mergeChild({parent,child,childHasStack,wrap});
1834
+ return {parent:parentA,childHasStack}
1835
+ };
1836
+
1837
+ const mergeChild=({parent,child,childHasStack,wrap})=>{
1838
+ if(child===undefined){
1839
+ return parent
1840
+ }
1841
+
1842
+ const[target,source]=wrap?[child,parent]:[parent,child];
1843
+ const stackError=mergeStack({wrap,target,source,childHasStack});
1844
+ const targetA=setErrorClass(target,target.constructor,stackError.name);
1845
+ const targetB=mergeMessage({parent,child,target:targetA,stackError});
1846
+ mergeAggregateErrors({target:targetB,source,parent,child});
1847
+ const targetC=setErrorProps(targetB,source,{soft:!wrap});
1848
+ return targetC
1849
+ };
1850
+
1851
+ function safeStringifyReplacer(seen) {
1852
+ return function (key, value) {
1853
+ // Handle objects with a custom `.toJSON()` method.
1854
+ if (typeof value?.toJSON === 'function') {
1855
+ value = value.toJSON();
1856
+ }
1857
+
1858
+ if (!(value !== null && typeof value === 'object')) {
1859
+ return value;
1860
+ }
1861
+
1862
+ if (seen.has(value)) {
1863
+ return '[Circular]';
1864
+ }
1865
+
1866
+ seen.add(value);
1867
+
1868
+ const newValue = Array.isArray(value) ? [] : {};
1869
+
1870
+ for (const [key2, value2] of Object.entries(value)) {
1871
+ newValue[key2] = safeStringifyReplacer(seen)(key2, value2);
1872
+ }
1873
+
1874
+ seen.delete(value);
1875
+
1876
+ return newValue;
1877
+ };
1878
+ }
1879
+
1880
+ function safeStringify(object, {indentation} = {}) {
1881
+ const seen = new WeakSet();
1882
+ return JSON.stringify(object, safeStringifyReplacer(seen), indentation);
1883
+ }
1884
+
1885
+ const defaultParseStack = (stack) => {
1886
+ const lines = stack.split("\n").map((l) => l.trim().replace("file://", ""));
1887
+ return lines;
1888
+ };
1889
+ function formattedLogObj(logObj, parseStack = defaultParseStack) {
1890
+ const result = {
1891
+ message: ""
1892
+ };
1893
+ const error = logObj.args.find((a) => a instanceof Error);
1894
+ if (!error) {
1895
+ result.message = logObj.args.map((arg) => typeof arg === "string" ? arg : safeStringify(arg)).join("; ");
1896
+ if (typeof logObj.tag === "string" && logObj.tag.length > 0) {
1897
+ result.message = `[${logObj.tag}] ${result.message}`;
1898
+ }
1899
+ return result;
1900
+ }
1901
+ const mergedErr = logObj.args.reduce(
1902
+ (acc, arg) => {
1903
+ if (arg === error) {
1904
+ return acc;
1905
+ }
1906
+ const msg = typeof arg === "string" ? arg : safeStringify(arg);
1907
+ return wrapErrorMessage(acc, msg);
1908
+ },
1909
+ mergeErrorCause(error)
1910
+ );
1911
+ result.message = mergedErr.message;
1912
+ result.error = {
1913
+ message: mergedErr.message,
1914
+ name: mergedErr.name
1915
+ };
1916
+ if (mergedErr.stack) {
1917
+ const stack = parseStack(mergedErr.stack);
1918
+ result.error.stack = stack.join("\n");
1919
+ result.message += "\n" + stack.slice(1).map((l) => " " + l).join("\n");
1920
+ }
1921
+ if (typeof logObj.tag === "string" && logObj.tag.length > 0) {
1922
+ result.message = `[${logObj.tag}] ${result.message}`;
1923
+ }
1924
+ return result;
1925
+ }
1926
+
1927
+ const consola = createConsola({
1928
+ level: LogLevels.debug
1929
+ });
1930
+ function formatLogObj(logObj) {
1931
+ return formattedLogObj(logObj);
1932
+ }
1933
+
1934
+ exports.LogLevels = LogLevels;
1935
+ exports.consola = consola;
1936
+ exports.formatLogObj = formatLogObj;
1937
+ exports.logger = consola;
1938
+ exports.rootLogger = consola;