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