@visulima/pail 4.0.0-alpha.10 → 4.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/LICENSE.md +143 -931
  3. package/dist/error.d.ts +95 -96
  4. package/dist/index.browser.d.ts +557 -47
  5. package/dist/index.browser.js +2 -2
  6. package/dist/index.server.d.ts +722 -65
  7. package/dist/index.server.js +27 -410
  8. package/dist/middleware/elysia.d.ts +65 -63
  9. package/dist/middleware/elysia.js +2 -2
  10. package/dist/middleware/express.d.ts +73 -71
  11. package/dist/middleware/express.js +1 -1
  12. package/dist/middleware/fastify.d.ts +69 -67
  13. package/dist/middleware/fastify.js +2 -2
  14. package/dist/middleware/hono.d.ts +74 -72
  15. package/dist/middleware/next/handler.d.ts +101 -34
  16. package/dist/middleware/sveltekit.d.ts +100 -98
  17. package/dist/object-tree.d.ts +67 -70
  18. package/dist/packem_shared/{AbstractJsonReporter-DlugSJpY.js → AbstractJsonReporter-BO8Calb4.js} +1 -5
  19. package/dist/packem_shared/{AbstractJsonReporter-CjtVgHbU.js → AbstractJsonReporter-nOj0Ft1F.js} +1 -5
  20. package/dist/packem_shared/{JsonReporter-Dbw82ewj.js → JsonReporter-CCmj7oYL.js} +1 -1
  21. package/dist/packem_shared/{JsonReporter-BgPvIyC2.js → JsonReporter-Ck2PIAEw.js} +2 -2
  22. package/dist/packem_shared/{PrettyReporter-C2dCzIaf.js → PrettyReporter-CIbrmjUV.js} +2 -4
  23. package/dist/packem_shared/{PrettyReporter-gMqa7j_m.js → PrettyReporter-CNJEO9g7.js} +1250 -15
  24. package/dist/packem_shared/abstract-json-reporter.d-BAgznjyU.d.ts +61 -0
  25. package/dist/packem_shared/{abstract-pretty-reporter-szQO-IgK.js → abstract-pretty-reporter-CkqCt5hg.js} +2300 -2298
  26. package/dist/packem_shared/create-middleware-logger.d-DheMh8q4.d.ts +47 -0
  27. package/dist/packem_shared/{index-Bx3-C0j9.js → index-6cG1Kp0t.js} +2 -2
  28. package/dist/packem_shared/types.d-BeLumqgD.d.ts +246 -0
  29. package/dist/packem_shared/types.d-C51XNfQz.d.ts +194 -0
  30. package/dist/packem_shared/types.d-CM5ie2qm.d.ts +236 -0
  31. package/dist/packem_shared/wide-event.d-B-t8ZnhI.d.ts +704 -0
  32. package/dist/packem_shared/{write-stream-BuFtjATz.js → write-stream-MDqyXmc_.js} +1 -1
  33. package/dist/processor/caller/caller-processor.d.ts +49 -47
  34. package/dist/processor/caller/caller-processor.js +1 -1
  35. package/dist/processor/environment-processor.d.ts +113 -113
  36. package/dist/processor/message-formatter-processor.d.ts +51 -49
  37. package/dist/processor/message-formatter-processor.js +2 -2
  38. package/dist/processor/opentelemetry-processor.d.ts +69 -66
  39. package/dist/processor/redact-processor.d.ts +60 -41
  40. package/dist/processor/sampling-processor.d.ts +102 -101
  41. package/dist/reporter/file/json-file-reporter.d.ts +91 -42
  42. package/dist/reporter/file/json-file-reporter.js +1 -1
  43. package/dist/reporter/http/abstract-http-reporter.d.ts +213 -211
  44. package/dist/reporter/http/abstract-http-reporter.js +1 -1
  45. package/dist/reporter/http/http-reporter.d.ts +40 -36
  46. package/dist/reporter/http/http-reporter.edge-light.d.ts +430 -38
  47. package/dist/reporter/http/http-reporter.edge-light.js +1 -5
  48. package/dist/reporter/json/index.browser.d.ts +99 -3
  49. package/dist/reporter/json/index.browser.js +2 -2
  50. package/dist/reporter/json/index.d.ts +51 -3
  51. package/dist/reporter/json/index.js +2 -2
  52. package/dist/reporter/pretty/index.browser.d.ts +106 -2
  53. package/dist/reporter/pretty/index.browser.js +1 -1
  54. package/dist/reporter/pretty/index.d.ts +219 -2
  55. package/dist/reporter/pretty/index.js +1 -1
  56. package/dist/reporter/simple/simple-reporter.server.d.ts +168 -18
  57. package/dist/reporter/simple/simple-reporter.server.js +3 -2
  58. package/dist/wide-event.d.ts +5 -300
  59. package/dist/wide-event.js +3 -2
  60. package/package.json +9 -21
  61. package/dist/constants.d.ts +0 -37
  62. package/dist/interactive/index.d.ts +0 -2
  63. package/dist/interactive/index.js +0 -2
  64. package/dist/interactive/interactive-manager.d.ts +0 -108
  65. package/dist/interactive/interactive-stream-hook.d.ts +0 -68
  66. package/dist/middleware/next/middleware.d.ts +0 -59
  67. package/dist/middleware/next/storage.d.ts +0 -14
  68. package/dist/middleware/shared/create-middleware-logger.d.ts +0 -82
  69. package/dist/middleware/shared/headers.d.ts +0 -14
  70. package/dist/middleware/shared/routes.d.ts +0 -30
  71. package/dist/middleware/shared/storage.d.ts +0 -29
  72. package/dist/packem_shared/InteractiveManager-CowYA3Hx.js +0 -178
  73. package/dist/packem_shared/InteractiveStreamHook-BypRlYTX.js +0 -133
  74. package/dist/packem_shared/Spinner-Cokext9b.js +0 -2183
  75. package/dist/packem_shared/getBarChar-D7JfmdTr.js +0 -459
  76. package/dist/packem_shared/index-BEfVUy9P.js +0 -1256
  77. package/dist/pail.browser.d.ts +0 -412
  78. package/dist/pail.server.d.ts +0 -233
  79. package/dist/processor/caller/get-caller-filename.d.ts +0 -23
  80. package/dist/progress-bar.d.ts +0 -145
  81. package/dist/progress-bar.js +0 -459
  82. package/dist/reporter/file/utils/rotating-file-stream.d.ts +0 -48
  83. package/dist/reporter/http/utils/compression.d.ts +0 -7
  84. package/dist/reporter/http/utils/log-size-error.d.ts +0 -30
  85. package/dist/reporter/http/utils/retry.d.ts +0 -27
  86. package/dist/reporter/json/abstract-json-reporter.d.ts +0 -61
  87. package/dist/reporter/json/json-reporter.browser.d.ts +0 -40
  88. package/dist/reporter/json/json-reporter.server.d.ts +0 -50
  89. package/dist/reporter/pretty/abstract-pretty-reporter.d.ts +0 -83
  90. package/dist/reporter/pretty/pretty-reporter.browser.d.ts +0 -36
  91. package/dist/reporter/pretty/pretty-reporter.server.d.ts +0 -70
  92. package/dist/reporter/raw/raw-reporter.browser.d.ts +0 -5
  93. package/dist/reporter/raw/raw-reporter.server.d.ts +0 -13
  94. package/dist/reporter/utils/default-inspector-config.d.ts +0 -3
  95. package/dist/reporter/utils/format-label.d.ts +0 -3
  96. package/dist/spinner.d.ts +0 -220
  97. package/dist/spinner.js +0 -2183
  98. package/dist/types.d.ts +0 -241
  99. package/dist/utils/ansi-escapes.d.ts +0 -4
  100. package/dist/utils/arrayify.d.ts +0 -2
  101. package/dist/utils/get-longest-badge.d.ts +0 -4
  102. package/dist/utils/get-longest-label.d.ts +0 -4
  103. package/dist/utils/merge-types.d.ts +0 -4
  104. package/dist/utils/stream/safe-stream-handler.d.ts +0 -21
  105. package/dist/utils/write-console-log-based-on-level.d.ts +0 -4
  106. package/dist/utils/write-stream.d.ts +0 -2
@@ -17,2540 +17,2540 @@ const __cjs_getBuiltinModule = (module) => {
17
17
  return __cjs_require(module);
18
18
  };
19
19
 
20
+ const {
21
+ createRequire
22
+ } = __cjs_getBuiltinModule("node:module");
20
23
  const process$2 = __cjs_getProcess;
21
24
  const {
22
25
  execFileSync
23
26
  } = __cjs_getBuiltinModule("node:child_process");
24
27
  const fs = __cjs_getBuiltinModule("node:fs");
25
28
  const tty = __cjs_getBuiltinModule("node:tty");
26
- const {
27
- createRequire
28
- } = __cjs_getBuiltinModule("node:module");
29
- import { grey, green, cyan, red, yellow, bold, magenta, underline } from '@visulima/colorize';
29
+ import colorize from '@visulima/colorize';
30
30
 
31
- const ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
32
- const fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
33
- const halfwidthRanges = [8361, 8361, 65377, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65512, 65518];
34
- const narrowRanges = [32, 126, 162, 163, 165, 166, 172, 172, 175, 175, 10214, 10221, 10629, 10630];
35
- const wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];
36
- const isInRange = (ranges, codePoint) => {
37
- let low = 0;
38
- let high = Math.floor(ranges.length / 2) - 1;
39
- while (low <= high) {
40
- const mid = Math.floor((low + high) / 2);
41
- const i = mid * 2;
42
- if (codePoint < ranges[i]) {
43
- high = mid - 1;
44
- } else if (codePoint > ranges[i + 1]) {
45
- low = mid + 1;
46
- } else {
47
- return true;
48
- }
49
- }
50
- return false;
51
- };
52
- const minimumAmbiguousCodePoint = ambiguousRanges[0];
53
- const maximumAmbiguousCodePoint = ambiguousRanges.at(-1);
54
- const minimumFullWidthCodePoint = fullwidthRanges[0];
55
- const maximumFullWidthCodePoint = fullwidthRanges.at(-1);
56
- const minimumHalfWidthCodePoint = halfwidthRanges[0];
57
- const maximumHalfWidthCodePoint = halfwidthRanges.at(-1);
58
- const minimumNarrowCodePoint = narrowRanges[0];
59
- const maximumNarrowCodePoint = narrowRanges.at(-1);
60
- const minimumWideCodePoint = wideRanges[0];
61
- const maximumWideCodePoint = wideRanges.at(-1);
62
- const commonCjkCodePoint = 19968;
63
- const [wideFastPathStart, wideFastPathEnd] = findWideFastPathRange(wideRanges);
64
- function findWideFastPathRange(ranges) {
65
- let fastPathStart = ranges[0];
66
- let fastPathEnd = ranges[1];
67
- for (let index = 0; index < ranges.length; index += 2) {
68
- const start = ranges[index];
69
- const end = ranges[index + 1];
70
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
71
- return [start, end];
72
- }
73
- if (end - start > fastPathEnd - fastPathStart) {
74
- fastPathStart = start;
75
- fastPathEnd = end;
76
- }
77
- }
78
- return [fastPathStart, fastPathEnd];
79
- }
80
- const isAmbiguous = (codePoint) => {
81
- if (codePoint < minimumAmbiguousCodePoint || codePoint > maximumAmbiguousCodePoint) {
82
- return false;
83
- }
84
- return isInRange(ambiguousRanges, codePoint);
31
+ const EXTENDED_RFC_5424_LOG_LEVELS = {
32
+ alert: 7,
33
+ // Action must be taken immediately. Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
34
+ critical: 6,
35
+ // Critical conditions. Example: Application component unavailable, unexpected exception.
36
+ debug: 1,
37
+ // Detailed debug information.
38
+ emergency: 8,
39
+ // Emergency: system is unusable.
40
+ error: 5,
41
+ // Runtime errors that do not require immediate action but should typically be logged and monitored.
42
+ informational: 2,
43
+ // Interesting events. Examples: User logs in, SQL logs.
44
+ notice: 3,
45
+ // Normal but significant events.
46
+ trace: 2,
47
+ // Trace information.
48
+ warning: 4
49
+ // Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
85
50
  };
86
- const isFullWidth = (codePoint) => {
87
- if (codePoint < minimumFullWidthCodePoint || codePoint > maximumFullWidthCodePoint) {
88
- return false;
51
+ const LOG_TYPES = {
52
+ alert: {
53
+ color: "red",
54
+ label: "alert",
55
+ logLevel: "alert"
56
+ },
57
+ await: {
58
+ color: "blue",
59
+ label: "awaiting",
60
+ logLevel: "informational"
61
+ },
62
+ complete: {
63
+ color: "cyan",
64
+ label: "complete",
65
+ logLevel: "informational"
66
+ },
67
+ critical: {
68
+ color: "redBright",
69
+ label: "critical",
70
+ logLevel: "critical"
71
+ },
72
+ debug: {
73
+ color: "gray",
74
+ label: "debug",
75
+ logLevel: "debug"
76
+ },
77
+ emergency: {
78
+ color: "redBright",
79
+ label: "emergency",
80
+ logLevel: "emergency"
81
+ },
82
+ error: {
83
+ color: "red",
84
+ label: "error",
85
+ logLevel: "error"
86
+ },
87
+ info: {
88
+ color: "blueBright",
89
+ label: "info",
90
+ logLevel: "informational"
91
+ },
92
+ log: {
93
+ label: "",
94
+ logLevel: "informational"
95
+ },
96
+ notice: {
97
+ color: "magentaBright",
98
+ label: "notice",
99
+ logLevel: "notice"
100
+ },
101
+ pending: {
102
+ color: "magenta",
103
+ label: "pending",
104
+ logLevel: "informational"
105
+ },
106
+ start: {
107
+ color: "greenBright",
108
+ label: "start",
109
+ logLevel: "informational"
110
+ },
111
+ stop: {
112
+ color: "red",
113
+ label: "stop",
114
+ logLevel: "informational"
115
+ },
116
+ success: {
117
+ color: "green",
118
+ label: "success",
119
+ logLevel: "informational"
120
+ },
121
+ trace: {
122
+ color: "cyanBright",
123
+ label: "trace",
124
+ logLevel: "trace"
125
+ },
126
+ wait: {
127
+ color: "blue",
128
+ label: "waiting",
129
+ logLevel: "informational"
130
+ },
131
+ warn: {
132
+ color: "yellow",
133
+ label: "warning",
134
+ logLevel: "warning"
135
+ },
136
+ warning: {
137
+ color: "yellow",
138
+ label: "warning",
139
+ logLevel: "warning"
140
+ },
141
+ watch: {
142
+ color: "yellowBright",
143
+ label: "watching",
144
+ logLevel: "informational"
89
145
  }
90
- return isInRange(fullwidthRanges, codePoint);
91
146
  };
92
- const isHalfWidth = (codePoint) => {
93
- if (codePoint < minimumHalfWidthCodePoint || codePoint > maximumHalfWidthCodePoint) {
94
- return false;
147
+ const EMPTY_SYMBOL = /* @__PURE__ */ Symbol("EMPTY");
148
+
149
+ const getLongestLabel = (types) => {
150
+ const labels = Object.keys(types).map((x) => types[x].label ?? "");
151
+ if (labels.length === 0) {
152
+ return "";
95
153
  }
96
- return isInRange(halfwidthRanges, codePoint);
154
+ return labels.reduce((x, y) => x.length > y.length ? x : y, "");
97
155
  };
98
- const isNarrow = (codePoint) => {
99
- if (codePoint < minimumNarrowCodePoint || codePoint > maximumNarrowCodePoint) {
100
- return false;
156
+
157
+ const TRUNCATOR = "…";
158
+ const inspectList = (list, from, options, inspect2, inspectItem, separator = ", ") => {
159
+ const size = list.length;
160
+ if (size === 0) {
161
+ return "";
101
162
  }
102
- return isInRange(narrowRanges, codePoint);
103
- };
104
- const isWide = (codePoint) => {
105
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
106
- return true;
163
+ let inspect_ = inspect2;
164
+ if (inspectItem !== void 0) {
165
+ inspect_ = inspectItem;
107
166
  }
108
- if (codePoint < minimumWideCodePoint || codePoint > maximumWideCodePoint) {
109
- return false;
167
+ const originalLength = options.truncate;
168
+ let output = "";
169
+ let peek = "";
170
+ let truncated = "";
171
+ for (let index = 0; index < size; index += 1) {
172
+ const last = index + 1 === list.length;
173
+ const secondToLast = index + 2 === list.length;
174
+ truncated = `${TRUNCATOR}(${String(list.length - index)})`;
175
+ let value = list[index];
176
+ options.truncate = originalLength - output.length - (last ? 0 : separator.length);
177
+ const string = peek || inspect_(value, from, options, inspect2) + (last ? "" : separator);
178
+ const nextLength = output.length + string.length;
179
+ const truncatedLength = nextLength + truncated.length;
180
+ if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
181
+ break;
182
+ }
183
+ if (!last && !secondToLast && truncatedLength > originalLength) {
184
+ break;
185
+ }
186
+ value = list[index + 1];
187
+ const peekSuffix = secondToLast ? "" : separator;
188
+ if (last) {
189
+ peek = "";
190
+ } else {
191
+ peek = inspect_(value, from, options, inspect2) + peekSuffix;
192
+ }
193
+ if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
194
+ break;
195
+ }
196
+ output += string;
197
+ if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
198
+ truncated = `${TRUNCATOR}(${String(list.length - index - 1)})`;
199
+ break;
200
+ }
201
+ truncated = "";
110
202
  }
111
- return isInRange(wideRanges, codePoint);
203
+ return `${output}${truncated}`;
112
204
  };
113
- function getCategory(codePoint) {
114
- if (isAmbiguous(codePoint)) {
115
- return "ambiguous";
116
- }
117
- if (isFullWidth(codePoint)) {
118
- return "fullwidth";
205
+ const inspectAttribute = ([key, value], _, options) => {
206
+ options.truncate -= 3;
207
+ if (!value) {
208
+ return options.stylize(String(key), "yellow");
119
209
  }
120
- if (isHalfWidth(codePoint)) {
121
- return "halfwidth";
122
- }
123
- if (isNarrow(codePoint)) {
124
- return "narrow";
125
- }
126
- if (isWide(codePoint)) {
127
- return "wide";
128
- }
129
- return "neutral";
130
- }
131
-
132
- function validate(codePoint) {
133
- if (!Number.isSafeInteger(codePoint)) {
134
- throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
135
- }
136
- }
137
- function eastAsianWidthType(codePoint) {
138
- validate(codePoint);
139
- return getCategory(codePoint);
140
- }
141
-
142
- const r = String.raw;
143
- const e = r`\p{Emoji}(?:\p{EMod}|[\u{E0020}-\u{E007E}]+\u{E007F}|\uFE0F?\u20E3?)`;
144
- const emojiRegex = () => new RegExp(r`\p{RI}{2}|(?![#*\d](?!\uFE0F?\u20E3))${e}(?:\u200D${e})*`, "gu");
145
- const ESCAPES = /* @__PURE__ */ new Set(["\x1B", "›"]);
146
- const ANSI_ESCAPE_BELL = "\x07";
147
- const ANSI_CSI = "[";
148
- const ANSI_SGR_TERMINATOR = "m";
149
- const ANSI_ESCAPE_LINK = `]8;;`;
150
- const END_CODE = 39;
151
- const RE_ZERO_WIDTH = /[\u200B\uFEFF\u2060-\u2064]/g;
152
- const RE_ESCAPE_PATTERN = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`);
153
- const ANSI_RESET_CODES = Object.freeze(
154
- /* @__PURE__ */ new Map([
155
- [0, 0],
156
- // Reset all
157
- [1, 22],
158
- // Bold → Not bold
159
- [2, 22],
160
- // Dim → Not bold
161
- [3, 23],
162
- // Italic → Not italic
163
- [4, 24],
164
- // Underline → Not underline
165
- [7, 27],
166
- // Inverse → Not inverse
167
- [8, 28],
168
- // Hidden → Not hidden
169
- [9, 29],
170
- // Strikethrough → Not strikethrough
171
- [30, 39],
172
- // Foreground colors → Default foreground
173
- [31, 39],
174
- [32, 39],
175
- [33, 39],
176
- [34, 39],
177
- [35, 39],
178
- [36, 39],
179
- [37, 39],
180
- [40, 49],
181
- // Background colors → Default background
182
- [41, 49],
183
- [42, 49],
184
- [43, 49],
185
- [44, 49],
186
- [45, 49],
187
- [46, 49],
188
- [47, 49],
189
- [90, 39]
190
- // Bright foreground → Default foreground
191
- ])
192
- );
193
- const RE_ANSI = /[\u001B\u009B](?:[[()#;?]{0,10}(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><]|\]8;;[^\u0007\u001B]{0,100}(?:\u0007|\u001B\\))/g;
194
- const RE_CONTROL = /[\u0000-\u0008\n-\u001F\u007F-\u009F]{1,1000}/y;
195
- const RE_EMOJI = emojiRegex();
196
-
197
- const charWidthCache = /* @__PURE__ */ new Map();
198
- const RE_LATIN_CHARS = /(?:[\u0020-\u007E\u00A0-\u00FF](?!\uFE0F)){1,1000}/y;
199
- const getCharType = (codePoint) => {
200
- if (codePoint >= 32 && codePoint <= 126) {
201
- return "latin";
202
- }
203
- if (codePoint === 8203 || codePoint === 8204 || codePoint === 8205 || codePoint === 8288) {
204
- return "zero";
210
+ return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`;
211
+ };
212
+ const inspectNode = (node, inspect2, options) => {
213
+ switch (node.nodeType) {
214
+ case 1: {
215
+ return inspectHTMLElement(node, node, options, inspect2);
216
+ }
217
+ case 3: {
218
+ return inspect2(node.data, inspect2, options);
219
+ }
220
+ default: {
221
+ return inspect2(node, inspect2, options);
222
+ }
205
223
  }
206
- if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
207
- return "control";
224
+ };
225
+ const inspectNodeCollection = (collection, options, inspect2, _) => inspectList(collection, collection, options, inspect2, inspectNode, "\n");
226
+ const inspectHTMLElement = (element, object, options, inspect2) => {
227
+ const properties = element.getAttributeNames();
228
+ const name = element.tagName.toLowerCase();
229
+ const head = options.stylize(`<${name}`, "special");
230
+ const headClose = options.stylize(`>`, "special");
231
+ const tail = options.stylize(`</${name}>`, "special");
232
+ options.truncate -= name.length * 2 + 5;
233
+ let propertyContents = "";
234
+ if (properties.length > 0) {
235
+ propertyContents += " ";
236
+ propertyContents += inspectList(
237
+ properties.map((key) => [key, element.getAttribute(key)]),
238
+ object,
239
+ options,
240
+ inspect2,
241
+ inspectAttribute,
242
+ " "
243
+ );
208
244
  }
209
- if (codePoint >= 160 && codePoint <= 255) {
210
- return "latin";
245
+ options.truncate -= propertyContents.length;
246
+ const { truncate: truncate2 } = options;
247
+ let children = inspectNodeCollection(element.children, options, inspect2);
248
+ if (children && children.length > truncate2) {
249
+ children = `${TRUNCATOR}(${String(element.children.length)})`;
211
250
  }
212
- if (codePoint >= 9472 && codePoint <= 9599) {
213
- return "latin";
251
+ return `${head}${propertyContents}${headClose}${children}${tail}`;
252
+ };
253
+ const inspectArguments = (arguments_, options, inspect2) => {
254
+ if (arguments_.length === 0) {
255
+ return "Arguments []";
214
256
  }
215
- if (codePoint >= 4352 && codePoint <= 4607 || codePoint >= 11904 && codePoint <= 40959 || codePoint >= 44032 && codePoint <= 55215 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65280 && codePoint <= 65519 && !(codePoint >= 65377 && codePoint <= 65439) || codePoint >= 12352 && codePoint <= 12543) {
216
- return "wide";
257
+ options.truncate -= 13;
258
+ return `Arguments [ ${inspectList(arguments_, arguments_, options, inspect2)} ]`;
259
+ };
260
+ const getIndent = (indent, depth) => {
261
+ let baseIndent;
262
+ if (indent === " ") {
263
+ baseIndent = " ";
264
+ } else if (typeof indent === "number" && indent > 0) {
265
+ baseIndent = Array.from({ length: indent + 1 }).join(" ");
266
+ } else {
267
+ return void 0;
217
268
  }
218
- if (codePoint === 8230) {
219
- return "latin";
269
+ return {
270
+ base: baseIndent,
271
+ prev: `
272
+ ${Array.from({ length: depth + 1 }).join(baseIndent)}`
273
+ };
274
+ };
275
+ const indentedJoin = (values, indent) => {
276
+ if (values.length === 0) {
277
+ return "";
220
278
  }
221
- return "other";
279
+ const lineJoiner = indent.prev + indent.base;
280
+ return lineJoiner + values.split(", ").join(`,${lineJoiner}`) + indent.prev;
222
281
  };
223
- const getCachedCharWidth = (codePoint, config) => {
224
- const highBits = Math.floor(codePoint / 65536);
225
- const lowBits = codePoint % 65536;
226
- let lowMap = charWidthCache.get(highBits);
227
- if (!lowMap) {
228
- lowMap = /* @__PURE__ */ new Map();
229
- charWidthCache.set(highBits, lowMap);
282
+ const simpleKeyRegex = /^[a-z_]\w*$/i;
283
+ const quoteEdgesRegex = /^"|"$/g;
284
+ const quoteComplexKey = (key, options) => {
285
+ if (simpleKeyRegex.test(key)) {
286
+ return key;
230
287
  }
231
- if (lowMap.has(lowBits)) {
232
- return lowMap.get(lowBits);
288
+ const stringifiedKey = JSON.stringify(key);
289
+ if (options.quoteStyle === "double") {
290
+ return stringifiedKey.replaceAll('"', String.raw`\"`);
233
291
  }
234
- let width;
235
- if (getCharType(codePoint) === "latin") {
236
- width = config.width.regular;
237
- } else if (getCharType(codePoint) === "control") {
238
- width = config.width.control;
239
- } else if (getCharType(codePoint) === "wide") {
240
- width = config.width.wide;
292
+ return stringifiedKey.replaceAll("'", String.raw`\'`).replaceAll(String.raw`\"`, '"').replaceAll(quoteEdgesRegex, "'");
293
+ };
294
+ const inspectProperty = ([key, value], object, options, inspect2) => {
295
+ options.truncate -= 2;
296
+ let keyString;
297
+ if (typeof key === "string") {
298
+ keyString = quoteComplexKey(key, options);
299
+ } else if (typeof key === "number") {
300
+ keyString = String(key);
241
301
  } else {
242
- const eaw = eastAsianWidthType(codePoint);
243
- switch (eaw) {
244
- case "ambiguous": {
245
- width = config.width.ambiguousIsNarrow ? config.width.regular : config.width.wide;
246
- break;
247
- }
248
- case "fullwidth": {
249
- width = config.width.fullWidth;
250
- break;
251
- }
252
- case "wide": {
253
- width = config.width.wide;
254
- break;
255
- }
256
- default: {
257
- width = config.width.regular;
258
- }
259
- }
302
+ keyString = `[${inspect2(key, object, options)}]`;
260
303
  }
261
- lowMap.set(lowBits, width);
262
- return width;
304
+ options.truncate -= keyString.length;
305
+ const valueString = inspect2(value, object, options);
306
+ return `${keyString}: ${valueString}`;
263
307
  };
264
- const isCombiningCharacter = (codePoint) => {
265
- if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
266
- return true;
267
- }
268
- if (codePoint >= 917760 && codePoint <= 917999 || codePoint >= 65024 && codePoint <= 65039) {
269
- return true;
308
+ const multiLineValues = (values) => {
309
+ for (const value of values) {
310
+ if (Array.isArray(value) || typeof value === "object" && value !== null) {
311
+ return true;
312
+ }
270
313
  }
271
- if (codePoint >= 3633 && codePoint <= 3642 || codePoint >= 3655 && codePoint <= 3662 || codePoint >= 3761 && codePoint <= 3769 || codePoint >= 3771 && codePoint <= 3772 || codePoint >= 3784 && codePoint <= 3789) {
272
- return true;
314
+ return false;
315
+ };
316
+ const inspectArray = (array, options, inspect2, indent) => {
317
+ const nonIndexProperties = Object.keys(array).slice(array.length);
318
+ if (array.length === 0 && nonIndexProperties.length === 0) {
319
+ return "[]";
273
320
  }
274
- if (codePoint >= 2304 && codePoint <= 2307 || codePoint >= 2362 && codePoint <= 2383 || codePoint >= 2385 && codePoint <= 2391 || codePoint >= 2402 && codePoint <= 2403 || codePoint >= 2433 && codePoint <= 2435 || codePoint >= 2492 && codePoint <= 2500 || codePoint >= 2509 && codePoint <= 2509 || codePoint >= 2561 && codePoint <= 2563 || codePoint >= 2620 && codePoint <= 2637) {
275
- return true;
321
+ options.truncate -= 4;
322
+ let listContents = inspectList(array, array, options, inspect2);
323
+ options.truncate -= listContents.length;
324
+ let propertyContents = "";
325
+ if (nonIndexProperties.length > 0) {
326
+ propertyContents = inspectList(
327
+ nonIndexProperties.map((key) => [key, array[key]]),
328
+ array,
329
+ options,
330
+ inspect2,
331
+ inspectProperty
332
+ );
276
333
  }
277
- if (codePoint >= 1611 && codePoint <= 1631 || codePoint >= 1648 && codePoint <= 1648 || codePoint >= 1750 && codePoint <= 1773 || codePoint >= 2276 && codePoint <= 2302) {
278
- return true;
334
+ const hasIndent = indent && multiLineValues(array);
335
+ if (hasIndent) {
336
+ listContents = indentedJoin(listContents, indent);
279
337
  }
280
- if (codePoint >= 1425 && codePoint <= 1469 || codePoint >= 1471 && codePoint <= 1471 || codePoint >= 1473 && codePoint <= 1474 || codePoint >= 1476 && codePoint <= 1477 || codePoint >= 1479 && codePoint <= 1479) {
281
- return true;
338
+ return `[${hasIndent ? "" : " "}${listContents}${propertyContents ? `, ${propertyContents}` : ""}${hasIndent ? "" : " "}]`;
339
+ };
340
+ const separatorRegex = /\d(?=(?:\d{3})+(?!\d))/g;
341
+ const decimalGroupRegex = /\d{3}/g;
342
+ const trailingUnderscoreRegex = /_$/;
343
+ const addNumericSeparator = (number_, string_) => {
344
+ if (number_ === Number.POSITIVE_INFINITY || number_ === Number.NEGATIVE_INFINITY || string_.includes("e")) {
345
+ return string_;
282
346
  }
283
- if (codePoint >= 3893 && codePoint <= 3893 || codePoint >= 3895 && codePoint <= 3895 || codePoint >= 3897 && codePoint <= 3897 || codePoint >= 3953 && codePoint <= 3966 || codePoint >= 3968 && codePoint <= 3972 || codePoint >= 3974 && codePoint <= 3975) {
284
- return true;
347
+ if (typeof number_ === "number") {
348
+ const int = number_ < 0 ? -Math.floor(-number_) : Math.floor(number_);
349
+ if (int !== number_) {
350
+ const intString = String(int);
351
+ const dec = string_.slice(intString.length + 1);
352
+ return (
353
+ // eslint-disable-next-line unicorn/prefer-string-replace-all
354
+ `${intString.replace(separatorRegex, "$&_")}.${dec.replace(decimalGroupRegex, "$&_").replace(trailingUnderscoreRegex, "")}`
355
+ );
356
+ }
285
357
  }
286
- return codePoint >= 768 && codePoint <= 777 || codePoint >= 803 && codePoint <= 803;
358
+ return string_.replace(separatorRegex, "$&_");
287
359
  };
288
- const getStringTruncatedWidth = (input, options = {}) => {
289
- if (!input || input.length === 0) {
290
- return { ellipsed: false, index: 0, truncated: false, width: 0 };
360
+ const isHighSurrogate = (char) => char >= "\uD800" && char <= "\uDBFF";
361
+ const truncate = (string, length, tail = TRUNCATOR) => {
362
+ string = String(string);
363
+ const tailLength = tail.length;
364
+ const stringLength = string.length;
365
+ if (tailLength > length && stringLength > tailLength) {
366
+ return tail;
291
367
  }
292
- const config = {
293
- truncation: {
294
- countAnsiEscapeCodes: options.countAnsiEscapeCodes ?? false,
295
- ellipsis: options.ellipsis ?? "",
296
- ellipsisWidth: options.ellipsisWidth ?? (options.ellipsis ? getStringTruncatedWidth(options.ellipsis, {
297
- ...options,
298
- ellipsis: "",
299
- ellipsisWidth: 0,
300
- limit: Number.POSITIVE_INFINITY
301
- }).width : 0),
302
- limit: options.limit ?? Number.POSITIVE_INFINITY
303
- },
304
- width: {
305
- ambiguousIsNarrow: options.ambiguousIsNarrow ?? false,
306
- ansi: options.ansiWidth ?? 0,
307
- control: options.controlWidth ?? 0,
308
- emoji: options.emojiWidth ?? 2,
309
- fullWidth: options.fullWidth ?? 2,
310
- halfWidth: options.halfWidth ?? 1,
311
- regular: options.regularWidth ?? 1,
312
- tab: options.tabWidth ?? 8,
313
- wide: options.wideWidth ?? 2
314
- }
315
- };
316
- const truncationLimit = Math.max(0, config.truncation.limit - config.truncation.ellipsisWidth);
317
- const { length } = input;
318
- const useCaching = length > 1e4;
319
- let index = 0;
320
- let width = 0;
321
- let truncationIndex = length;
322
- let truncationEnabled = false;
323
- const hasAnsi = input.includes("\x1B") || input.includes("›");
324
- while (index < length) {
325
- if (hasAnsi && (input[index] === "\x1B" || input[index] === "›")) {
326
- if (input.startsWith("\x1B]8;;", index)) {
327
- const BELL = "\x07";
328
- const OSC8_CLOSER = `\x1B]8;;${BELL}`;
329
- const OSC8_CLOSER_LEN = OSC8_CLOSER.length;
330
- const endOfParametersIndex = input.indexOf(BELL, index + 5);
331
- if (endOfParametersIndex === -1) ;
332
- else {
333
- const startOfCloserIndex = input.indexOf(OSC8_CLOSER, endOfParametersIndex + 1);
334
- if (startOfCloserIndex === -1) ;
335
- else {
336
- const endOfSequenceIndex = startOfCloserIndex + OSC8_CLOSER_LEN;
337
- const linkText = input.slice(endOfParametersIndex + 1, startOfCloserIndex);
338
- const strippedLinkText = linkText.replace(RE_ANSI, "");
339
- const linkTextWidthResult = getStringTruncatedWidth(strippedLinkText, {
340
- ambiguousIsNarrow: config.width.ambiguousIsNarrow,
341
- ansiWidth: config.width.ansi,
342
- controlWidth: config.width.control,
343
- countAnsiEscapeCodes: false,
344
- // Never count ANSI in link text width
345
- ellipsis: config.truncation.ellipsis,
346
- ellipsisWidth: config.truncation.ellipsisWidth,
347
- emojiWidth: config.width.emoji,
348
- fullWidth: config.width.fullWidth,
349
- halfWidth: config.width.halfWidth,
350
- limit: Math.max(0, truncationLimit - width),
351
- regularWidth: config.width.regular,
352
- tabWidth: config.width.tab,
353
- wideWidth: config.width.wide
354
- });
355
- const textWidth = linkTextWidthResult.width;
356
- if (linkTextWidthResult.truncated) {
357
- truncationEnabled = true;
358
- truncationIndex = Math.min(truncationIndex, index);
359
- } else if (width + textWidth > truncationLimit) {
360
- truncationIndex = Math.min(truncationIndex, index);
361
- truncationEnabled = true;
362
- if (width + textWidth > config.truncation.limit) {
363
- break;
364
- }
365
- }
366
- width += textWidth;
367
- index = endOfSequenceIndex;
368
- if (truncationEnabled && width >= config.truncation.limit) {
369
- break;
370
- }
371
- continue;
372
- }
373
- }
374
- }
375
- RE_ANSI.lastIndex = index;
376
- if (RE_ANSI.test(input)) {
377
- const ansiLength = RE_ANSI.lastIndex - index;
378
- const ansiWidth = config.truncation.countAnsiEscapeCodes ? ansiLength : config.width.ansi;
379
- if (width + ansiWidth > truncationLimit) {
380
- truncationIndex = Math.min(truncationIndex, index);
381
- if (width + ansiWidth > config.truncation.limit) {
382
- truncationEnabled = true;
383
- break;
384
- }
385
- }
386
- width += ansiWidth;
387
- index = RE_ANSI.lastIndex;
388
- continue;
389
- }
390
- }
391
- const charCode = input.codePointAt(index);
392
- if (charCode === 8203 || charCode === 65279 || charCode >= 8288 && charCode <= 8292) {
393
- index += 1;
394
- continue;
395
- }
396
- if (charCode === 9) {
397
- if (width + config.width.tab > truncationLimit) {
398
- truncationIndex = Math.min(truncationIndex, index);
399
- if (width + config.width.tab > config.truncation.limit) {
400
- truncationEnabled = true;
401
- break;
402
- }
403
- }
404
- width += config.width.tab;
405
- index += 1;
406
- continue;
407
- }
408
- RE_LATIN_CHARS.lastIndex = index;
409
- if (RE_LATIN_CHARS.test(input)) {
410
- const latinLength = RE_LATIN_CHARS.lastIndex - index;
411
- const latinWidth = latinLength * config.width.regular;
412
- if (width + latinWidth > truncationLimit) {
413
- const charsToLimit = Math.floor((truncationLimit - width) / config.width.regular);
414
- truncationIndex = Math.min(truncationIndex, index + charsToLimit);
415
- if (width + latinWidth > config.truncation.limit) {
416
- truncationEnabled = true;
417
- break;
418
- }
419
- }
420
- width += latinWidth;
421
- index = RE_LATIN_CHARS.lastIndex;
422
- continue;
423
- }
424
- if (charCode <= 31 || charCode >= 127 && charCode <= 159) {
425
- RE_CONTROL.lastIndex = index;
426
- if (RE_CONTROL.test(input)) {
427
- const controlLength = RE_CONTROL.lastIndex - index;
428
- const controlWidth = controlLength * config.width.control;
429
- if (width + controlWidth > truncationLimit) {
430
- truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / config.width.control));
431
- if (width + controlWidth > config.truncation.limit) {
432
- truncationEnabled = true;
433
- break;
434
- }
435
- }
436
- width += controlWidth;
437
- index = RE_CONTROL.lastIndex;
438
- continue;
439
- }
440
- }
441
- RE_EMOJI.lastIndex = index;
442
- if (RE_EMOJI.test(input)) {
443
- if (width + config.width.emoji > truncationLimit) {
444
- truncationIndex = Math.min(truncationIndex, index);
445
- if (width + config.width.emoji > config.truncation.limit) {
446
- truncationEnabled = true;
447
- break;
448
- }
449
- }
450
- width += config.width.emoji;
451
- index = RE_EMOJI.lastIndex;
452
- continue;
453
- }
454
- const codePoint = input.codePointAt(index) ?? 0;
455
- if (isCombiningCharacter(codePoint)) {
456
- index += codePoint > 65535 ? 2 : 1;
457
- continue;
458
- }
459
- let charWidth;
460
- if (useCaching) {
461
- charWidth = getCachedCharWidth(codePoint, config);
462
- } else {
463
- const charType = getCharType(codePoint);
464
- switch (charType) {
465
- case "control": {
466
- charWidth = config.width.control;
467
- break;
468
- }
469
- case "latin": {
470
- charWidth = config.width.regular;
471
- break;
472
- }
473
- case "wide": {
474
- charWidth = config.width.wide;
475
- break;
476
- }
477
- case "zero": {
478
- charWidth = 0;
479
- break;
480
- }
481
- default: {
482
- const eaw = eastAsianWidthType(codePoint);
483
- switch (eaw) {
484
- case "ambiguous": {
485
- charWidth = config.width.ambiguousIsNarrow ? config.width.regular : config.width.wide;
486
- break;
487
- }
488
- case "fullwidth": {
489
- charWidth = config.width.fullWidth;
490
- break;
491
- }
492
- case "wide": {
493
- charWidth = config.width.wide;
494
- break;
495
- }
496
- default: {
497
- charWidth = config.width.regular;
498
- }
499
- }
500
- }
501
- }
502
- }
503
- if (width + charWidth > truncationLimit) {
504
- truncationIndex = Math.min(truncationIndex, index);
505
- if (width + charWidth > config.truncation.limit) {
506
- truncationEnabled = true;
507
- break;
508
- }
368
+ if (stringLength > length && stringLength > tailLength) {
369
+ let end = length - tailLength;
370
+ if (end > 0 && isHighSurrogate(string[end - 1])) {
371
+ end -= 1;
509
372
  }
510
- width += charWidth;
511
- index += codePoint > 65535 ? 2 : 1;
373
+ return `${string.slice(0, end)}${tail}`;
512
374
  }
513
- let finalWidth = width;
514
- let ellipsed = false;
515
- if (truncationEnabled && config.truncation.limit >= config.truncation.ellipsisWidth) {
516
- finalWidth = config.truncation.limit;
517
- ellipsed = true;
375
+ return string;
376
+ };
377
+ const inspectBigInt = (number, options) => {
378
+ let nums = truncate(number.toString(), options.truncate - 1);
379
+ if (nums !== TRUNCATOR) {
380
+ nums += "n";
518
381
  }
519
- return {
520
- ellipsed,
521
- index: truncationEnabled ? truncationIndex : length,
522
- truncated: truncationEnabled,
523
- width: finalWidth
524
- };
382
+ return options.stylize(options.numericSeparator ? addNumericSeparator(number, nums) : nums, "bigint");
525
383
  };
526
-
527
- const getStringWidth = (input, options = {}) => getStringTruncatedWidth(input, { ...options, ellipsis: "", ellipsisWidth: 0, limit: Number.POSITIVE_INFINITY }).width;
528
-
529
- const RE_ANSI_CODE = /\x1B\[(\d+)m/;
530
- class AnsiStateTracker {
531
- activeForeground = void 0;
532
- activeBackground = void 0;
533
- // Track other formatting (bold, italic, etc.)
534
- activeFormatting = [];
535
- /**
536
- * Processes an escape sequence and updates the internal state
537
- * @param sequence The escape sequence to process
538
- */
539
- processEscape(sequence) {
540
- const match = RE_ANSI_CODE.exec(sequence);
541
- if (!match) {
542
- return;
543
- }
544
- const code = Number.parseInt(match[1], 10);
545
- switch (code) {
546
- case 0: {
547
- this.activeForeground = void 0;
548
- this.activeBackground = void 0;
549
- this.activeFormatting = [];
550
- break;
551
- }
552
- case 39: {
553
- this.activeForeground = void 0;
554
- break;
555
- }
556
- case 49: {
557
- this.activeBackground = void 0;
558
- break;
559
- }
560
- default: {
561
- if (code >= 30 && code <= 37 || code >= 90 && code <= 97) {
562
- this.activeForeground = sequence;
563
- } else if (code >= 40 && code <= 47 || code >= 100 && code <= 107) {
564
- this.activeBackground = sequence;
565
- } else if ([1, 2, 3, 4, 7, 8, 9].includes(code)) {
566
- this.activeFormatting.push(sequence);
567
- } else if ([22, 23, 24, 27, 28, 29].includes(code)) {
568
- const formatResetMap = {
569
- 22: "[1m",
570
- // Reset bold
571
- 23: "[3m",
572
- // Reset italic
573
- 24: "[4m",
574
- // Reset underline
575
- 27: "[7m",
576
- // Reset inverse
577
- 28: "[8m",
578
- // Reset hidden
579
- 29: "[9m"
580
- // Reset strikethrough
581
- };
582
- const formatToRemove = formatResetMap[code];
583
- if (formatToRemove) {
584
- this.activeFormatting = this.activeFormatting.filter((fmt) => !fmt.includes(formatToRemove));
585
- }
586
- }
587
- }
588
- }
384
+ const gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
385
+ return O.__proto__;
386
+ } : void 0);
387
+ const inspectObject$1 = (object, options, inspect2, indent) => {
388
+ if ("window" in globalThis && object === globalThis) {
389
+ return "{ [object Window] }";
589
390
  }
590
- /**
591
- * Gets all active escape sequences to apply.
592
- * @returns String with all active escapes
593
- */
594
- getStartEscapesForAllActiveAttributes() {
595
- return [this.activeBackground, this.activeForeground, ...this.activeFormatting].filter(Boolean).join("");
391
+ if (object === globalThis || "global" in globalThis && object === globalThis) {
392
+ return "{ [object globalThis] }";
596
393
  }
597
- /**
598
- * Gets all closing escape sequences for the currently active attributes.
599
- * The order is generally reverse of application: formatting, foreground, background.
600
- * @returns String with all necessary closing escapes.
601
- */
602
- getEndEscapesForAllActiveAttributes() {
603
- const closingEscapes = [];
604
- if (this.activeFormatting.length > 0) {
605
- const formatResetMap = {
606
- "\x1B[1m": "\x1B[22m",
607
- // Bold
608
- "\x1B[2m": "\x1B[22m",
609
- // Faint/Dim (also reset by 22)
610
- "\x1B[3m": "\x1B[23m",
611
- // Italic
612
- "\x1B[4m": "\x1B[24m",
613
- // Underline
614
- "\x1B[7m": "\x1B[27m",
615
- // Inverse
616
- "\x1B[8m": "\x1B[28m",
617
- // Hidden/Conceal
618
- "\x1B[9m": "\x1B[29m"
619
- // Strikethrough
620
- };
621
- [...this.activeFormatting].toReversed().forEach((formatCode) => {
622
- const resetCode = formatResetMap[formatCode];
623
- if (resetCode) {
624
- closingEscapes.push(resetCode);
625
- }
626
- });
627
- }
628
- if (this.activeForeground) {
629
- closingEscapes.push("\x1B[39m");
630
- }
631
- if (this.activeBackground) {
632
- closingEscapes.push("\x1B[49m");
633
- }
634
- return closingEscapes.join("");
394
+ const properties = Object.getOwnPropertyNames(object);
395
+ const symbols = Object.getOwnPropertySymbols(object);
396
+ const isPlainObject = gPO(object) === Object.prototype || object.constructor === Object;
397
+ const protoTag = object instanceof Object ? "" : "null prototype";
398
+ let stringTag;
399
+ if (!isPlainObject && Symbol.toStringTag in object) {
400
+ stringTag = object[Symbol.toStringTag];
401
+ } else {
402
+ stringTag = protoTag ? "Object" : "";
635
403
  }
636
- }
637
- const checkEscapeSequence = (chars, index) => {
638
- if (!ESCAPES.has(chars[index])) {
639
- return { isInsideEscape: false, isInsideLinkEscape: false };
404
+ const tag = stringTag || protoTag ? `[${[stringTag, protoTag].filter(Boolean).join(": ")}] ` : "";
405
+ if (properties.length === 0 && symbols.length === 0) {
406
+ return `${tag}{}`;
640
407
  }
641
- const isInsideEscape = true;
642
- const possibleLink = chars.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join("");
643
- const isInsideLinkEscape = possibleLink === ANSI_ESCAPE_LINK;
644
- return { isInsideEscape, isInsideLinkEscape };
408
+ options.truncate -= 4;
409
+ const propertyContents = inspectList(
410
+ properties.map((key) => [key, object[key]]),
411
+ object,
412
+ options,
413
+ inspect2,
414
+ inspectProperty
415
+ );
416
+ const symbolContents = inspectList(
417
+ symbols.map((key) => [key, object[key]]),
418
+ object,
419
+ options,
420
+ inspect2,
421
+ inspectProperty
422
+ );
423
+ let separator = "";
424
+ if (propertyContents && symbolContents) {
425
+ separator = ", ";
426
+ }
427
+ if (indent) {
428
+ return `${tag}{${indentedJoin(propertyContents + separator + symbolContents, indent)}}`;
429
+ }
430
+ return `${tag}{ ${propertyContents}${separator}${symbolContents} }`;
645
431
  };
646
- const processAnsiString = (string, options = {}) => {
647
- const stateTracker = new AnsiStateTracker();
648
- let currentText = "";
649
- let isInsideEscape = false;
650
- let escapeBuffer = "";
651
- let currentUrl = "";
652
- let isInHyperlink = false;
653
- const chars = [...string];
654
- for (let index = 0; index < chars.length; index++) {
655
- const character = chars[index];
656
- if (character && ESCAPES.has(character)) {
657
- if (currentText) {
658
- const width2 = options.getWidth?.(currentText) ?? 0;
659
- const segment2 = {
660
- isEscapeSequence: false,
661
- isGrapheme: true,
662
- text: currentText,
663
- width: width2
664
- };
665
- if (isInHyperlink) {
666
- segment2.isHyperlink = true;
667
- segment2.hyperlinkUrl = currentUrl;
668
- }
669
- if (options.onSegment?.(segment2, stateTracker) === false) {
670
- return;
671
- }
672
- currentText = "";
673
- }
674
- isInsideEscape = true;
675
- escapeBuffer = character;
676
- const escapeInfo = checkEscapeSequence(chars, index);
677
- const { isInsideLinkEscape } = escapeInfo;
678
- if (isInsideLinkEscape) {
679
- let urlEnd = index + 1;
680
- currentUrl = "";
681
- while (urlEnd < chars.length) {
682
- const nextChar = chars[urlEnd];
683
- if (nextChar === ANSI_ESCAPE_BELL) {
684
- break;
685
- }
686
- currentUrl += nextChar;
687
- urlEnd += 1;
688
- }
689
- currentUrl = currentUrl.slice(4);
690
- const segment2 = {
691
- hyperlinkUrl: currentUrl,
692
- isEscapeSequence: true,
693
- isGrapheme: false,
694
- isHyperlink: true,
695
- isHyperlinkStart: true,
696
- width: 0
697
- };
698
- if (options.onSegment?.(segment2, stateTracker) === false) {
699
- return;
700
- }
701
- index = urlEnd;
702
- isInHyperlink = true;
703
- isInsideEscape = false;
704
- escapeBuffer = "";
705
- continue;
706
- }
707
- if (index + 1 < chars.length && chars[index + 1] === "\\" && isInHyperlink) {
708
- const segment2 = {
709
- isEscapeSequence: true,
710
- isGrapheme: false,
711
- isHyperlink: true,
712
- isHyperlinkEnd: true,
713
- width: 0
714
- };
715
- if (options.onSegment?.(segment2, stateTracker) === false) {
716
- return;
717
- }
718
- isInHyperlink = false;
719
- currentUrl = "";
720
- index += 1;
721
- isInsideEscape = false;
722
- escapeBuffer = "";
723
- continue;
724
- }
725
- }
726
- if (isInsideEscape) {
727
- if (escapeBuffer !== character) {
728
- escapeBuffer += character;
729
- }
730
- if (character === ANSI_SGR_TERMINATOR) {
731
- isInsideEscape = false;
732
- stateTracker.processEscape(escapeBuffer);
733
- const segment2 = {
734
- isEscapeSequence: true,
735
- isGrapheme: false,
736
- text: escapeBuffer,
737
- width: 0
738
- };
739
- if (options.onSegment?.(segment2, stateTracker) === false) {
740
- return;
741
- }
742
- escapeBuffer = "";
743
- }
744
- continue;
745
- }
746
- currentText += character;
747
- const width = options.getWidth?.(currentText) ?? 0;
748
- const segment = {
749
- isEscapeSequence: false,
750
- isGrapheme: true,
751
- text: currentText,
752
- width
753
- };
754
- if (isInHyperlink) {
755
- segment.isHyperlink = true;
756
- segment.hyperlinkUrl = currentUrl;
757
- }
758
- if (options.onSegment?.(segment, stateTracker) === false) {
759
- return;
760
- }
761
- currentText = "";
432
+ const inspectClass = (value, options, inspect2, indent) => {
433
+ let name = "";
434
+ name = name || value.constructor.name;
435
+ if (!name || name === "_class") {
436
+ name = "<Anonymous Class>";
762
437
  }
763
- if (currentText) {
764
- const width = options.getWidth?.(currentText) ?? 0;
765
- const segment = {
766
- isEscapeSequence: false,
767
- isGrapheme: true,
768
- text: currentText,
769
- width
770
- };
771
- if (isInHyperlink) {
772
- segment.isHyperlink = true;
773
- segment.hyperlinkUrl = currentUrl;
774
- }
775
- options.onSegment?.(segment, stateTracker);
438
+ options.truncate -= name.length;
439
+ return `${name} ${inspectObject$1(value, options, inspect2, indent)}`;
440
+ };
441
+ const inspectDate = (dateObject, options) => {
442
+ const stringRepresentation = dateObject.toJSON();
443
+ if (stringRepresentation === null) {
444
+ return "Invalid Date";
776
445
  }
777
- if (escapeBuffer) {
778
- const segment = {
779
- isEscapeSequence: true,
780
- isGrapheme: false,
781
- text: escapeBuffer,
782
- width: 0
783
- };
784
- options.onSegment?.(segment, stateTracker);
446
+ const split = stringRepresentation.split("T");
447
+ const date = split[0];
448
+ return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date");
449
+ };
450
+ const errorKeys = /* @__PURE__ */ new Set(["column", "columnNumber", "description", "fileName", "line", "lineNumber", "message", "name", "number", "stack"]);
451
+ const inspectObject = (error, options, inspect2) => {
452
+ const properties = Object.getOwnPropertyNames(error).filter((key) => !errorKeys.has(key));
453
+ const { name } = error;
454
+ options.truncate -= name.length;
455
+ let message = "";
456
+ if (typeof error.message === "string") {
457
+ message = truncate(error.message, options.truncate);
458
+ } else {
459
+ properties.unshift("message");
785
460
  }
461
+ message = message ? `: ${message}` : "";
462
+ options.truncate -= message.length + 5;
463
+ const propertyContents = inspectList(
464
+ properties.map((key) => [key, error[key]]),
465
+ error,
466
+ options,
467
+ inspect2,
468
+ inspectProperty
469
+ );
470
+ return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
786
471
  };
787
- const wrapAnsiCode = (code) => {
788
- const escapeChar = ESCAPES.values().next().value;
789
- return `${escapeChar}${ANSI_CSI}${String(code)}${ANSI_SGR_TERMINATOR}`;
472
+ const inspectFunction = (function_, options) => {
473
+ const functionType = function_[Symbol.toStringTag] || "Function";
474
+ const source = function_.toString();
475
+ if (source.length < options.truncate - 12) {
476
+ return options.stylize(`[${functionType}: ${source}]`, "special");
477
+ }
478
+ const { name } = function_;
479
+ if (!name) {
480
+ return options.stylize(`[${functionType}]`, "special");
481
+ }
482
+ return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special");
790
483
  };
791
- const wrapAnsiHyperlink = (url) => {
792
- const escapeChar = ESCAPES.values().next().value;
793
- return `${escapeChar}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
484
+ const inspectMapEntry = ([key, value], object, options, inspect2) => {
485
+ options.truncate -= 4;
486
+ key = inspect2(key, object, options);
487
+ options.truncate -= key.length;
488
+ return `${key} => ${inspect2(value, object, options)}`;
794
489
  };
795
- const preserveAnsi = (rawLines) => {
796
- if (rawLines.length === 0) {
797
- return "";
490
+ const inspectMap = (map, options, inspect2, indent) => {
491
+ if (map.size <= 0) {
492
+ return "Map (0) {}";
798
493
  }
799
- if (rawLines.length === 1) {
800
- return rawLines[0];
494
+ options.truncate -= 7;
495
+ let returnValue = inspectList([...map.entries()], map, options, inspect2, inspectMapEntry);
496
+ if (indent) {
497
+ returnValue = indentedJoin(returnValue, indent);
801
498
  }
802
- let returnValue = "";
803
- let escapeCode;
804
- let escapeUrl;
805
- const preString = rawLines.join("\n");
806
- const pre = [...preString];
807
- let preStringIndex = 0;
808
- for (const [index, character] of pre.entries()) {
809
- returnValue += character;
810
- if (ESCAPES.has(character)) {
811
- const match = RE_ESCAPE_PATTERN.exec(preString.slice(preStringIndex));
812
- const groups = match?.groups ?? {};
813
- if (groups.code !== void 0) {
814
- const code2 = Number.parseFloat(groups.code);
815
- escapeCode = code2 === END_CODE ? void 0 : code2;
816
- } else if (groups.uri !== void 0) {
817
- escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
818
- }
819
- }
820
- const code = ANSI_RESET_CODES.get(Number(escapeCode));
821
- if (pre[index + 1] === "\n") {
822
- if (escapeUrl) {
823
- returnValue += wrapAnsiHyperlink("");
824
- }
825
- if (escapeCode && code) {
826
- returnValue += wrapAnsiCode(code);
827
- }
828
- } else if (character === "\n") {
829
- if (escapeCode && code) {
830
- returnValue += wrapAnsiCode(escapeCode);
831
- }
832
- if (escapeUrl) {
833
- returnValue += wrapAnsiHyperlink(escapeUrl);
834
- }
835
- }
836
- preStringIndex += character.length;
499
+ return `Map (${String(map.size)}) {${indent ? "" : " "}${returnValue}${indent ? "" : " "}}`;
500
+ };
501
+ function inspectNumber(number, options) {
502
+ if (Number.isNaN(number)) {
503
+ return options.stylize("NaN", "number");
837
504
  }
838
- return returnValue;
505
+ if (number === Number.POSITIVE_INFINITY) {
506
+ return options.stylize("Infinity", "number");
507
+ }
508
+ if (number === Number.NEGATIVE_INFINITY) {
509
+ return options.stylize("-Infinity", "number");
510
+ }
511
+ if (number === 0) {
512
+ return options.stylize(1 / number === Number.POSITIVE_INFINITY ? "+0" : "-0", "number");
513
+ }
514
+ return options.stylize(truncate(options.numericSeparator ? addNumericSeparator(number, number.toString()) : number.toString(), options.truncate), "number");
515
+ }
516
+ const getPromiseValue = () => "Promise{…}";
517
+ const inspectRegExp = (regExp, options) => {
518
+ const sourceLength = options.truncate - (2 + regExp.flags.length);
519
+ return options.stylize(`/${truncate(regExp.source, sourceLength)}/${regExp.flags}`, "regexp");
839
520
  };
840
- const RE_SPLIT_WHITESPACE = /(?=\s)|(?<=\s)/;
841
- const RE_WHITESPACE_ONLY = /^\s+$/;
842
- const resetAnsiAtLineBreak = (currentLine) => {
843
- if (!currentLine.includes("\x1B")) {
844
- return currentLine;
521
+ const inspectSet = (set, options, inspect2, indent) => {
522
+ if (set.size === 0) {
523
+ return "Set (0) {}";
845
524
  }
846
- let result = currentLine;
847
- if (currentLine.includes("\x1B[30m")) {
848
- result += "\x1B[39m";
525
+ options.truncate -= 7;
526
+ let returnValue = inspectList([...set], set, options, inspect2);
527
+ if (indent) {
528
+ returnValue = indentedJoin(returnValue, indent);
849
529
  }
850
- if (currentLine.includes("\x1B[42m")) {
851
- result += "\x1B[49m";
530
+ return `Set (${String(set.size)}) {${indent ? "" : " "}${returnValue}${indent ? "" : " "}}`;
531
+ };
532
+ const wrapQuotes = (string_, options) => {
533
+ const quoteChar = options.quoteStyle === "double" ? '"' : "'";
534
+ if (options.quoteStyle === "double") {
535
+ string_ = string_.replaceAll('"', '"');
852
536
  }
853
- return result;
537
+ return quoteChar + string_ + quoteChar;
854
538
  };
855
- const stringVisibleTrimSpacesRight = (string) => {
856
- const words = string.split(" ");
857
- let last = words.length;
858
- while (last > 0 && getStringWidth(words[last - 1]) === 0) {
859
- last--;
539
+ const stringEscapeChars = new RegExp(
540
+ String.raw`['\0-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5` + String.raw`\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]`,
541
+ "g"
542
+ );
543
+ const escapeCharacters = {
544
+ " ": String.raw`\t`,
545
+ "\n": String.raw`\n`,
546
+ "\f": String.raw`\f`,
547
+ "\r": String.raw`\r`,
548
+ "\b": String.raw`\b`,
549
+ "'": String.raw`\'`,
550
+ "\\": "\\\\"
551
+ };
552
+ const hex = 16;
553
+ const escape = (char) => escapeCharacters[char] || String.raw`\u${`0000${char.codePointAt(0).toString(hex)}`.slice(-4)}`;
554
+ const inspectString = (string_, options) => {
555
+ if (stringEscapeChars.test(string_)) {
556
+ string_ = string_.replaceAll(stringEscapeChars, escape);
860
557
  }
861
- if (last === words.length) {
862
- return string;
558
+ return options.stylize(wrapQuotes(truncate(string_, options.truncate - 2), options), "string");
559
+ };
560
+ const inspectSymbol = (value) => {
561
+ if ("description" in Symbol.prototype) {
562
+ return value.description ? `Symbol(${value.description})` : "Symbol()";
863
563
  }
864
- return words.slice(0, last).join(" ") + words.slice(last).join("");
564
+ return value.toString();
865
565
  };
866
- const wrapWithBreakAtWidth = (string, width, trim) => {
867
- if (string.length === 0) {
868
- return [""];
566
+ const getArrayName = (array) => {
567
+ if (typeof Buffer === "function" && array instanceof Buffer) {
568
+ return "Buffer";
869
569
  }
870
- if (width <= 0) {
871
- return [string];
570
+ return array[Symbol.toStringTag];
571
+ };
572
+ const inspectTypedArray = (array, options, inspect2) => {
573
+ const name = getArrayName(array);
574
+ options.truncate -= name.length + 4;
575
+ const nonIndexProperties = Object.keys(array).slice(array.length);
576
+ if (array.length === 0 && nonIndexProperties.length === 0) {
577
+ return `${name}[]`;
872
578
  }
873
- const rows = [];
874
- const ansiTracker = new AnsiStateTracker();
875
- let currentLine = "";
876
- let currentWidth = 0;
877
- let isInsideEscape = false;
878
- let isInsideLinkEscape = false;
879
- let escapeBuffer = "";
880
- let index = 0;
881
- while (index < string.length) {
882
- const char = string[index];
883
- if (ESCAPES.has(char)) {
884
- isInsideEscape = true;
885
- escapeBuffer = char;
886
- currentLine += char;
887
- const escapeInfo = checkEscapeSequence([...string], index);
888
- isInsideLinkEscape = escapeInfo.isInsideLinkEscape;
889
- index += 1;
890
- continue;
891
- }
892
- if (isInsideEscape) {
893
- escapeBuffer += char;
894
- currentLine += char;
895
- if (isInsideLinkEscape) {
896
- if (char === ANSI_ESCAPE_BELL) {
897
- isInsideEscape = isInsideLinkEscape = false;
898
- }
899
- } else if (char === ANSI_SGR_TERMINATOR) {
900
- isInsideEscape = false;
901
- ansiTracker.processEscape(escapeBuffer);
902
- }
903
- index += 1;
904
- continue;
905
- }
906
- const charWidth = getStringWidth(char);
907
- const isSpace = char === " ";
908
- if (charWidth === 0) {
909
- currentLine += char;
910
- index += 1;
911
- continue;
912
- }
913
- if (currentWidth + charWidth > width) {
914
- if (currentLine) {
915
- rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
916
- }
917
- currentLine = ansiTracker.getStartEscapesForAllActiveAttributes();
918
- currentWidth = getStringWidth(currentLine);
919
- if (isSpace && trim) {
920
- while (index < string.length && string[index] === " ") {
921
- index += 1;
922
- }
923
- continue;
924
- }
925
- }
926
- currentLine += char;
927
- currentWidth += charWidth;
928
- if (currentWidth === width && index < string.length - 1) {
929
- rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
930
- currentLine = ansiTracker.getStartEscapesForAllActiveAttributes();
931
- currentWidth = getStringWidth(currentLine);
932
- if (index + 1 < string.length && string[index + 1] === " " && trim) {
933
- index += 1;
934
- while (index < string.length && string[index] === " ") {
935
- index += 1;
936
- }
937
- continue;
938
- }
579
+ let output = "";
580
+ for (let index = 0; index < array.length; index++) {
581
+ const string = `${options.stylize(truncate(array[index], options.truncate), "number")}${index === array.length - 1 ? "" : ", "}`;
582
+ options.truncate -= string.length;
583
+ if (array[index] !== array.length && options.truncate <= 3) {
584
+ output += `${TRUNCATOR}(${String(array.length - array[index] + 1)})`;
585
+ break;
939
586
  }
940
- index += 1;
587
+ output += string;
941
588
  }
942
- if (currentLine) {
943
- rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
589
+ let propertyContents = "";
590
+ if (nonIndexProperties.length > 0) {
591
+ propertyContents = inspectList(
592
+ nonIndexProperties.map((key) => [key, array[key]]),
593
+ array,
594
+ options,
595
+ inspect2,
596
+ inspectProperty
597
+ );
944
598
  }
945
- return trim ? rows.map((element) => stringVisibleTrimSpacesRight(element)) : rows;
599
+ return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
946
600
  };
947
- const wrapCharByChar = (string, width, trim) => {
948
- if (string.length === 0) {
949
- return [];
601
+ const constructorMap = /* @__PURE__ */ new WeakMap();
602
+ const stringTagMap = {};
603
+ const baseTypesMap = {
604
+ Arguments: inspectArguments,
605
+ Array: inspectArray,
606
+ ArrayBuffer: () => "",
607
+ BigInt: inspectBigInt,
608
+ bigint: inspectBigInt,
609
+ Boolean: (value, options) => options.stylize(String(value), "boolean"),
610
+ boolean: (value, options) => options.stylize(String(value), "boolean"),
611
+ DataView: () => "",
612
+ Date: inspectDate,
613
+ Error: inspectObject,
614
+ Float32Array: inspectTypedArray,
615
+ Float64Array: inspectTypedArray,
616
+ Function: inspectFunction,
617
+ function: inspectFunction,
618
+ Generator: () => "",
619
+ HTMLCollection: inspectNodeCollection,
620
+ Int8Array: inspectTypedArray,
621
+ Int16Array: inspectTypedArray,
622
+ Int32Array: inspectTypedArray,
623
+ Map: inspectMap,
624
+ NodeList: inspectNodeCollection,
625
+ null: (_value, options) => options.stylize("null", "null"),
626
+ Number: inspectNumber,
627
+ number: inspectNumber,
628
+ Promise: getPromiseValue,
629
+ RegExp: inspectRegExp,
630
+ Set: inspectSet,
631
+ String: inspectString,
632
+ string: inspectString,
633
+ // A Symbol polyfill will return `Symbol` not `symbol` from typedetect
634
+ Symbol: inspectSymbol,
635
+ symbol: inspectSymbol,
636
+ Uint8Array: inspectTypedArray,
637
+ Uint8ClampedArray: inspectTypedArray,
638
+ Uint16Array: inspectTypedArray,
639
+ Uint32Array: inspectTypedArray,
640
+ undefined: (_value, options) => options.stylize("undefined", "undefined"),
641
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
642
+ WeakMap: (_value, options) => options.stylize("WeakMap{…}", "special"),
643
+ // WeakSet, WeakMap are totally opaque to us
644
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
645
+ WeakSet: (_value, options) => options.stylize("WeakSet{…}", "special")
646
+ };
647
+ const nodeInspectCustomSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
648
+ const inspectCustom = (value, options, type, depth) => {
649
+ if (!("window" in globalThis) && typeof value[nodeInspectCustomSymbol] === "function") {
650
+ return value[nodeInspectCustomSymbol](depth, options);
950
651
  }
951
- const inputToProcess = trim ? string.trim() : string;
952
- if (inputToProcess.length === 0) {
953
- return [];
652
+ if ("inspect" in value && typeof value.inspect === "function") {
653
+ return value.inspect(depth, options);
954
654
  }
955
- const rows = [];
956
- let currentLine = "";
957
- let currentWidth = 0;
958
- processAnsiString(inputToProcess, {
959
- getWidth: getStringWidth,
960
- // eslint-disable-next-line sonarjs/cognitive-complexity,sonarjs/no-invariant-returns
961
- onSegment: (segment, stateTracker) => {
962
- const segText = segment.text ?? "";
963
- if (segment.isEscapeSequence) {
964
- currentLine += segText;
965
- } else {
966
- const isSpace = segText === " ";
967
- if (segment.width === 0) {
968
- currentLine += segText;
969
- return true;
970
- }
971
- if (currentWidth + segment.width > width) {
972
- if (currentLine) {
973
- rows.push(currentLine);
974
- }
975
- currentLine = stateTracker.getStartEscapesForAllActiveAttributes();
976
- currentWidth = 0;
977
- if (isSpace) {
978
- if (trim) {
979
- return true;
980
- }
981
- rows.push(stateTracker.getStartEscapesForAllActiveAttributes() + segText);
982
- return true;
983
- }
984
- }
985
- currentLine += segText;
986
- currentWidth += segment.width;
987
- }
988
- return true;
989
- }
990
- });
991
- if (currentLine) {
992
- rows.push(currentLine);
655
+ if ("constructor" in value && constructorMap.has(value.constructor)) {
656
+ return constructorMap.get(value.constructor)?.(value, options) ?? "unknown";
993
657
  }
994
- return trim ? rows.map((row) => stringVisibleTrimSpacesRight(row)) : rows;
658
+ const tagInspector = stringTagMap[type];
659
+ if (tagInspector) {
660
+ return tagInspector(value, options);
661
+ }
662
+ return "";
995
663
  };
996
- const wrapWithWordBoundaries = (string, width, trim) => {
997
- if (string.length === 0) {
998
- return [];
664
+ const internalInspect = (value, options, depth, seen) => {
665
+ if (seen.includes(value)) {
666
+ return "[Circular]";
999
667
  }
1000
- const inputToProcess = trim ? string.trim() : string;
1001
- if (inputToProcess.length === 0) {
1002
- return [];
668
+ if (depth >= options.depth && options.depth > 0 && typeof value === "object") {
669
+ return Array.isArray(value) ? "[Array]" : "[Object]";
1003
670
  }
1004
- const tokens = inputToProcess.split(RE_SPLIT_WHITESPACE);
1005
- const rows = [];
1006
- let currentLine = "";
1007
- let currentWidth = 0;
1008
- let index = 0;
1009
- while (index < tokens.length) {
1010
- const token = tokens[index];
1011
- const isSpace = RE_WHITESPACE_ONLY.test(token);
1012
- const tokenVisibleWidth = getStringWidth(token);
1013
- if (token.length === 0) {
1014
- index += 1;
1015
- continue;
1016
- }
1017
- if (trim && isSpace && currentWidth === 0) {
1018
- index += 1;
1019
- continue;
671
+ const inspect2 = (object, from, options2) => {
672
+ if (from) {
673
+ seen = [...seen, from];
1020
674
  }
1021
- if (currentWidth + tokenVisibleWidth > width && currentWidth > 0) {
1022
- if (trim) {
1023
- rows.push(stringVisibleTrimSpacesRight(currentLine));
1024
- } else {
1025
- rows.push(currentLine);
675
+ return internalInspect(object, options2, depth + 1, seen);
676
+ };
677
+ const indent = options.indent ? getIndent(options.indent, depth) : void 0;
678
+ let type = value === null ? "null" : typeof value;
679
+ if (type === "object") {
680
+ type = Object.prototype.toString.call(value).slice(8, -1);
681
+ }
682
+ const baseInspector = baseTypesMap[type];
683
+ if (baseInspector !== void 0) {
684
+ return baseInspector(value, options, inspect2, indent);
685
+ }
686
+ if (options.customInspect && value) {
687
+ const output = inspectCustom(value, options, type, options.depth - depth);
688
+ if (output) {
689
+ if (typeof output === "string") {
690
+ return output;
1026
691
  }
1027
- currentLine = "";
1028
- currentWidth = 0;
1029
- continue;
692
+ return inspect2(output, value, options);
1030
693
  }
1031
- currentLine += token;
1032
- currentWidth += tokenVisibleWidth;
1033
- index += 1;
1034
694
  }
1035
- if (currentLine) {
1036
- if (trim) {
1037
- rows.push(stringVisibleTrimSpacesRight(currentLine));
1038
- } else {
1039
- rows.push(currentLine);
1040
- }
1041
- }
1042
- return rows;
1043
- };
1044
- const wrapAndBreakWords = (string, width, trim) => {
1045
- if (string.length === 0) {
1046
- return [];
695
+ const proto = value ? Object.getPrototypeOf(value) : false;
696
+ if (proto === Object.prototype || proto === null) {
697
+ return inspectObject$1(value, options, inspect2, indent);
1047
698
  }
1048
- const inputToProcess = trim ? string.trim() : string;
1049
- if (inputToProcess.length === 0) {
1050
- return [];
699
+ if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) {
700
+ return inspectHTMLElement(value, value, options, inspect2);
1051
701
  }
1052
- const tokens = inputToProcess.split(RE_SPLIT_WHITESPACE);
1053
- const rows = [];
1054
- let currentLine = "";
1055
- let currentWidth = 0;
1056
- let index = 0;
1057
- while (index < tokens.length) {
1058
- const token = tokens[index];
1059
- const isSpace = RE_WHITESPACE_ONLY.test(token);
1060
- const tokenVisibleWidth = getStringWidth(token);
1061
- if (token.length === 0) {
1062
- index += 1;
1063
- continue;
1064
- }
1065
- if (trim && isSpace && currentWidth === 0) {
1066
- index += 1;
1067
- continue;
1068
- }
1069
- if (tokenVisibleWidth > width) {
1070
- if (currentLine) {
1071
- rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
1072
- }
1073
- const brokenLines = wrapWithBreakAtWidth(token, width, trim);
1074
- if (brokenLines.length > 0) {
1075
- for (let brokenLineIndex = 0; brokenLineIndex < brokenLines.length - 1; brokenLineIndex += 1) {
1076
- rows.push(brokenLines[brokenLineIndex]);
1077
- }
1078
- currentLine = brokenLines.at(-1);
1079
- currentWidth = getStringWidth(currentLine);
1080
- } else {
1081
- currentLine = "";
1082
- currentWidth = 0;
1083
- }
1084
- index += 1;
1085
- continue;
1086
- }
1087
- if (currentWidth + tokenVisibleWidth > width && currentWidth > 0) {
1088
- rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
1089
- currentLine = "";
1090
- currentWidth = 0;
1091
- if (trim && isSpace) {
1092
- index += 1;
1093
- continue;
1094
- }
702
+ if ("constructor" in value) {
703
+ if (value.constructor !== Object) {
704
+ return inspectClass(value, options, inspect2, indent);
1095
705
  }
1096
- currentLine += token;
1097
- currentWidth += tokenVisibleWidth;
1098
- index += 1;
706
+ return inspectObject$1(value, options, inspect2, indent);
1099
707
  }
1100
- if (currentLine) {
1101
- rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
708
+ if (value === Object(value)) {
709
+ return inspectObject$1(value, options, inspect2, indent);
1102
710
  }
1103
- return rows;
1104
- };
1105
- const WrapMode = {
1106
- /**
1107
- * Breaks words at character boundaries to fit the width
1108
- */
1109
- BREAK_AT_CHARACTERS: "BREAK_AT_CHARACTERS",
1110
- /**
1111
- * Breaks lines at word boundaries. If a word is longer than the width, it will be broken.
1112
- */
1113
- BREAK_WORDS: "BREAK_WORDS",
1114
- /**
1115
- * Preserves word boundaries, words are kept intact even if they exceed width
1116
- */
1117
- PRESERVE_WORDS: "PRESERVE_WORDS",
1118
- /**
1119
- * Enforces strict adherence to the width limit by breaking at exact width
1120
- */
1121
- STRICT_WIDTH: "STRICT_WIDTH"
711
+ return options.stylize(String(value), type);
1122
712
  };
1123
- const wordWrap = (string, options = {}) => {
1124
- const { removeZeroWidthCharacters = true, trim = true, width = 80, wrapMode = WrapMode.PRESERVE_WORDS } = options;
1125
- if (trim && string.trim() === "") {
1126
- return "";
1127
- }
1128
- let normalizedString = string.normalize("NFC").replaceAll("\r\n", "\n");
1129
- if (removeZeroWidthCharacters) {
1130
- normalizedString = normalizedString.replaceAll(RE_ZERO_WIDTH, "");
713
+ const inspect = (value, options_ = {}) => {
714
+ const options = {
715
+ breakLength: Number.POSITIVE_INFINITY,
716
+ customInspect: true,
717
+ depth: 5,
718
+ indent: void 0,
719
+ maxArrayLength: Number.POSITIVE_INFINITY,
720
+ numericSeparator: true,
721
+ quoteStyle: "single",
722
+ showHidden: false,
723
+ showProxy: false,
724
+ stylize: (s) => s,
725
+ truncate: Number.POSITIVE_INFINITY,
726
+ ...options_
727
+ };
728
+ if (options.indent !== void 0 && options.indent !== " " && !(Number.parseInt(options.indent, 10) === options.indent && options.indent > 0)) {
729
+ throw new TypeError('option "indent" must be "\\t", an integer > 0, or `undefined`');
1131
730
  }
1132
- const result = normalizedString.split("\n").map((line) => {
1133
- if (trim && line.trim() === "") {
1134
- return "";
1135
- }
1136
- let wrappedLines;
1137
- switch (wrapMode) {
1138
- case WrapMode.BREAK_AT_CHARACTERS: {
1139
- wrappedLines = wrapCharByChar(line, width, trim);
1140
- break;
1141
- }
1142
- case WrapMode.BREAK_WORDS: {
1143
- wrappedLines = wrapAndBreakWords(line, width, trim);
1144
- break;
1145
- }
1146
- case WrapMode.STRICT_WIDTH: {
1147
- wrappedLines = wrapWithBreakAtWidth(line, width, trim);
1148
- break;
1149
- }
1150
- default: {
1151
- wrappedLines = wrapWithWordBoundaries(line, width, trim);
1152
- }
1153
- }
1154
- return preserveAnsi(wrappedLines);
1155
- });
1156
- return result.join("\n");
731
+ return internalInspect(value, options, 0, []);
1157
732
  };
1158
733
 
1159
- const defaultColumns = 80;
1160
- const defaultRows = 24;
1161
- const exec = (command, arguments_, { shell, env } = {}) => execFileSync(command, arguments_, {
1162
- encoding: "utf8",
1163
- stdio: ["ignore", "pipe", "ignore"],
1164
- timeout: 500,
1165
- shell,
1166
- env
1167
- }).trim();
1168
- const create = (columns, rows) => ({
1169
- columns: Number.parseInt(columns, 10),
1170
- rows: Number.parseInt(rows, 10)
1171
- });
1172
- const createIfNotDefault = (maybeColumns, maybeRows) => {
1173
- const { columns, rows } = create(maybeColumns, maybeRows);
1174
- if (Number.isNaN(columns) || Number.isNaN(rows)) {
1175
- return;
1176
- }
1177
- if (columns === defaultColumns && rows === defaultRows) {
1178
- return;
1179
- }
1180
- return { columns, rows };
734
+ const writeStream = (data, stream) => {
735
+ const write = stream["__write"] ?? stream.write.bind(stream);
736
+ return write.call(stream, data);
1181
737
  };
1182
- const isForegroundProcess = () => {
1183
- if (process$2.platform !== "linux") {
1184
- return true;
1185
- }
1186
- try {
1187
- const statContents = fs.readFileSync("/proc/self/stat", "utf8");
1188
- const closingParenthesisIndex = statContents.lastIndexOf(") ");
1189
- if (closingParenthesisIndex === -1) {
1190
- return false;
1191
- }
1192
- const statFields = statContents.slice(closingParenthesisIndex + 2).trim().split(/\s+/);
1193
- const processGroupId = Number.parseInt(statFields[2], 10);
1194
- const foregroundProcessGroupId = Number.parseInt(statFields[5], 10);
1195
- if (Number.isNaN(processGroupId) || Number.isNaN(foregroundProcessGroupId)) {
1196
- return false;
738
+
739
+ const normalizeLF = (code) => code.replaceAll(/\r\n|\r(?!\n)|\n/gu, "\n");
740
+ const rawProcess = globalThis.process ?? /* @__PURE__ */ Object.create(null);
741
+ const processShims = {
742
+ versions: {}
743
+ };
744
+ const process$1 = /* @__PURE__ */ new Proxy(rawProcess, {
745
+ get(target, property) {
746
+ if (property in target) {
747
+ return target[property];
1197
748
  }
1198
- if (foregroundProcessGroupId <= 0) {
1199
- return false;
749
+ if (property in processShims) {
750
+ return processShims[property];
1200
751
  }
1201
- return processGroupId === foregroundProcessGroupId;
1202
- } catch {
1203
- return false;
1204
- }
1205
- };
1206
- function terminalSize() {
1207
- const { env, stdout, stderr } = process$2;
1208
- if (stdout?.columns && stdout?.rows) {
1209
- return create(stdout.columns, stdout.rows);
1210
- }
1211
- if (stderr?.columns && stderr?.rows) {
1212
- return create(stderr.columns, stderr.rows);
1213
- }
1214
- if (env.COLUMNS && env.LINES) {
1215
- return create(env.COLUMNS, env.LINES);
752
+ return void 0;
1216
753
  }
1217
- const fallback = {
1218
- columns: defaultColumns,
1219
- rows: defaultRows
754
+ });
755
+ const getMarkerLines = (loc, source, linesAbove, linesBelow) => {
756
+ const startLoc = {
757
+ column: 0,
758
+ // @ts-expect-error Can be overwritten
759
+ line: -1,
760
+ ...loc.start
1220
761
  };
1221
- if (process$2.platform === "win32") {
1222
- return tput() ?? fallback;
1223
- }
1224
- if (process$2.platform === "darwin") {
1225
- return devTty() ?? tput() ?? fallback;
1226
- }
1227
- return devTty() ?? tput() ?? resize() ?? fallback;
1228
- }
1229
- const devTty = () => {
1230
- try {
1231
- const flags = process$2.platform === "darwin" ? fs.constants.O_EVTONLY | fs.constants.O_NONBLOCK : fs.constants.O_NONBLOCK;
1232
- const { columns, rows } = tty.WriteStream(fs.openSync("/dev/tty", flags));
1233
- return { columns, rows };
1234
- } catch {
762
+ const endLoc = {
763
+ ...startLoc,
764
+ ...loc.end
765
+ };
766
+ const startLine = startLoc.line;
767
+ const startColumn = startLoc.column;
768
+ const endLine = endLoc.line;
769
+ const endColumn = endLoc.column;
770
+ let start = Math.max(startLine - (linesAbove + 1), 0);
771
+ let end = Math.min(source.length, endLine + linesBelow);
772
+ if (startLine === -1) {
773
+ start = 0;
1235
774
  }
1236
- };
1237
- const tput = () => {
1238
- try {
1239
- const columns = exec("tput", ["cols"], { env: { TERM: "dumb", ...process$2.env } });
1240
- const rows = exec("tput", ["lines"], { env: { TERM: "dumb", ...process$2.env } });
1241
- if (columns && rows) {
1242
- return createIfNotDefault(columns, rows);
1243
- }
1244
- } catch {
775
+ if (endLine === -1) {
776
+ end = source.length;
1245
777
  }
1246
- };
1247
- const resize = () => {
1248
- try {
1249
- if (!isForegroundProcess()) {
1250
- return;
1251
- }
1252
- const size = exec("resize", ["-u"]).match(/\d+/g);
1253
- if (size.length === 2) {
1254
- return createIfNotDefault(size[0], size[1]);
778
+ const lineDiff = endLine - startLine;
779
+ const markerLines = {};
780
+ if (lineDiff) {
781
+ for (let index = 0; index <= lineDiff; index++) {
782
+ const lineNumber = index + startLine;
783
+ if (!startColumn) {
784
+ markerLines[lineNumber] = true;
785
+ } else if (index === 0) {
786
+ const sourceLength = source[lineNumber - 1]?.length;
787
+ markerLines[lineNumber] = [startColumn, (sourceLength ?? 0) - startColumn + 1];
788
+ } else if (index === lineDiff) {
789
+ markerLines[lineNumber] = [0, endColumn];
790
+ } else {
791
+ const sourceLength = source[lineNumber - index]?.length;
792
+ markerLines[lineNumber] = [0, sourceLength];
793
+ }
1255
794
  }
1256
- } catch {
795
+ } else if (startColumn === endColumn) {
796
+ markerLines[startLine] = startColumn ? [startColumn, 0] : true;
797
+ } else {
798
+ markerLines[startLine] = [startColumn, (endColumn ?? 0) - (startColumn ?? 0)];
1257
799
  }
800
+ return { end, markerLines, start };
1258
801
  };
1259
-
1260
- const EXTENDED_RFC_5424_LOG_LEVELS = {
1261
- alert: 7,
1262
- // Action must be taken immediately. Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
1263
- critical: 6,
1264
- // Critical conditions. Example: Application component unavailable, unexpected exception.
1265
- debug: 1,
1266
- // Detailed debug information.
1267
- emergency: 8,
1268
- // Emergency: system is unusable.
1269
- error: 5,
1270
- // Runtime errors that do not require immediate action but should typically be logged and monitored.
1271
- informational: 2,
1272
- // Interesting events. Examples: User logs in, SQL logs.
1273
- notice: 3,
1274
- // Normal but significant events.
1275
- trace: 2,
1276
- // Trace information.
1277
- warning: 4
1278
- // Exceptional occurrences that are not errors. Examples: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
1279
- };
1280
- const LOG_TYPES = {
1281
- alert: {
1282
- color: "red",
1283
- label: "alert",
1284
- logLevel: "alert"
1285
- },
1286
- await: {
1287
- color: "blue",
1288
- label: "awaiting",
1289
- logLevel: "informational"
1290
- },
1291
- complete: {
1292
- color: "cyan",
1293
- label: "complete",
1294
- logLevel: "informational"
1295
- },
1296
- critical: {
1297
- color: "redBright",
1298
- label: "critical",
1299
- logLevel: "critical"
1300
- },
1301
- debug: {
1302
- color: "gray",
1303
- label: "debug",
1304
- logLevel: "debug"
1305
- },
1306
- emergency: {
1307
- color: "redBright",
1308
- label: "emergency",
1309
- logLevel: "emergency"
1310
- },
1311
- error: {
1312
- color: "red",
1313
- label: "error",
1314
- logLevel: "error"
1315
- },
1316
- info: {
1317
- color: "blueBright",
1318
- label: "info",
1319
- logLevel: "informational"
1320
- },
1321
- log: {
1322
- label: "",
1323
- logLevel: "informational"
1324
- },
1325
- notice: {
1326
- color: "magentaBright",
1327
- label: "notice",
1328
- logLevel: "notice"
1329
- },
1330
- pending: {
1331
- color: "magenta",
1332
- label: "pending",
1333
- logLevel: "informational"
1334
- },
1335
- start: {
1336
- color: "greenBright",
1337
- label: "start",
1338
- logLevel: "informational"
1339
- },
1340
- stop: {
1341
- color: "red",
1342
- label: "stop",
1343
- logLevel: "informational"
1344
- },
1345
- success: {
1346
- color: "green",
1347
- label: "success",
1348
- logLevel: "informational"
1349
- },
1350
- trace: {
1351
- color: "cyanBright",
1352
- label: "trace",
1353
- logLevel: "trace"
1354
- },
1355
- wait: {
1356
- color: "blue",
1357
- label: "waiting",
1358
- logLevel: "informational"
1359
- },
1360
- warn: {
1361
- color: "yellow",
1362
- label: "warning",
1363
- logLevel: "warning"
1364
- },
1365
- warning: {
1366
- color: "yellow",
1367
- label: "warning",
1368
- logLevel: "warning"
1369
- },
1370
- watch: {
1371
- color: "yellowBright",
1372
- label: "watching",
1373
- logLevel: "informational"
802
+ const CODE_FRAME_POINTER = process$1.platform === "win32" && !process$1.env?.WT_SESSION ? ">" : "❯";
803
+ const codeFrame = (source, loc, options) => {
804
+ const config = {
805
+ // grab 2 lines before, and 3 lines after focused line
806
+ linesAbove: 2,
807
+ linesBelow: 3,
808
+ prefix: "",
809
+ showGutter: true,
810
+ tabWidth: 4,
811
+ ...options,
812
+ color: {
813
+ gutter: (value) => value,
814
+ marker: (value) => value,
815
+ message: (value) => value,
816
+ ...options?.color
817
+ }
818
+ };
819
+ const hasColumns = typeof loc.start.column === "number";
820
+ let lines = normalizeLF(source).split("\n");
821
+ if (typeof config.tabWidth === "number") {
822
+ lines = lines.map((ln) => ln.replaceAll(" ", " ".repeat(config.tabWidth)));
1374
823
  }
1375
- };
1376
- const EMPTY_SYMBOL = /* @__PURE__ */ Symbol("EMPTY");
1377
-
1378
- const getLongestLabel = (types) => {
1379
- const labels = Object.keys(types).map((x) => types[x].label ?? "");
1380
- if (labels.length === 0) {
1381
- return "";
824
+ const { end, markerLines, start } = getMarkerLines(loc, lines, config.linesAbove, config.linesBelow);
825
+ const numberMaxWidth = String(end).length;
826
+ const { gutter: colorizeGutter, marker: colorizeMarker, message: colorizeMessage } = config.color;
827
+ let frame = lines.slice(start, end).map((line, index) => {
828
+ const number = start + 1 + index;
829
+ const hasMarker = markerLines[number];
830
+ const paddedNumber = ` ${String(number)}`.slice(-numberMaxWidth);
831
+ const lastMarkerLine = !markerLines[number + 1];
832
+ const gutter = ` ${paddedNumber}${config.showGutter ? " |" : ""}`;
833
+ if (hasMarker) {
834
+ let markerLine = "";
835
+ if (Array.isArray(hasMarker)) {
836
+ const markerSpacing = line.replaceAll(/[^\t]/g, " ").slice(0, Math.max(hasMarker[0] - 1, 0));
837
+ const numberOfMarkers = hasMarker[1] || 1;
838
+ markerLine = [
839
+ "\n ",
840
+ config.prefix + colorizeGutter(gutter.replaceAll(/\d/g, " ")),
841
+ " ",
842
+ markerSpacing,
843
+ colorizeMarker("^").repeat(numberOfMarkers)
844
+ ].join("");
845
+ if (lastMarkerLine && config.message) {
846
+ markerLine += ` ${colorizeMessage(config.message)}`;
847
+ }
848
+ }
849
+ return [config.prefix + colorizeMarker(CODE_FRAME_POINTER), colorizeGutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
850
+ }
851
+ return `${config.prefix} ${colorizeGutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
852
+ }).join("\n");
853
+ if (config.message && !hasColumns) {
854
+ frame = `${config.prefix + " ".repeat(numberMaxWidth + 1) + config.message}
855
+ ${frame}`;
1382
856
  }
1383
- return labels.reduce((x, y) => x.length > y.length ? x : y, "");
857
+ return frame;
1384
858
  };
1385
859
 
1386
- const TRUNCATOR = "…";
1387
- const inspectList = (list, from, options, inspect2, inspectItem, separator = ", ") => {
1388
- const size = list.length;
1389
- if (size === 0) {
1390
- return "";
1391
- }
1392
- let inspect_ = inspect2;
1393
- if (inspectItem !== void 0) {
1394
- inspect_ = inspectItem;
1395
- }
1396
- const originalLength = options.truncate;
1397
- let output = "";
1398
- let peek = "";
1399
- let truncated = "";
1400
- for (let index = 0; index < size; index += 1) {
1401
- const last = index + 1 === list.length;
1402
- const secondToLast = index + 2 === list.length;
1403
- truncated = `${TRUNCATOR}(${String(list.length - index)})`;
1404
- let value = list[index];
1405
- options.truncate = originalLength - output.length - (last ? 0 : separator.length);
1406
- const string = peek || inspect_(value, from, options, inspect2) + (last ? "" : separator);
1407
- const nextLength = output.length + string.length;
1408
- const truncatedLength = nextLength + truncated.length;
1409
- if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
1410
- break;
1411
- }
1412
- if (!last && !secondToLast && truncatedLength > originalLength) {
1413
- break;
1414
- }
1415
- value = list[index + 1];
1416
- const peekSuffix = secondToLast ? "" : separator;
1417
- if (last) {
1418
- peek = "";
1419
- } else {
1420
- peek = inspect_(value, from, options, inspect2) + peekSuffix;
1421
- }
1422
- if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
1423
- break;
1424
- }
1425
- output += string;
1426
- if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
1427
- truncated = `${TRUNCATOR}(${String(list.length - index - 1)})`;
1428
- break;
1429
- }
1430
- truncated = "";
860
+ const debugLog = (message, ...arguments_) => {
861
+ if (process.env.DEBUG && process.env.DEBUG === "true") {
862
+ console.debug(`error:parse-stacktrace: ${message}`, ...arguments_);
1431
863
  }
1432
- return `${output}${truncated}`;
1433
864
  };
1434
- const inspectAttribute = ([key, value], _, options) => {
1435
- options.truncate -= 3;
1436
- if (!value) {
1437
- return options.stylize(String(key), "yellow");
865
+ const UNKNOWN_FUNCTION = "<unknown>";
866
+ const CHROMIUM_REGEX = /^.*?\s*at\s(?:(.+?\)(?:\s\[.+\])?|\(?.*?)\s?\((?:address\sat\s)?)?(?:async\s)?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
867
+ const CHROMIUM_EVAL_REGEX = /\((\S+)\),\s(<[^>]+>)?:(\d+)?:(\d+)?\)?/;
868
+ const CHROMIUM_MAPPED = /(.*?):(\d+):(\d+)(?:\s<-\s.+:\d+:\d+)?/;
869
+ const WINDOWS_EVAL_REGEX = /eval\sat\s(<anonymous>)\s\((.*)\)?:(\d+)?:(\d+)\),\s*<anonymous>?:(\d+)?:(\d+)/;
870
+ const NODE_REGEX = /^\s*in\s(?:([^\\/]+(?:\s\[as\s\S+\])?)\s\(?)?\(at?\s?(.*?):(\d+)(?::(\d+))?\)?\s*$/;
871
+ const NODE_NESTED_REGEX = /in\s(.*)\s\(at\s(.+)\)\sat/;
872
+ const REACT_ANDROID_NATIVE_REGEX = /^(?:.*@)?(.*):(\d+):(\d+)$/;
873
+ const GECKO_REGEX = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. \/=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
874
+ const GECKO_EVAL_REGEX = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
875
+ const FIREFOX_REGEX = /(\S[^\s[]*\[.*\]|.*?)@(.*):(\d+):(\d+)/;
876
+ const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
877
+ const AT_PREFIX_REGEX = /at\s/;
878
+ const CHROMIUM_EVAL_SPLIT_REGEX = /^(\S+):(\d+):(\d+)$|^(\S+):(\d+)$/;
879
+ const TRIM_REGEX = /^\s+|\s+$/g;
880
+ const ERROR_LINE_REGEX = /\S*(?:Error: |AggregateError:)/;
881
+ const ANONYMOUS_FUNCTION_REGEX = /^Anonymous function$/;
882
+ const NODE_LINE_REGEX = /^\s*in\s.*/;
883
+ const CHROMIUM_LINE_REGEX = /^.*?\s*at\s.*/;
884
+ const GECKO_LINE_REGEX = /^.*?\s*@.*|\[native code\]/;
885
+ const extractSafariExtensionDetails = (methodName, url) => {
886
+ const isSafariExtension = methodName.includes("safari-extension");
887
+ const isSafariWebExtension = methodName.includes("safari-web-extension");
888
+ return isSafariExtension || isSafariWebExtension ? [
889
+ methodName.includes("@") ? methodName.split("@")[0] : UNKNOWN_FUNCTION,
890
+ isSafariExtension ? `safari-extension:${url}` : `safari-web-extension:${url}`
891
+ ] : [methodName, url];
892
+ };
893
+ const parseMapped = (trace, maybeMapped) => {
894
+ const match = CHROMIUM_MAPPED.exec(maybeMapped);
895
+ if (match) {
896
+ trace.file = match[1];
897
+ trace.line = +match[2];
898
+ trace.column = +match[3];
1438
899
  }
1439
- return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`;
1440
900
  };
1441
- const inspectNode = (node, inspect2, options) => {
1442
- switch (node.nodeType) {
1443
- case 1: {
1444
- return inspectHTMLElement(node, node, options, inspect2);
1445
- }
1446
- case 3: {
1447
- return inspect2(node.data, inspect2, options);
901
+ const parseNode = (line) => {
902
+ const nestedNode = NODE_NESTED_REGEX.exec(line);
903
+ if (nestedNode) {
904
+ debugLog(`parse nested node error stack line: "${line}"`, `found: ${JSON.stringify(nestedNode)}`);
905
+ const split = nestedNode[2].split(":");
906
+ return {
907
+ column: split[2] ? +split[2] : void 0,
908
+ file: split[0],
909
+ line: split[1] ? +split[1] : void 0,
910
+ methodName: nestedNode[1] ?? UNKNOWN_FUNCTION,
911
+ raw: line,
912
+ type: void 0
913
+ };
914
+ }
915
+ const node = NODE_REGEX.exec(line);
916
+ if (node) {
917
+ debugLog(`parse node error stack line: "${line}"`, `found: ${JSON.stringify(node)}`);
918
+ const trace = {
919
+ column: node[4] ? +node[4] : void 0,
920
+ file: node[2] ? node[2].replace(AT_PREFIX_REGEX, "") : void 0,
921
+ line: node[3] ? +node[3] : void 0,
922
+ methodName: node[1] ?? UNKNOWN_FUNCTION,
923
+ raw: line,
924
+ type: line.startsWith("internal") ? "internal" : void 0
925
+ };
926
+ parseMapped(trace, `${node[2]}:${node[3]}:${node[4]}`);
927
+ return trace;
928
+ }
929
+ return void 0;
930
+ };
931
+ const parseChromium = (line) => {
932
+ const parts = CHROMIUM_REGEX.exec(line);
933
+ if (parts) {
934
+ debugLog(`parse chrome error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
935
+ const isNative = parts[2]?.startsWith("native");
936
+ const isEval = parts[2]?.startsWith("eval") || parts[1]?.startsWith("eval");
937
+ let evalOrigin;
938
+ let windowsParts;
939
+ if (isEval) {
940
+ const subMatch = CHROMIUM_EVAL_REGEX.exec(line);
941
+ if (subMatch) {
942
+ const split = CHROMIUM_EVAL_SPLIT_REGEX.exec(subMatch[1]);
943
+ if (split) {
944
+ parts[2] = split[4] ?? split[1];
945
+ parts[3] = split[5] ?? split[2];
946
+ parts[4] = split[3];
947
+ } else if (subMatch[2]) {
948
+ parts[2] = subMatch[1];
949
+ }
950
+ if (subMatch[2]) {
951
+ evalOrigin = {
952
+ column: subMatch[4] ? +subMatch[4] : void 0,
953
+ file: subMatch[2],
954
+ line: subMatch[3] ? +subMatch[3] : void 0,
955
+ methodName: "eval",
956
+ raw: line,
957
+ type: "eval"
958
+ };
959
+ }
960
+ } else {
961
+ const windowsSubMatch = WINDOWS_EVAL_REGEX.exec(line);
962
+ if (windowsSubMatch) {
963
+ windowsParts = {
964
+ column: windowsSubMatch[4] ? +windowsSubMatch[4] : void 0,
965
+ file: windowsSubMatch[2],
966
+ line: windowsSubMatch[3] ? +windowsSubMatch[3] : void 0
967
+ };
968
+ evalOrigin = {
969
+ column: windowsSubMatch[6] ? +windowsSubMatch[6] : void 0,
970
+ file: windowsSubMatch[1],
971
+ line: windowsSubMatch[5] ? +windowsSubMatch[5] : void 0,
972
+ methodName: "eval",
973
+ raw: windowsSubMatch[0],
974
+ type: "eval"
975
+ };
976
+ }
977
+ }
1448
978
  }
1449
- default: {
1450
- return inspect2(node, inspect2, options);
979
+ const [methodName, file] = extractSafariExtensionDetails(
980
+ // Normalize IE's 'Anonymous function'
981
+ parts[1] ? parts[1].replace(ANONYMOUS_FUNCTION_REGEX, "<anonymous>") : UNKNOWN_FUNCTION,
982
+ parts[2]
983
+ );
984
+ const trace = {
985
+ column: parts[4] ? +parts[4] : void 0,
986
+ evalOrigin,
987
+ file,
988
+ line: parts[3] ? +parts[3] : void 0,
989
+ methodName,
990
+ raw: line,
991
+ // eslint-disable-next-line sonarjs/no-nested-conditional
992
+ type: isEval ? "eval" : isNative ? "native" : void 0
993
+ };
994
+ if (windowsParts) {
995
+ trace.column = windowsParts.column;
996
+ trace.file = windowsParts.file;
997
+ trace.line = windowsParts.line;
998
+ } else {
999
+ parseMapped(trace, `${file}:${parts[3]}:${parts[4]}`);
1451
1000
  }
1001
+ return trace;
1452
1002
  }
1003
+ return void 0;
1453
1004
  };
1454
- const inspectNodeCollection = (collection, options, inspect2, _) => inspectList(collection, collection, options, inspect2, inspectNode, "\n");
1455
- const inspectHTMLElement = (element, object, options, inspect2) => {
1456
- const properties = element.getAttributeNames();
1457
- const name = element.tagName.toLowerCase();
1458
- const head = options.stylize(`<${name}`, "special");
1459
- const headClose = options.stylize(`>`, "special");
1460
- const tail = options.stylize(`</${name}>`, "special");
1461
- options.truncate -= name.length * 2 + 5;
1462
- let propertyContents = "";
1463
- if (properties.length > 0) {
1464
- propertyContents += " ";
1465
- propertyContents += inspectList(
1466
- properties.map((key) => [key, element.getAttribute(key)]),
1467
- object,
1468
- options,
1469
- inspect2,
1470
- inspectAttribute,
1471
- " "
1005
+ const parseGecko = (line, topFrameMeta) => {
1006
+ const parts = GECKO_REGEX.exec(line);
1007
+ if (parts) {
1008
+ debugLog(`parse gecko error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
1009
+ const isEval = parts[3]?.includes(" > eval");
1010
+ const subMatch = isEval && parts[3] && GECKO_EVAL_REGEX.exec(parts[3]);
1011
+ let evalOrigin;
1012
+ if (isEval && subMatch) {
1013
+ parts[3] = subMatch[1];
1014
+ evalOrigin = {
1015
+ column: parts[5] ? +parts[5] : void 0,
1016
+ file: parts[3],
1017
+ line: parts[4] ? +parts[4] : void 0,
1018
+ methodName: "eval",
1019
+ raw: line,
1020
+ type: "eval"
1021
+ };
1022
+ parts[4] = subMatch[2];
1023
+ }
1024
+ const [methodName, file] = extractSafariExtensionDetails(
1025
+ // Normalize IE's 'Anonymous function'
1026
+ parts[1] ? parts[1].replace(ANONYMOUS_FUNCTION_REGEX, "<anonymous>") : UNKNOWN_FUNCTION,
1027
+ parts[3]
1472
1028
  );
1029
+ let column;
1030
+ if ((topFrameMeta?.type === "safari" || !isEval && topFrameMeta?.type === "firefox") && topFrameMeta.column) {
1031
+ column = topFrameMeta.column;
1032
+ } else if (!isEval && parts[5]) {
1033
+ column = +parts[5];
1034
+ }
1035
+ let lineNumber;
1036
+ if ((topFrameMeta?.type === "safari" || !isEval && topFrameMeta?.type === "firefox") && topFrameMeta.line) {
1037
+ lineNumber = topFrameMeta.line;
1038
+ } else if (parts[4]) {
1039
+ lineNumber = +parts[4];
1040
+ }
1041
+ return {
1042
+ column,
1043
+ evalOrigin,
1044
+ file,
1045
+ line: lineNumber,
1046
+ methodName,
1047
+ raw: line,
1048
+ // eslint-disable-next-line sonarjs/no-nested-conditional
1049
+ type: isEval ? "eval" : file.includes("[native code]") ? "native" : void 0
1050
+ };
1473
1051
  }
1474
- options.truncate -= propertyContents.length;
1475
- const { truncate: truncate2 } = options;
1476
- let children = inspectNodeCollection(element.children, options, inspect2);
1477
- if (children && children.length > truncate2) {
1478
- children = `${TRUNCATOR}(${String(element.children.length)})`;
1052
+ return void 0;
1053
+ };
1054
+ const parseFirefox = (line, topFrameMeta) => {
1055
+ const parts = FIREFOX_REGEX.exec(line);
1056
+ const isEval = parts ? parts[2].includes(" > eval") : false;
1057
+ if (!isEval && parts) {
1058
+ debugLog(`parse firefox error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
1059
+ return {
1060
+ column: parts[4] ? +parts[4] : topFrameMeta?.column ?? void 0,
1061
+ file: parts[2],
1062
+ line: parts[3] ? +parts[3] : topFrameMeta?.line ?? void 0,
1063
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- intentionally using || to treat empty string as unknown
1064
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1065
+ raw: line,
1066
+ type: void 0
1067
+ };
1479
1068
  }
1480
- return `${head}${propertyContents}${headClose}${children}${tail}`;
1069
+ return void 0;
1481
1070
  };
1482
- const inspectArguments = (arguments_, options, inspect2) => {
1483
- if (arguments_.length === 0) {
1484
- return "Arguments []";
1071
+ const parseReactAndroidNative = (line) => {
1072
+ const parts = REACT_ANDROID_NATIVE_REGEX.exec(line);
1073
+ if (parts) {
1074
+ debugLog(`parse react android native error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
1075
+ return {
1076
+ column: parts[3] ? +parts[3] : void 0,
1077
+ file: parts[1],
1078
+ line: parts[2] ? +parts[2] : void 0,
1079
+ methodName: UNKNOWN_FUNCTION,
1080
+ raw: line,
1081
+ type: void 0
1082
+ };
1485
1083
  }
1486
- options.truncate -= 13;
1487
- return `Arguments [ ${inspectList(arguments_, arguments_, options, inspect2)} ]`;
1084
+ return void 0;
1488
1085
  };
1489
- const getIndent = (indent, depth) => {
1490
- let baseIndent;
1491
- if (indent === " ") {
1492
- baseIndent = " ";
1493
- } else if (typeof indent === "number" && indent > 0) {
1494
- baseIndent = Array.from({ length: indent + 1 }).join(" ");
1495
- } else {
1496
- return void 0;
1497
- }
1498
- return {
1499
- base: baseIndent,
1500
- prev: `
1501
- ${Array.from({ length: depth + 1 }).join(baseIndent)}`
1502
- };
1503
- };
1504
- const indentedJoin = (values, indent) => {
1505
- if (values.length === 0) {
1506
- return "";
1086
+ const parseStacktrace = (error, { filter, frameLimit = 50 } = {}) => {
1087
+ const errorRecord = error;
1088
+ const rawStack = typeof errorRecord.stacktrace === "string" ? errorRecord.stacktrace : error.stack ?? "";
1089
+ let lines = rawStack.split("\n").map((line) => {
1090
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
1091
+ return cleanedLine.replaceAll(TRIM_REGEX, "");
1092
+ }).filter((line) => !ERROR_LINE_REGEX.test(line) && line !== "eval code");
1093
+ if (filter) {
1094
+ lines = lines.filter((element) => filter(element));
1507
1095
  }
1508
- const lineJoiner = indent.prev + indent.base;
1509
- return lineJoiner + values.split(", ").join(`,${lineJoiner}`) + indent.prev;
1096
+ lines = lines.slice(0, frameLimit);
1097
+ return lines.reduce((stack, line, currentIndex) => {
1098
+ if (!line) {
1099
+ return stack;
1100
+ }
1101
+ if (line.length > 1024) {
1102
+ return stack;
1103
+ }
1104
+ let parseResult;
1105
+ if (NODE_LINE_REGEX.test(line)) {
1106
+ parseResult = parseNode(line);
1107
+ } else if (CHROMIUM_LINE_REGEX.test(line)) {
1108
+ parseResult = parseChromium(line);
1109
+ } else if (GECKO_LINE_REGEX.test(line)) {
1110
+ let topFrameMeta;
1111
+ if (currentIndex === 0) {
1112
+ const browserError = error;
1113
+ const columnNumber = browserError.columnNumber;
1114
+ const lineNumber = browserError.lineNumber;
1115
+ const safariLine = browserError.line;
1116
+ const safariColumn = browserError.column;
1117
+ if (columnNumber || lineNumber) {
1118
+ topFrameMeta = {
1119
+ column: columnNumber,
1120
+ line: lineNumber,
1121
+ type: "firefox"
1122
+ };
1123
+ } else if (safariLine || safariColumn) {
1124
+ topFrameMeta = {
1125
+ column: safariColumn,
1126
+ line: safariLine,
1127
+ type: "safari"
1128
+ };
1129
+ }
1130
+ }
1131
+ parseResult = parseFirefox(line, topFrameMeta) ?? parseGecko(line, topFrameMeta);
1132
+ } else {
1133
+ parseResult = parseReactAndroidNative(line);
1134
+ }
1135
+ if (parseResult) {
1136
+ stack.push(parseResult);
1137
+ } else {
1138
+ debugLog(`parse error stack line: "${line}"`, "not parser found");
1139
+ }
1140
+ return stack;
1141
+ }, []);
1510
1142
  };
1511
- const simpleKeyRegex = /^[a-z_]\w*$/i;
1512
- const quoteEdgesRegex = /^"|"$/g;
1513
- const quoteComplexKey = (key, options) => {
1514
- if (simpleKeyRegex.test(key)) {
1515
- return key;
1143
+
1144
+ const {
1145
+ existsSync,
1146
+ readFileSync
1147
+ } = __cjs_getBuiltinModule("node:fs");
1148
+ const {
1149
+ relative
1150
+ } = __cjs_getBuiltinModule("node:path");
1151
+ const {
1152
+ cwd
1153
+ } = __cjs_getProcess;
1154
+ const {
1155
+ fileURLToPath
1156
+ } = __cjs_getBuiltinModule("node:url");
1157
+ const getPrefix = (prefix, indentation, deep) => {
1158
+ if (deep === 0) {
1159
+ return prefix;
1516
1160
  }
1517
- const stringifiedKey = JSON.stringify(key);
1518
- if (options.quoteStyle === "double") {
1519
- return stringifiedKey.replaceAll('"', String.raw`\"`);
1161
+ if (indentation === " ") {
1162
+ return prefix + " ".repeat(deep);
1520
1163
  }
1521
- return stringifiedKey.replaceAll("'", String.raw`\'`).replaceAll(String.raw`\"`, '"').replaceAll(quoteEdgesRegex, "'");
1164
+ return prefix + " ".repeat(indentation * deep);
1522
1165
  };
1523
- const inspectProperty = ([key, value], object, options, inspect2) => {
1524
- options.truncate -= 2;
1525
- let keyString;
1526
- if (typeof key === "string") {
1527
- keyString = quoteComplexKey(key, options);
1528
- } else if (typeof key === "number") {
1529
- keyString = String(key);
1530
- } else {
1531
- keyString = `[${inspect2(key, object, options)}]`;
1166
+ const getRelativePath = (filePath, cwdPath) => {
1167
+ const path = filePath.replace("async file:", "file:");
1168
+ return relative(cwdPath, path.startsWith("file:") ? fileURLToPath(path) : path);
1169
+ };
1170
+ const getTitleText = (error, hideErrorTitle, color) => {
1171
+ if (hideErrorTitle) {
1172
+ return color.title(error.message);
1532
1173
  }
1533
- options.truncate -= keyString.length;
1534
- const valueString = inspect2(value, object, options);
1535
- return `${keyString}: ${valueString}`;
1174
+ const messagePart = error.message ? `: ${error.message}` : "";
1175
+ return color.title(error.name + messagePart);
1536
1176
  };
1537
- const multiLineValues = (values) => {
1538
- for (const value of values) {
1539
- if (Array.isArray(value) || typeof value === "object" && value !== null) {
1540
- return true;
1177
+ const getMessage = (error, { color, hideErrorTitle, indentation, prefix }, deep) => `${getPrefix(prefix, indentation, deep)}${getTitleText(error, hideErrorTitle, color)}
1178
+ `;
1179
+ const getHint = (error, { color, indentation, prefix }, deep) => {
1180
+ if (error.hint === void 0) {
1181
+ return void 0;
1182
+ }
1183
+ const spaces = getPrefix(prefix, indentation, deep);
1184
+ let message = "";
1185
+ if (Array.isArray(error.hint)) {
1186
+ for (const line of error.hint) {
1187
+ message += `${spaces + line}
1188
+ `;
1541
1189
  }
1190
+ } else {
1191
+ message += spaces + error.hint;
1542
1192
  }
1543
- return false;
1193
+ return color.hint(message);
1544
1194
  };
1545
- const inspectArray = (array, options, inspect2, indent) => {
1546
- const nonIndexProperties = Object.keys(array).slice(array.length);
1547
- if (array.length === 0 && nonIndexProperties.length === 0) {
1548
- return "[]";
1549
- }
1550
- options.truncate -= 4;
1551
- let listContents = inspectList(array, array, options, inspect2);
1552
- options.truncate -= listContents.length;
1553
- let propertyContents = "";
1554
- if (nonIndexProperties.length > 0) {
1555
- propertyContents = inspectList(
1556
- nonIndexProperties.map((key) => [key, array[key]]),
1557
- array,
1558
- options,
1559
- inspect2,
1560
- inspectProperty
1561
- );
1195
+ const getMainFrame = (trace, { color, cwd: cwdPath, displayShortPath, indentation, prefix }, deep = 0) => {
1196
+ const filePath = displayShortPath ? getRelativePath(trace.file, cwdPath) : trace.file;
1197
+ const { fileLine, method } = color;
1198
+ return `${getPrefix(prefix, indentation, deep)}at ${trace.methodName ? `${method(trace.methodName)} ` : ""}${fileLine(filePath)}:${fileLine(
1199
+ trace.line?.toString() ?? ""
1200
+ )}`;
1201
+ };
1202
+ const getCode = (trace, { color, indentation, linesAbove, linesBelow, prefix, showGutter, showLineNumbers, tabWidth }, deep) => {
1203
+ if (trace.file === void 0) {
1204
+ return void 0;
1562
1205
  }
1563
- const hasIndent = indent && multiLineValues(array);
1564
- if (hasIndent) {
1565
- listContents = indentedJoin(listContents, indent);
1206
+ const filePath = trace.file.replace("file://", "");
1207
+ if (!existsSync(filePath)) {
1208
+ return void 0;
1566
1209
  }
1567
- return `[${hasIndent ? "" : " "}${listContents}${propertyContents ? `, ${propertyContents}` : ""}${hasIndent ? "" : " "}]`;
1210
+ const fileContent = readFileSync(filePath, "utf8");
1211
+ return codeFrame(
1212
+ fileContent,
1213
+ {
1214
+ start: { column: trace.column, line: trace.line }
1215
+ },
1216
+ { color, linesAbove, linesBelow, prefix: getPrefix(prefix, indentation, deep), showGutter, showLineNumbers, tabWidth }
1217
+ );
1568
1218
  };
1569
- const separatorRegex = /\d(?=(?:\d{3})+(?!\d))/g;
1570
- const decimalGroupRegex = /\d{3}/g;
1571
- const trailingUnderscoreRegex = /_$/;
1572
- const addNumericSeparator = (number_, string_) => {
1573
- if (number_ === Number.POSITIVE_INFINITY || number_ === Number.NEGATIVE_INFINITY || string_.includes("e")) {
1574
- return string_;
1219
+ const getErrors = (error, options, deep) => {
1220
+ if (error.errors.length === 0) {
1221
+ return void 0;
1575
1222
  }
1576
- if (typeof number_ === "number") {
1577
- const int = number_ < 0 ? -Math.floor(-number_) : Math.floor(number_);
1578
- if (int !== number_) {
1579
- const intString = String(int);
1580
- const dec = string_.slice(intString.length + 1);
1581
- return (
1582
- // eslint-disable-next-line unicorn/prefer-string-replace-all
1583
- `${intString.replace(separatorRegex, "$&_")}.${dec.replace(decimalGroupRegex, "$&_").replace(trailingUnderscoreRegex, "")}`
1584
- );
1223
+ let message = `${getPrefix(options.prefix, options.indentation, deep)}Errors:
1224
+
1225
+ `;
1226
+ let first = true;
1227
+ for (const error_ of error.errors) {
1228
+ if (first) {
1229
+ first = false;
1230
+ } else {
1231
+ message += "\n\n";
1585
1232
  }
1233
+ message += internalRenderError(error_, { ...options, framesMaxLimit: 1, hideErrorCodeView: options.hideErrorErrorsCodeView }, deep + 1);
1586
1234
  }
1587
- return string_.replace(separatorRegex, "$&_");
1235
+ return `
1236
+ ${message}`;
1588
1237
  };
1589
- const isHighSurrogate = (char) => char >= "\uD800" && char <= "\uDBFF";
1590
- const truncate = (string, length, tail = TRUNCATOR) => {
1591
- string = String(string);
1592
- const tailLength = tail.length;
1593
- const stringLength = string.length;
1594
- if (tailLength > length && stringLength > tailLength) {
1595
- return tail;
1238
+ const getCause = (error, options, deep) => {
1239
+ let message = `${getPrefix(options.prefix, options.indentation, deep)}Caused by:
1240
+
1241
+ `;
1242
+ const cause = error.cause;
1243
+ message += getMessage(cause, options, deep);
1244
+ const stacktrace = parseStacktrace(cause);
1245
+ const mainFrame = stacktrace.shift();
1246
+ const hint = getHint(cause, options, deep);
1247
+ if (hint) {
1248
+ message += `${hint}
1249
+ `;
1596
1250
  }
1597
- if (stringLength > length && stringLength > tailLength) {
1598
- let end = length - tailLength;
1599
- if (end > 0 && isHighSurrogate(string[end - 1])) {
1600
- end -= 1;
1251
+ if (mainFrame) {
1252
+ message += getMainFrame(mainFrame, options, deep);
1253
+ if (!options.hideErrorCauseCodeView) {
1254
+ const code = getCode(mainFrame, options, deep);
1255
+ if (code !== void 0) {
1256
+ message += `
1257
+ ${code}`;
1258
+ }
1601
1259
  }
1602
- return `${string.slice(0, end)}${tail}`;
1603
- }
1604
- return string;
1605
- };
1606
- const inspectBigInt = (number, options) => {
1607
- let nums = truncate(number.toString(), options.truncate - 1);
1608
- if (nums !== TRUNCATOR) {
1609
- nums += "n";
1610
1260
  }
1611
- return options.stylize(options.numericSeparator ? addNumericSeparator(number, nums) : nums, "bigint");
1612
- };
1613
- const gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) {
1614
- return O.__proto__;
1615
- } : void 0);
1616
- const inspectObject$1 = (object, options, inspect2, indent) => {
1617
- if ("window" in globalThis && object === globalThis) {
1618
- return "{ [object Window] }";
1619
- }
1620
- if (object === globalThis || "global" in globalThis && object === globalThis) {
1621
- return "{ [object globalThis] }";
1261
+ if (cause.cause) {
1262
+ message += `
1263
+ ${getCause(cause, options, deep + 1)}`;
1264
+ } else if (cause instanceof AggregateError) {
1265
+ const errors = getErrors(cause, options, deep);
1266
+ if (errors !== void 0) {
1267
+ message += `
1268
+ ${errors}`;
1269
+ }
1622
1270
  }
1623
- const properties = Object.getOwnPropertyNames(object);
1624
- const symbols = Object.getOwnPropertySymbols(object);
1625
- const isPlainObject = gPO(object) === Object.prototype || object.constructor === Object;
1626
- const protoTag = object instanceof Object ? "" : "null prototype";
1627
- let stringTag;
1628
- if (!isPlainObject && Symbol.toStringTag in object) {
1629
- stringTag = object[Symbol.toStringTag];
1630
- } else {
1631
- stringTag = protoTag ? "Object" : "";
1271
+ return `
1272
+ ${message}`;
1273
+ };
1274
+ const getStacktrace = (stack, options) => (stack.length > 0 ? "\n" : "") + stack.map((frame) => getMainFrame(frame, options)).join("\n");
1275
+ const internalRenderError = (error, options, deep) => {
1276
+ const config = {
1277
+ cwd: cwd(),
1278
+ displayShortPath: false,
1279
+ filterStacktrace: void 0,
1280
+ framesMaxLimit: Number.POSITIVE_INFINITY,
1281
+ hideErrorCauseCodeView: false,
1282
+ hideErrorCodeView: false,
1283
+ hideErrorErrorsCodeView: false,
1284
+ hideErrorTitle: false,
1285
+ hideMessage: false,
1286
+ indentation: 4,
1287
+ linesAbove: 2,
1288
+ linesBelow: 3,
1289
+ prefix: "",
1290
+ showGutter: true,
1291
+ showLineNumbers: true,
1292
+ tabWidth: 4,
1293
+ ...options,
1294
+ color: {
1295
+ fileLine: (value) => value,
1296
+ gutter: (value) => value,
1297
+ hint: (value) => value,
1298
+ marker: (value) => value,
1299
+ message: (value) => value,
1300
+ method: (value) => value,
1301
+ title: (value) => value,
1302
+ ...options.color
1303
+ }
1304
+ };
1305
+ const stack = parseStacktrace(error, {
1306
+ filter: options.filterStacktrace,
1307
+ frameLimit: config.framesMaxLimit
1308
+ });
1309
+ const mainFrame = stack.shift();
1310
+ return [
1311
+ options.hideMessage ? void 0 : getMessage(error, config, deep),
1312
+ getHint(error, config, deep),
1313
+ mainFrame ? getMainFrame(mainFrame, config, deep) : void 0,
1314
+ mainFrame && !config.hideErrorCodeView ? getCode(mainFrame, config, deep) : void 0,
1315
+ error instanceof AggregateError ? getErrors(error, config, deep) : void 0,
1316
+ error.cause === void 0 ? void 0 : getCause(error, config, deep),
1317
+ stack.length > 0 ? getStacktrace(stack, config) : void 0
1318
+ ].filter(Boolean).join("\n").replaceAll("\\", "/");
1319
+ };
1320
+ const renderError = (error, options = {}) => {
1321
+ if (options.framesMaxLimit !== void 0 && options.framesMaxLimit <= 0) {
1322
+ throw new RangeError("The 'framesMaxLimit' option must be a positive number");
1632
1323
  }
1633
- const tag = stringTag || protoTag ? `[${[stringTag, protoTag].filter(Boolean).join(": ")}] ` : "";
1634
- if (properties.length === 0 && symbols.length === 0) {
1635
- return `${tag}{}`;
1324
+ return internalRenderError(error, options, 0);
1325
+ };
1326
+
1327
+ const ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
1328
+ const fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
1329
+ const halfwidthRanges = [8361, 8361, 65377, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65512, 65518];
1330
+ const narrowRanges = [32, 126, 162, 163, 165, 166, 172, 172, 175, 175, 10214, 10221, 10629, 10630];
1331
+ const wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];
1332
+ const isInRange = (ranges, codePoint) => {
1333
+ let low = 0;
1334
+ let high = Math.floor(ranges.length / 2) - 1;
1335
+ while (low <= high) {
1336
+ const mid = Math.floor((low + high) / 2);
1337
+ const i = mid * 2;
1338
+ if (codePoint < ranges[i]) {
1339
+ high = mid - 1;
1340
+ } else if (codePoint > ranges[i + 1]) {
1341
+ low = mid + 1;
1342
+ } else {
1343
+ return true;
1344
+ }
1636
1345
  }
1637
- options.truncate -= 4;
1638
- const propertyContents = inspectList(
1639
- properties.map((key) => [key, object[key]]),
1640
- object,
1641
- options,
1642
- inspect2,
1643
- inspectProperty
1644
- );
1645
- const symbolContents = inspectList(
1646
- symbols.map((key) => [key, object[key]]),
1647
- object,
1648
- options,
1649
- inspect2,
1650
- inspectProperty
1651
- );
1652
- let separator = "";
1653
- if (propertyContents && symbolContents) {
1654
- separator = ", ";
1346
+ return false;
1347
+ };
1348
+ const minimumAmbiguousCodePoint = ambiguousRanges[0];
1349
+ const maximumAmbiguousCodePoint = ambiguousRanges.at(-1);
1350
+ const minimumFullWidthCodePoint = fullwidthRanges[0];
1351
+ const maximumFullWidthCodePoint = fullwidthRanges.at(-1);
1352
+ const minimumHalfWidthCodePoint = halfwidthRanges[0];
1353
+ const maximumHalfWidthCodePoint = halfwidthRanges.at(-1);
1354
+ const minimumNarrowCodePoint = narrowRanges[0];
1355
+ const maximumNarrowCodePoint = narrowRanges.at(-1);
1356
+ const minimumWideCodePoint = wideRanges[0];
1357
+ const maximumWideCodePoint = wideRanges.at(-1);
1358
+ const commonCjkCodePoint = 19968;
1359
+ const [wideFastPathStart, wideFastPathEnd] = findWideFastPathRange(wideRanges);
1360
+ function findWideFastPathRange(ranges) {
1361
+ let fastPathStart = ranges[0];
1362
+ let fastPathEnd = ranges[1];
1363
+ for (let index = 0; index < ranges.length; index += 2) {
1364
+ const start = ranges[index];
1365
+ const end = ranges[index + 1];
1366
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
1367
+ return [start, end];
1368
+ }
1369
+ if (end - start > fastPathEnd - fastPathStart) {
1370
+ fastPathStart = start;
1371
+ fastPathEnd = end;
1372
+ }
1655
1373
  }
1656
- if (indent) {
1657
- return `${tag}{${indentedJoin(propertyContents + separator + symbolContents, indent)}}`;
1374
+ return [fastPathStart, fastPathEnd];
1375
+ }
1376
+ const isAmbiguous = (codePoint) => {
1377
+ if (codePoint < minimumAmbiguousCodePoint || codePoint > maximumAmbiguousCodePoint) {
1378
+ return false;
1658
1379
  }
1659
- return `${tag}{ ${propertyContents}${separator}${symbolContents} }`;
1380
+ return isInRange(ambiguousRanges, codePoint);
1660
1381
  };
1661
- const inspectClass = (value, options, inspect2, indent) => {
1662
- let name = "";
1663
- name = name || value.constructor.name;
1664
- if (!name || name === "_class") {
1665
- name = "<Anonymous Class>";
1382
+ const isFullWidth = (codePoint) => {
1383
+ if (codePoint < minimumFullWidthCodePoint || codePoint > maximumFullWidthCodePoint) {
1384
+ return false;
1666
1385
  }
1667
- options.truncate -= name.length;
1668
- return `${name} ${inspectObject$1(value, options, inspect2, indent)}`;
1386
+ return isInRange(fullwidthRanges, codePoint);
1669
1387
  };
1670
- const inspectDate = (dateObject, options) => {
1671
- const stringRepresentation = dateObject.toJSON();
1672
- if (stringRepresentation === null) {
1673
- return "Invalid Date";
1388
+ const isHalfWidth = (codePoint) => {
1389
+ if (codePoint < minimumHalfWidthCodePoint || codePoint > maximumHalfWidthCodePoint) {
1390
+ return false;
1674
1391
  }
1675
- const split = stringRepresentation.split("T");
1676
- const date = split[0];
1677
- return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date");
1392
+ return isInRange(halfwidthRanges, codePoint);
1678
1393
  };
1679
- const errorKeys = /* @__PURE__ */ new Set(["column", "columnNumber", "description", "fileName", "line", "lineNumber", "message", "name", "number", "stack"]);
1680
- const inspectObject = (error, options, inspect2) => {
1681
- const properties = Object.getOwnPropertyNames(error).filter((key) => !errorKeys.has(key));
1682
- const { name } = error;
1683
- options.truncate -= name.length;
1684
- let message = "";
1685
- if (typeof error.message === "string") {
1686
- message = truncate(error.message, options.truncate);
1687
- } else {
1688
- properties.unshift("message");
1394
+ const isNarrow = (codePoint) => {
1395
+ if (codePoint < minimumNarrowCodePoint || codePoint > maximumNarrowCodePoint) {
1396
+ return false;
1689
1397
  }
1690
- message = message ? `: ${message}` : "";
1691
- options.truncate -= message.length + 5;
1692
- const propertyContents = inspectList(
1693
- properties.map((key) => [key, error[key]]),
1694
- error,
1695
- options,
1696
- inspect2,
1697
- inspectProperty
1698
- );
1699
- return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
1398
+ return isInRange(narrowRanges, codePoint);
1700
1399
  };
1701
- const inspectFunction = (function_, options) => {
1702
- const functionType = function_[Symbol.toStringTag] || "Function";
1703
- const source = function_.toString();
1704
- if (source.length < options.truncate - 12) {
1705
- return options.stylize(`[${functionType}: ${source}]`, "special");
1400
+ const isWide = (codePoint) => {
1401
+ if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
1402
+ return true;
1706
1403
  }
1707
- const { name } = function_;
1708
- if (!name) {
1709
- return options.stylize(`[${functionType}]`, "special");
1404
+ if (codePoint < minimumWideCodePoint || codePoint > maximumWideCodePoint) {
1405
+ return false;
1710
1406
  }
1711
- return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special");
1712
- };
1713
- const inspectMapEntry = ([key, value], object, options, inspect2) => {
1714
- options.truncate -= 4;
1715
- key = inspect2(key, object, options);
1716
- options.truncate -= key.length;
1717
- return `${key} => ${inspect2(value, object, options)}`;
1407
+ return isInRange(wideRanges, codePoint);
1718
1408
  };
1719
- const inspectMap = (map, options, inspect2, indent) => {
1720
- if (map.size <= 0) {
1721
- return "Map (0) {}";
1722
- }
1723
- options.truncate -= 7;
1724
- let returnValue = inspectList([...map.entries()], map, options, inspect2, inspectMapEntry);
1725
- if (indent) {
1726
- returnValue = indentedJoin(returnValue, indent);
1409
+ function getCategory(codePoint) {
1410
+ if (isAmbiguous(codePoint)) {
1411
+ return "ambiguous";
1727
1412
  }
1728
- return `Map (${String(map.size)}) {${indent ? "" : " "}${returnValue}${indent ? "" : " "}}`;
1729
- };
1730
- function inspectNumber(number, options) {
1731
- if (Number.isNaN(number)) {
1732
- return options.stylize("NaN", "number");
1413
+ if (isFullWidth(codePoint)) {
1414
+ return "fullwidth";
1733
1415
  }
1734
- if (number === Number.POSITIVE_INFINITY) {
1735
- return options.stylize("Infinity", "number");
1416
+ if (isHalfWidth(codePoint)) {
1417
+ return "halfwidth";
1736
1418
  }
1737
- if (number === Number.NEGATIVE_INFINITY) {
1738
- return options.stylize("-Infinity", "number");
1419
+ if (isNarrow(codePoint)) {
1420
+ return "narrow";
1739
1421
  }
1740
- if (number === 0) {
1741
- return options.stylize(1 / number === Number.POSITIVE_INFINITY ? "+0" : "-0", "number");
1422
+ if (isWide(codePoint)) {
1423
+ return "wide";
1742
1424
  }
1743
- return options.stylize(truncate(options.numericSeparator ? addNumericSeparator(number, number.toString()) : number.toString(), options.truncate), "number");
1425
+ return "neutral";
1744
1426
  }
1745
- const getPromiseValue = () => "Promise{…}";
1746
- const inspectRegExp = (regExp, options) => {
1747
- const sourceLength = options.truncate - (2 + regExp.flags.length);
1748
- return options.stylize(`/${truncate(regExp.source, sourceLength)}/${regExp.flags}`, "regexp");
1749
- };
1750
- const inspectSet = (set, options, inspect2, indent) => {
1751
- if (set.size === 0) {
1752
- return "Set (0) {}";
1427
+
1428
+ function validate(codePoint) {
1429
+ if (!Number.isSafeInteger(codePoint)) {
1430
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
1753
1431
  }
1754
- options.truncate -= 7;
1755
- let returnValue = inspectList([...set], set, options, inspect2);
1756
- if (indent) {
1757
- returnValue = indentedJoin(returnValue, indent);
1432
+ }
1433
+ function eastAsianWidthType(codePoint) {
1434
+ validate(codePoint);
1435
+ return getCategory(codePoint);
1436
+ }
1437
+
1438
+ const r = String.raw;
1439
+ const e = r`\p{Emoji}(?:\p{EMod}|[\u{E0020}-\u{E007E}]+\u{E007F}|\uFE0F?\u20E3?)`;
1440
+ const emojiRegex = () => new RegExp(r`\p{RI}{2}|(?![#*\d](?!\uFE0F?\u20E3))${e}(?:\u200D${e})*`, "gu");
1441
+ const ESCAPES = /* @__PURE__ */ new Set(["\x1B", "›"]);
1442
+ const ANSI_ESCAPE_BELL = "\x07";
1443
+ const ANSI_CSI = "[";
1444
+ const ANSI_SGR_TERMINATOR = "m";
1445
+ const ANSI_ESCAPE_LINK = `]8;;`;
1446
+ const END_CODE = 39;
1447
+ const RE_ZERO_WIDTH = /[\u200B\uFEFF\u2060-\u2064]/g;
1448
+ const RE_ESCAPE_PATTERN = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`);
1449
+ const ANSI_RESET_CODES = Object.freeze(
1450
+ /* @__PURE__ */ new Map([
1451
+ [0, 0],
1452
+ // Reset all
1453
+ [1, 22],
1454
+ // Bold → Not bold
1455
+ [2, 22],
1456
+ // Dim → Not bold
1457
+ [3, 23],
1458
+ // Italic → Not italic
1459
+ [4, 24],
1460
+ // Underline → Not underline
1461
+ [7, 27],
1462
+ // Inverse → Not inverse
1463
+ [8, 28],
1464
+ // Hidden → Not hidden
1465
+ [9, 29],
1466
+ // Strikethrough → Not strikethrough
1467
+ [30, 39],
1468
+ // Foreground colors → Default foreground
1469
+ [31, 39],
1470
+ [32, 39],
1471
+ [33, 39],
1472
+ [34, 39],
1473
+ [35, 39],
1474
+ [36, 39],
1475
+ [37, 39],
1476
+ [40, 49],
1477
+ // Background colors → Default background
1478
+ [41, 49],
1479
+ [42, 49],
1480
+ [43, 49],
1481
+ [44, 49],
1482
+ [45, 49],
1483
+ [46, 49],
1484
+ [47, 49],
1485
+ [90, 39]
1486
+ // Bright foreground → Default foreground
1487
+ ])
1488
+ );
1489
+ const RE_ANSI = /[\u001B\u009B](?:[[()#;?]{0,10}(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><]|\]8;;[^\u0007\u001B]{0,100}(?:\u0007|\u001B\\))/g;
1490
+ const RE_CONTROL = /[\u0000-\u0008\n-\u001F\u007F-\u009F]{1,1000}/y;
1491
+ const RE_EMOJI = emojiRegex();
1492
+
1493
+ const charWidthCache = /* @__PURE__ */ new Map();
1494
+ const RE_LATIN_CHARS = /(?:[\u0020-\u007E\u00A0-\u00FF](?!\uFE0F)){1,1000}/y;
1495
+ const getCharType = (codePoint) => {
1496
+ if (codePoint >= 32 && codePoint <= 126) {
1497
+ return "latin";
1758
1498
  }
1759
- return `Set (${String(set.size)}) {${indent ? "" : " "}${returnValue}${indent ? "" : " "}}`;
1760
- };
1761
- const wrapQuotes = (string_, options) => {
1762
- const quoteChar = options.quoteStyle === "double" ? '"' : "'";
1763
- if (options.quoteStyle === "double") {
1764
- string_ = string_.replaceAll('"', '"');
1499
+ if (codePoint === 8203 || codePoint === 8204 || codePoint === 8205 || codePoint === 8288) {
1500
+ return "zero";
1765
1501
  }
1766
- return quoteChar + string_ + quoteChar;
1502
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
1503
+ return "control";
1504
+ }
1505
+ if (codePoint >= 160 && codePoint <= 255) {
1506
+ return "latin";
1507
+ }
1508
+ if (codePoint >= 9472 && codePoint <= 9599) {
1509
+ return "latin";
1510
+ }
1511
+ if (codePoint >= 4352 && codePoint <= 4607 || codePoint >= 11904 && codePoint <= 40959 || codePoint >= 44032 && codePoint <= 55215 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65280 && codePoint <= 65519 && !(codePoint >= 65377 && codePoint <= 65439) || codePoint >= 12352 && codePoint <= 12543) {
1512
+ return "wide";
1513
+ }
1514
+ if (codePoint === 8230) {
1515
+ return "latin";
1516
+ }
1517
+ return "other";
1767
1518
  };
1768
- const stringEscapeChars = new RegExp(
1769
- String.raw`['\0-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5` + String.raw`\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]`,
1770
- "g"
1771
- );
1772
- const escapeCharacters = {
1773
- " ": String.raw`\t`,
1774
- "\n": String.raw`\n`,
1775
- "\f": String.raw`\f`,
1776
- "\r": String.raw`\r`,
1777
- "\b": String.raw`\b`,
1778
- "'": String.raw`\'`,
1779
- "\\": "\\\\"
1519
+ const getCachedCharWidth = (codePoint, config) => {
1520
+ const highBits = Math.floor(codePoint / 65536);
1521
+ const lowBits = codePoint % 65536;
1522
+ let lowMap = charWidthCache.get(highBits);
1523
+ if (!lowMap) {
1524
+ lowMap = /* @__PURE__ */ new Map();
1525
+ charWidthCache.set(highBits, lowMap);
1526
+ }
1527
+ if (lowMap.has(lowBits)) {
1528
+ return lowMap.get(lowBits);
1529
+ }
1530
+ let width;
1531
+ if (getCharType(codePoint) === "latin") {
1532
+ width = config.width.regular;
1533
+ } else if (getCharType(codePoint) === "control") {
1534
+ width = config.width.control;
1535
+ } else if (getCharType(codePoint) === "wide") {
1536
+ width = config.width.wide;
1537
+ } else {
1538
+ const eaw = eastAsianWidthType(codePoint);
1539
+ switch (eaw) {
1540
+ case "ambiguous": {
1541
+ width = config.width.ambiguousIsNarrow ? config.width.regular : config.width.wide;
1542
+ break;
1543
+ }
1544
+ case "fullwidth": {
1545
+ width = config.width.fullWidth;
1546
+ break;
1547
+ }
1548
+ case "wide": {
1549
+ width = config.width.wide;
1550
+ break;
1551
+ }
1552
+ default: {
1553
+ width = config.width.regular;
1554
+ }
1555
+ }
1556
+ }
1557
+ lowMap.set(lowBits, width);
1558
+ return width;
1780
1559
  };
1781
- const hex = 16;
1782
- const escape = (char) => escapeCharacters[char] || String.raw`\u${`0000${char.codePointAt(0).toString(hex)}`.slice(-4)}`;
1783
- const inspectString = (string_, options) => {
1784
- if (stringEscapeChars.test(string_)) {
1785
- string_ = string_.replaceAll(stringEscapeChars, escape);
1560
+ const isCombiningCharacter = (codePoint) => {
1561
+ if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
1562
+ return true;
1786
1563
  }
1787
- return options.stylize(wrapQuotes(truncate(string_, options.truncate - 2), options), "string");
1564
+ if (codePoint >= 917760 && codePoint <= 917999 || codePoint >= 65024 && codePoint <= 65039) {
1565
+ return true;
1566
+ }
1567
+ if (codePoint >= 3633 && codePoint <= 3642 || codePoint >= 3655 && codePoint <= 3662 || codePoint >= 3761 && codePoint <= 3769 || codePoint >= 3771 && codePoint <= 3772 || codePoint >= 3784 && codePoint <= 3789) {
1568
+ return true;
1569
+ }
1570
+ if (codePoint >= 2304 && codePoint <= 2307 || codePoint >= 2362 && codePoint <= 2383 || codePoint >= 2385 && codePoint <= 2391 || codePoint >= 2402 && codePoint <= 2403 || codePoint >= 2433 && codePoint <= 2435 || codePoint >= 2492 && codePoint <= 2500 || codePoint >= 2509 && codePoint <= 2509 || codePoint >= 2561 && codePoint <= 2563 || codePoint >= 2620 && codePoint <= 2637) {
1571
+ return true;
1572
+ }
1573
+ if (codePoint >= 1611 && codePoint <= 1631 || codePoint >= 1648 && codePoint <= 1648 || codePoint >= 1750 && codePoint <= 1773 || codePoint >= 2276 && codePoint <= 2302) {
1574
+ return true;
1575
+ }
1576
+ if (codePoint >= 1425 && codePoint <= 1469 || codePoint >= 1471 && codePoint <= 1471 || codePoint >= 1473 && codePoint <= 1474 || codePoint >= 1476 && codePoint <= 1477 || codePoint >= 1479 && codePoint <= 1479) {
1577
+ return true;
1578
+ }
1579
+ if (codePoint >= 3893 && codePoint <= 3893 || codePoint >= 3895 && codePoint <= 3895 || codePoint >= 3897 && codePoint <= 3897 || codePoint >= 3953 && codePoint <= 3966 || codePoint >= 3968 && codePoint <= 3972 || codePoint >= 3974 && codePoint <= 3975) {
1580
+ return true;
1581
+ }
1582
+ return codePoint >= 768 && codePoint <= 777 || codePoint >= 803 && codePoint <= 803;
1788
1583
  };
1789
- const inspectSymbol = (value) => {
1790
- if ("description" in Symbol.prototype) {
1791
- return value.description ? `Symbol(${value.description})` : "Symbol()";
1584
+ const getStringTruncatedWidth = (input, options = {}) => {
1585
+ if (!input || input.length === 0) {
1586
+ return { ellipsed: false, index: 0, truncated: false, width: 0 };
1792
1587
  }
1793
- return value.toString();
1588
+ const config = {
1589
+ truncation: {
1590
+ countAnsiEscapeCodes: options.countAnsiEscapeCodes ?? false,
1591
+ ellipsis: options.ellipsis ?? "",
1592
+ ellipsisWidth: options.ellipsisWidth ?? (options.ellipsis ? getStringTruncatedWidth(options.ellipsis, {
1593
+ ...options,
1594
+ ellipsis: "",
1595
+ ellipsisWidth: 0,
1596
+ limit: Number.POSITIVE_INFINITY
1597
+ }).width : 0),
1598
+ limit: options.limit ?? Number.POSITIVE_INFINITY
1599
+ },
1600
+ width: {
1601
+ ambiguousIsNarrow: options.ambiguousIsNarrow ?? false,
1602
+ ansi: options.ansiWidth ?? 0,
1603
+ control: options.controlWidth ?? 0,
1604
+ emoji: options.emojiWidth ?? 2,
1605
+ fullWidth: options.fullWidth ?? 2,
1606
+ halfWidth: options.halfWidth ?? 1,
1607
+ regular: options.regularWidth ?? 1,
1608
+ tab: options.tabWidth ?? 8,
1609
+ wide: options.wideWidth ?? 2
1610
+ }
1611
+ };
1612
+ const truncationLimit = Math.max(0, config.truncation.limit - config.truncation.ellipsisWidth);
1613
+ const { length } = input;
1614
+ const useCaching = length > 1e4;
1615
+ let index = 0;
1616
+ let width = 0;
1617
+ let truncationIndex = length;
1618
+ let truncationEnabled = false;
1619
+ const hasAnsi = input.includes("\x1B") || input.includes("›");
1620
+ while (index < length) {
1621
+ if (hasAnsi && (input[index] === "\x1B" || input[index] === "›")) {
1622
+ if (input.startsWith("\x1B]8;;", index)) {
1623
+ const BELL = "\x07";
1624
+ const OSC8_CLOSER = `\x1B]8;;${BELL}`;
1625
+ const OSC8_CLOSER_LEN = OSC8_CLOSER.length;
1626
+ const endOfParametersIndex = input.indexOf(BELL, index + 5);
1627
+ if (endOfParametersIndex === -1) ;
1628
+ else {
1629
+ const startOfCloserIndex = input.indexOf(OSC8_CLOSER, endOfParametersIndex + 1);
1630
+ if (startOfCloserIndex === -1) ;
1631
+ else {
1632
+ const endOfSequenceIndex = startOfCloserIndex + OSC8_CLOSER_LEN;
1633
+ const linkText = input.slice(endOfParametersIndex + 1, startOfCloserIndex);
1634
+ const strippedLinkText = linkText.replace(RE_ANSI, "");
1635
+ const linkTextWidthResult = getStringTruncatedWidth(strippedLinkText, {
1636
+ ambiguousIsNarrow: config.width.ambiguousIsNarrow,
1637
+ ansiWidth: config.width.ansi,
1638
+ controlWidth: config.width.control,
1639
+ countAnsiEscapeCodes: false,
1640
+ // Never count ANSI in link text width
1641
+ ellipsis: config.truncation.ellipsis,
1642
+ ellipsisWidth: config.truncation.ellipsisWidth,
1643
+ emojiWidth: config.width.emoji,
1644
+ fullWidth: config.width.fullWidth,
1645
+ halfWidth: config.width.halfWidth,
1646
+ limit: Math.max(0, truncationLimit - width),
1647
+ regularWidth: config.width.regular,
1648
+ tabWidth: config.width.tab,
1649
+ wideWidth: config.width.wide
1650
+ });
1651
+ const textWidth = linkTextWidthResult.width;
1652
+ if (linkTextWidthResult.truncated) {
1653
+ truncationEnabled = true;
1654
+ truncationIndex = Math.min(truncationIndex, index);
1655
+ } else if (width + textWidth > truncationLimit) {
1656
+ truncationIndex = Math.min(truncationIndex, index);
1657
+ truncationEnabled = true;
1658
+ if (width + textWidth > config.truncation.limit) {
1659
+ break;
1660
+ }
1661
+ }
1662
+ width += textWidth;
1663
+ index = endOfSequenceIndex;
1664
+ if (truncationEnabled && width >= config.truncation.limit) {
1665
+ break;
1666
+ }
1667
+ continue;
1668
+ }
1669
+ }
1670
+ }
1671
+ RE_ANSI.lastIndex = index;
1672
+ if (RE_ANSI.test(input)) {
1673
+ const ansiLength = RE_ANSI.lastIndex - index;
1674
+ const ansiWidth = config.truncation.countAnsiEscapeCodes ? ansiLength : config.width.ansi;
1675
+ if (width + ansiWidth > truncationLimit) {
1676
+ truncationIndex = Math.min(truncationIndex, index);
1677
+ if (width + ansiWidth > config.truncation.limit) {
1678
+ truncationEnabled = true;
1679
+ break;
1680
+ }
1681
+ }
1682
+ width += ansiWidth;
1683
+ index = RE_ANSI.lastIndex;
1684
+ continue;
1685
+ }
1686
+ }
1687
+ const charCode = input.codePointAt(index);
1688
+ if (charCode === 8203 || charCode === 65279 || charCode >= 8288 && charCode <= 8292) {
1689
+ index += 1;
1690
+ continue;
1691
+ }
1692
+ if (charCode === 9) {
1693
+ if (width + config.width.tab > truncationLimit) {
1694
+ truncationIndex = Math.min(truncationIndex, index);
1695
+ if (width + config.width.tab > config.truncation.limit) {
1696
+ truncationEnabled = true;
1697
+ break;
1698
+ }
1699
+ }
1700
+ width += config.width.tab;
1701
+ index += 1;
1702
+ continue;
1703
+ }
1704
+ RE_LATIN_CHARS.lastIndex = index;
1705
+ if (RE_LATIN_CHARS.test(input)) {
1706
+ const latinLength = RE_LATIN_CHARS.lastIndex - index;
1707
+ const latinWidth = latinLength * config.width.regular;
1708
+ if (width + latinWidth > truncationLimit) {
1709
+ const charsToLimit = Math.floor((truncationLimit - width) / config.width.regular);
1710
+ truncationIndex = Math.min(truncationIndex, index + charsToLimit);
1711
+ if (width + latinWidth > config.truncation.limit) {
1712
+ truncationEnabled = true;
1713
+ break;
1714
+ }
1715
+ }
1716
+ width += latinWidth;
1717
+ index = RE_LATIN_CHARS.lastIndex;
1718
+ continue;
1719
+ }
1720
+ if (charCode <= 31 || charCode >= 127 && charCode <= 159) {
1721
+ RE_CONTROL.lastIndex = index;
1722
+ if (RE_CONTROL.test(input)) {
1723
+ const controlLength = RE_CONTROL.lastIndex - index;
1724
+ const controlWidth = controlLength * config.width.control;
1725
+ if (width + controlWidth > truncationLimit) {
1726
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / config.width.control));
1727
+ if (width + controlWidth > config.truncation.limit) {
1728
+ truncationEnabled = true;
1729
+ break;
1730
+ }
1731
+ }
1732
+ width += controlWidth;
1733
+ index = RE_CONTROL.lastIndex;
1734
+ continue;
1735
+ }
1736
+ }
1737
+ RE_EMOJI.lastIndex = index;
1738
+ if (RE_EMOJI.test(input)) {
1739
+ if (width + config.width.emoji > truncationLimit) {
1740
+ truncationIndex = Math.min(truncationIndex, index);
1741
+ if (width + config.width.emoji > config.truncation.limit) {
1742
+ truncationEnabled = true;
1743
+ break;
1744
+ }
1745
+ }
1746
+ width += config.width.emoji;
1747
+ index = RE_EMOJI.lastIndex;
1748
+ continue;
1749
+ }
1750
+ const codePoint = input.codePointAt(index) ?? 0;
1751
+ if (isCombiningCharacter(codePoint)) {
1752
+ index += codePoint > 65535 ? 2 : 1;
1753
+ continue;
1754
+ }
1755
+ let charWidth;
1756
+ if (useCaching) {
1757
+ charWidth = getCachedCharWidth(codePoint, config);
1758
+ } else {
1759
+ const charType = getCharType(codePoint);
1760
+ switch (charType) {
1761
+ case "control": {
1762
+ charWidth = config.width.control;
1763
+ break;
1764
+ }
1765
+ case "latin": {
1766
+ charWidth = config.width.regular;
1767
+ break;
1768
+ }
1769
+ case "wide": {
1770
+ charWidth = config.width.wide;
1771
+ break;
1772
+ }
1773
+ case "zero": {
1774
+ charWidth = 0;
1775
+ break;
1776
+ }
1777
+ default: {
1778
+ const eaw = eastAsianWidthType(codePoint);
1779
+ switch (eaw) {
1780
+ case "ambiguous": {
1781
+ charWidth = config.width.ambiguousIsNarrow ? config.width.regular : config.width.wide;
1782
+ break;
1783
+ }
1784
+ case "fullwidth": {
1785
+ charWidth = config.width.fullWidth;
1786
+ break;
1787
+ }
1788
+ case "wide": {
1789
+ charWidth = config.width.wide;
1790
+ break;
1791
+ }
1792
+ default: {
1793
+ charWidth = config.width.regular;
1794
+ }
1795
+ }
1796
+ }
1797
+ }
1798
+ }
1799
+ if (width + charWidth > truncationLimit) {
1800
+ truncationIndex = Math.min(truncationIndex, index);
1801
+ if (width + charWidth > config.truncation.limit) {
1802
+ truncationEnabled = true;
1803
+ break;
1804
+ }
1805
+ }
1806
+ width += charWidth;
1807
+ index += codePoint > 65535 ? 2 : 1;
1808
+ }
1809
+ let finalWidth = width;
1810
+ let ellipsed = false;
1811
+ if (truncationEnabled && config.truncation.limit >= config.truncation.ellipsisWidth) {
1812
+ finalWidth = config.truncation.limit;
1813
+ ellipsed = true;
1814
+ }
1815
+ return {
1816
+ ellipsed,
1817
+ index: truncationEnabled ? truncationIndex : length,
1818
+ truncated: truncationEnabled,
1819
+ width: finalWidth
1820
+ };
1794
1821
  };
1795
- const getArrayName = (array) => {
1796
- if (typeof Buffer === "function" && array instanceof Buffer) {
1797
- return "Buffer";
1822
+
1823
+ const getStringWidth = (input, options = {}) => getStringTruncatedWidth(input, { ...options, ellipsis: "", ellipsisWidth: 0, limit: Number.POSITIVE_INFINITY }).width;
1824
+
1825
+ const RE_ANSI_CODE = /\x1B\[(\d+)m/;
1826
+ class AnsiStateTracker {
1827
+ activeForeground = void 0;
1828
+ activeBackground = void 0;
1829
+ // Track other formatting (bold, italic, etc.)
1830
+ activeFormatting = [];
1831
+ /**
1832
+ * Processes an escape sequence and updates the internal state
1833
+ * @param sequence The escape sequence to process
1834
+ */
1835
+ processEscape(sequence) {
1836
+ const match = RE_ANSI_CODE.exec(sequence);
1837
+ if (!match) {
1838
+ return;
1839
+ }
1840
+ const code = Number.parseInt(match[1], 10);
1841
+ switch (code) {
1842
+ case 0: {
1843
+ this.activeForeground = void 0;
1844
+ this.activeBackground = void 0;
1845
+ this.activeFormatting = [];
1846
+ break;
1847
+ }
1848
+ case 39: {
1849
+ this.activeForeground = void 0;
1850
+ break;
1851
+ }
1852
+ case 49: {
1853
+ this.activeBackground = void 0;
1854
+ break;
1855
+ }
1856
+ default: {
1857
+ if (code >= 30 && code <= 37 || code >= 90 && code <= 97) {
1858
+ this.activeForeground = sequence;
1859
+ } else if (code >= 40 && code <= 47 || code >= 100 && code <= 107) {
1860
+ this.activeBackground = sequence;
1861
+ } else if ([1, 2, 3, 4, 7, 8, 9].includes(code)) {
1862
+ this.activeFormatting.push(sequence);
1863
+ } else if ([22, 23, 24, 27, 28, 29].includes(code)) {
1864
+ const formatResetMap = {
1865
+ 22: "[1m",
1866
+ // Reset bold
1867
+ 23: "[3m",
1868
+ // Reset italic
1869
+ 24: "[4m",
1870
+ // Reset underline
1871
+ 27: "[7m",
1872
+ // Reset inverse
1873
+ 28: "[8m",
1874
+ // Reset hidden
1875
+ 29: "[9m"
1876
+ // Reset strikethrough
1877
+ };
1878
+ const formatToRemove = formatResetMap[code];
1879
+ if (formatToRemove) {
1880
+ this.activeFormatting = this.activeFormatting.filter((fmt) => !fmt.includes(formatToRemove));
1881
+ }
1882
+ }
1883
+ }
1884
+ }
1798
1885
  }
1799
- return array[Symbol.toStringTag];
1800
- };
1801
- const inspectTypedArray = (array, options, inspect2) => {
1802
- const name = getArrayName(array);
1803
- options.truncate -= name.length + 4;
1804
- const nonIndexProperties = Object.keys(array).slice(array.length);
1805
- if (array.length === 0 && nonIndexProperties.length === 0) {
1806
- return `${name}[]`;
1886
+ /**
1887
+ * Gets all active escape sequences to apply.
1888
+ * @returns String with all active escapes
1889
+ */
1890
+ getStartEscapesForAllActiveAttributes() {
1891
+ return [this.activeBackground, this.activeForeground, ...this.activeFormatting].filter(Boolean).join("");
1807
1892
  }
1808
- let output = "";
1809
- for (let index = 0; index < array.length; index++) {
1810
- const string = `${options.stylize(truncate(array[index], options.truncate), "number")}${index === array.length - 1 ? "" : ", "}`;
1811
- options.truncate -= string.length;
1812
- if (array[index] !== array.length && options.truncate <= 3) {
1813
- output += `${TRUNCATOR}(${String(array.length - array[index] + 1)})`;
1814
- break;
1893
+ /**
1894
+ * Gets all closing escape sequences for the currently active attributes.
1895
+ * The order is generally reverse of application: formatting, foreground, background.
1896
+ * @returns String with all necessary closing escapes.
1897
+ */
1898
+ getEndEscapesForAllActiveAttributes() {
1899
+ const closingEscapes = [];
1900
+ if (this.activeFormatting.length > 0) {
1901
+ const formatResetMap = {
1902
+ "\x1B[1m": "\x1B[22m",
1903
+ // Bold
1904
+ "\x1B[2m": "\x1B[22m",
1905
+ // Faint/Dim (also reset by 22)
1906
+ "\x1B[3m": "\x1B[23m",
1907
+ // Italic
1908
+ "\x1B[4m": "\x1B[24m",
1909
+ // Underline
1910
+ "\x1B[7m": "\x1B[27m",
1911
+ // Inverse
1912
+ "\x1B[8m": "\x1B[28m",
1913
+ // Hidden/Conceal
1914
+ "\x1B[9m": "\x1B[29m"
1915
+ // Strikethrough
1916
+ };
1917
+ [...this.activeFormatting].toReversed().forEach((formatCode) => {
1918
+ const resetCode = formatResetMap[formatCode];
1919
+ if (resetCode) {
1920
+ closingEscapes.push(resetCode);
1921
+ }
1922
+ });
1815
1923
  }
1816
- output += string;
1924
+ if (this.activeForeground) {
1925
+ closingEscapes.push("\x1B[39m");
1926
+ }
1927
+ if (this.activeBackground) {
1928
+ closingEscapes.push("\x1B[49m");
1929
+ }
1930
+ return closingEscapes.join("");
1817
1931
  }
1818
- let propertyContents = "";
1819
- if (nonIndexProperties.length > 0) {
1820
- propertyContents = inspectList(
1821
- nonIndexProperties.map((key) => [key, array[key]]),
1822
- array,
1823
- options,
1824
- inspect2,
1825
- inspectProperty
1826
- );
1932
+ }
1933
+ const checkEscapeSequence = (chars, index) => {
1934
+ if (!ESCAPES.has(chars[index])) {
1935
+ return { isInsideEscape: false, isInsideLinkEscape: false };
1827
1936
  }
1828
- return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
1829
- };
1830
- const constructorMap = /* @__PURE__ */ new WeakMap();
1831
- const stringTagMap = {};
1832
- const baseTypesMap = {
1833
- Arguments: inspectArguments,
1834
- Array: inspectArray,
1835
- ArrayBuffer: () => "",
1836
- BigInt: inspectBigInt,
1837
- bigint: inspectBigInt,
1838
- Boolean: (value, options) => options.stylize(String(value), "boolean"),
1839
- boolean: (value, options) => options.stylize(String(value), "boolean"),
1840
- DataView: () => "",
1841
- Date: inspectDate,
1842
- Error: inspectObject,
1843
- Float32Array: inspectTypedArray,
1844
- Float64Array: inspectTypedArray,
1845
- Function: inspectFunction,
1846
- function: inspectFunction,
1847
- Generator: () => "",
1848
- HTMLCollection: inspectNodeCollection,
1849
- Int8Array: inspectTypedArray,
1850
- Int16Array: inspectTypedArray,
1851
- Int32Array: inspectTypedArray,
1852
- Map: inspectMap,
1853
- NodeList: inspectNodeCollection,
1854
- null: (_value, options) => options.stylize("null", "null"),
1855
- Number: inspectNumber,
1856
- number: inspectNumber,
1857
- Promise: getPromiseValue,
1858
- RegExp: inspectRegExp,
1859
- Set: inspectSet,
1860
- String: inspectString,
1861
- string: inspectString,
1862
- // A Symbol polyfill will return `Symbol` not `symbol` from typedetect
1863
- Symbol: inspectSymbol,
1864
- symbol: inspectSymbol,
1865
- Uint8Array: inspectTypedArray,
1866
- Uint8ClampedArray: inspectTypedArray,
1867
- Uint16Array: inspectTypedArray,
1868
- Uint32Array: inspectTypedArray,
1869
- undefined: (_value, options) => options.stylize("undefined", "undefined"),
1870
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1871
- WeakMap: (_value, options) => options.stylize("WeakMap{…}", "special"),
1872
- // WeakSet, WeakMap are totally opaque to us
1873
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1874
- WeakSet: (_value, options) => options.stylize("WeakSet{…}", "special")
1937
+ const isInsideEscape = true;
1938
+ const possibleLink = chars.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join("");
1939
+ const isInsideLinkEscape = possibleLink === ANSI_ESCAPE_LINK;
1940
+ return { isInsideEscape, isInsideLinkEscape };
1875
1941
  };
1876
- const nodeInspectCustomSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1877
- const inspectCustom = (value, options, type, depth) => {
1878
- if (!("window" in globalThis) && typeof value[nodeInspectCustomSymbol] === "function") {
1879
- return value[nodeInspectCustomSymbol](depth, options);
1880
- }
1881
- if ("inspect" in value && typeof value.inspect === "function") {
1882
- return value.inspect(depth, options);
1942
+ const processAnsiString = (string, options = {}) => {
1943
+ const stateTracker = new AnsiStateTracker();
1944
+ let currentText = "";
1945
+ let isInsideEscape = false;
1946
+ let escapeBuffer = "";
1947
+ let currentUrl = "";
1948
+ let isInHyperlink = false;
1949
+ const chars = [...string];
1950
+ for (let index = 0; index < chars.length; index++) {
1951
+ const character = chars[index];
1952
+ if (character && ESCAPES.has(character)) {
1953
+ if (currentText) {
1954
+ const width2 = options.getWidth?.(currentText) ?? 0;
1955
+ const segment2 = {
1956
+ isEscapeSequence: false,
1957
+ isGrapheme: true,
1958
+ text: currentText,
1959
+ width: width2
1960
+ };
1961
+ if (isInHyperlink) {
1962
+ segment2.isHyperlink = true;
1963
+ segment2.hyperlinkUrl = currentUrl;
1964
+ }
1965
+ if (options.onSegment?.(segment2, stateTracker) === false) {
1966
+ return;
1967
+ }
1968
+ currentText = "";
1969
+ }
1970
+ isInsideEscape = true;
1971
+ escapeBuffer = character;
1972
+ const escapeInfo = checkEscapeSequence(chars, index);
1973
+ const { isInsideLinkEscape } = escapeInfo;
1974
+ if (isInsideLinkEscape) {
1975
+ let urlEnd = index + 1;
1976
+ currentUrl = "";
1977
+ while (urlEnd < chars.length) {
1978
+ const nextChar = chars[urlEnd];
1979
+ if (nextChar === ANSI_ESCAPE_BELL) {
1980
+ break;
1981
+ }
1982
+ currentUrl += nextChar;
1983
+ urlEnd += 1;
1984
+ }
1985
+ currentUrl = currentUrl.slice(4);
1986
+ const segment2 = {
1987
+ hyperlinkUrl: currentUrl,
1988
+ isEscapeSequence: true,
1989
+ isGrapheme: false,
1990
+ isHyperlink: true,
1991
+ isHyperlinkStart: true,
1992
+ width: 0
1993
+ };
1994
+ if (options.onSegment?.(segment2, stateTracker) === false) {
1995
+ return;
1996
+ }
1997
+ index = urlEnd;
1998
+ isInHyperlink = true;
1999
+ isInsideEscape = false;
2000
+ escapeBuffer = "";
2001
+ continue;
2002
+ }
2003
+ if (index + 1 < chars.length && chars[index + 1] === "\\" && isInHyperlink) {
2004
+ const segment2 = {
2005
+ isEscapeSequence: true,
2006
+ isGrapheme: false,
2007
+ isHyperlink: true,
2008
+ isHyperlinkEnd: true,
2009
+ width: 0
2010
+ };
2011
+ if (options.onSegment?.(segment2, stateTracker) === false) {
2012
+ return;
2013
+ }
2014
+ isInHyperlink = false;
2015
+ currentUrl = "";
2016
+ index += 1;
2017
+ isInsideEscape = false;
2018
+ escapeBuffer = "";
2019
+ continue;
2020
+ }
2021
+ }
2022
+ if (isInsideEscape) {
2023
+ if (escapeBuffer !== character) {
2024
+ escapeBuffer += character;
2025
+ }
2026
+ if (character === ANSI_SGR_TERMINATOR) {
2027
+ isInsideEscape = false;
2028
+ stateTracker.processEscape(escapeBuffer);
2029
+ const segment2 = {
2030
+ isEscapeSequence: true,
2031
+ isGrapheme: false,
2032
+ text: escapeBuffer,
2033
+ width: 0
2034
+ };
2035
+ if (options.onSegment?.(segment2, stateTracker) === false) {
2036
+ return;
2037
+ }
2038
+ escapeBuffer = "";
2039
+ }
2040
+ continue;
2041
+ }
2042
+ currentText += character;
2043
+ const width = options.getWidth?.(currentText) ?? 0;
2044
+ const segment = {
2045
+ isEscapeSequence: false,
2046
+ isGrapheme: true,
2047
+ text: currentText,
2048
+ width
2049
+ };
2050
+ if (isInHyperlink) {
2051
+ segment.isHyperlink = true;
2052
+ segment.hyperlinkUrl = currentUrl;
2053
+ }
2054
+ if (options.onSegment?.(segment, stateTracker) === false) {
2055
+ return;
2056
+ }
2057
+ currentText = "";
1883
2058
  }
1884
- if ("constructor" in value && constructorMap.has(value.constructor)) {
1885
- return constructorMap.get(value.constructor)?.(value, options) ?? "unknown";
2059
+ if (currentText) {
2060
+ const width = options.getWidth?.(currentText) ?? 0;
2061
+ const segment = {
2062
+ isEscapeSequence: false,
2063
+ isGrapheme: true,
2064
+ text: currentText,
2065
+ width
2066
+ };
2067
+ if (isInHyperlink) {
2068
+ segment.isHyperlink = true;
2069
+ segment.hyperlinkUrl = currentUrl;
2070
+ }
2071
+ options.onSegment?.(segment, stateTracker);
1886
2072
  }
1887
- const tagInspector = stringTagMap[type];
1888
- if (tagInspector) {
1889
- return tagInspector(value, options);
2073
+ if (escapeBuffer) {
2074
+ const segment = {
2075
+ isEscapeSequence: true,
2076
+ isGrapheme: false,
2077
+ text: escapeBuffer,
2078
+ width: 0
2079
+ };
2080
+ options.onSegment?.(segment, stateTracker);
1890
2081
  }
1891
- return "";
1892
2082
  };
1893
- const internalInspect = (value, options, depth, seen) => {
1894
- if (seen.includes(value)) {
1895
- return "[Circular]";
2083
+ const wrapAnsiCode = (code) => {
2084
+ const escapeChar = ESCAPES.values().next().value;
2085
+ return `${escapeChar}${ANSI_CSI}${String(code)}${ANSI_SGR_TERMINATOR}`;
2086
+ };
2087
+ const wrapAnsiHyperlink = (url) => {
2088
+ const escapeChar = ESCAPES.values().next().value;
2089
+ return `${escapeChar}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
2090
+ };
2091
+ const preserveAnsi = (rawLines) => {
2092
+ if (rawLines.length === 0) {
2093
+ return "";
1896
2094
  }
1897
- if (depth >= options.depth && options.depth > 0 && typeof value === "object") {
1898
- return Array.isArray(value) ? "[Array]" : "[Object]";
2095
+ if (rawLines.length === 1) {
2096
+ return rawLines[0];
1899
2097
  }
1900
- const inspect2 = (object, from, options2) => {
1901
- if (from) {
1902
- seen = [...seen, from];
2098
+ let returnValue = "";
2099
+ let escapeCode;
2100
+ let escapeUrl;
2101
+ const preString = rawLines.join("\n");
2102
+ const pre = [...preString];
2103
+ let preStringIndex = 0;
2104
+ for (const [index, character] of pre.entries()) {
2105
+ returnValue += character;
2106
+ if (ESCAPES.has(character)) {
2107
+ const match = RE_ESCAPE_PATTERN.exec(preString.slice(preStringIndex));
2108
+ const groups = match?.groups ?? {};
2109
+ if (groups.code !== void 0) {
2110
+ const code2 = Number.parseFloat(groups.code);
2111
+ escapeCode = code2 === END_CODE ? void 0 : code2;
2112
+ } else if (groups.uri !== void 0) {
2113
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
2114
+ }
1903
2115
  }
1904
- return internalInspect(object, options2, depth + 1, seen);
1905
- };
1906
- const indent = options.indent ? getIndent(options.indent, depth) : void 0;
1907
- let type = value === null ? "null" : typeof value;
1908
- if (type === "object") {
1909
- type = Object.prototype.toString.call(value).slice(8, -1);
1910
- }
1911
- const baseInspector = baseTypesMap[type];
1912
- if (baseInspector !== void 0) {
1913
- return baseInspector(value, options, inspect2, indent);
1914
- }
1915
- if (options.customInspect && value) {
1916
- const output = inspectCustom(value, options, type, options.depth - depth);
1917
- if (output) {
1918
- if (typeof output === "string") {
1919
- return output;
2116
+ const code = ANSI_RESET_CODES.get(Number(escapeCode));
2117
+ if (pre[index + 1] === "\n") {
2118
+ if (escapeUrl) {
2119
+ returnValue += wrapAnsiHyperlink("");
2120
+ }
2121
+ if (escapeCode && code) {
2122
+ returnValue += wrapAnsiCode(code);
2123
+ }
2124
+ } else if (character === "\n") {
2125
+ if (escapeCode && code) {
2126
+ returnValue += wrapAnsiCode(escapeCode);
2127
+ }
2128
+ if (escapeUrl) {
2129
+ returnValue += wrapAnsiHyperlink(escapeUrl);
1920
2130
  }
1921
- return inspect2(output, value, options);
1922
2131
  }
2132
+ preStringIndex += character.length;
1923
2133
  }
1924
- const proto = value ? Object.getPrototypeOf(value) : false;
1925
- if (proto === Object.prototype || proto === null) {
1926
- return inspectObject$1(value, options, inspect2, indent);
1927
- }
1928
- if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) {
1929
- return inspectHTMLElement(value, value, options, inspect2);
2134
+ return returnValue;
2135
+ };
2136
+ const RE_SPLIT_WHITESPACE = /(?=\s)|(?<=\s)/;
2137
+ const RE_WHITESPACE_ONLY = /^\s+$/;
2138
+ const resetAnsiAtLineBreak = (currentLine) => {
2139
+ if (!currentLine.includes("\x1B")) {
2140
+ return currentLine;
1930
2141
  }
1931
- if ("constructor" in value) {
1932
- if (value.constructor !== Object) {
1933
- return inspectClass(value, options, inspect2, indent);
1934
- }
1935
- return inspectObject$1(value, options, inspect2, indent);
2142
+ let result = currentLine;
2143
+ if (currentLine.includes("\x1B[30m")) {
2144
+ result += "\x1B[39m";
1936
2145
  }
1937
- if (value === Object(value)) {
1938
- return inspectObject$1(value, options, inspect2, indent);
2146
+ if (currentLine.includes("\x1B[42m")) {
2147
+ result += "\x1B[49m";
1939
2148
  }
1940
- return options.stylize(String(value), type);
2149
+ return result;
1941
2150
  };
1942
- const inspect = (value, options_ = {}) => {
1943
- const options = {
1944
- breakLength: Number.POSITIVE_INFINITY,
1945
- customInspect: true,
1946
- depth: 5,
1947
- indent: void 0,
1948
- maxArrayLength: Number.POSITIVE_INFINITY,
1949
- numericSeparator: true,
1950
- quoteStyle: "single",
1951
- showHidden: false,
1952
- showProxy: false,
1953
- stylize: (s) => s,
1954
- truncate: Number.POSITIVE_INFINITY,
1955
- ...options_
1956
- };
1957
- if (options.indent !== void 0 && options.indent !== " " && !(Number.parseInt(options.indent, 10) === options.indent && options.indent > 0)) {
1958
- throw new TypeError('option "indent" must be "\\t", an integer > 0, or `undefined`');
2151
+ const stringVisibleTrimSpacesRight = (string) => {
2152
+ const words = string.split(" ");
2153
+ let last = words.length;
2154
+ while (last > 0 && getStringWidth(words[last - 1]) === 0) {
2155
+ last--;
1959
2156
  }
1960
- return internalInspect(value, options, 0, []);
1961
- };
1962
-
1963
- const writeStream = (data, stream) => {
1964
- const write = stream.__write ?? stream.write.bind(stream);
1965
- return write.call(stream, data);
1966
- };
1967
-
1968
- const normalizeLF = (code) => code.replaceAll(/\r\n|\r(?!\n)|\n/gu, "\n");
1969
- const rawProcess = globalThis.process ?? /* @__PURE__ */ Object.create(null);
1970
- const processShims = {
1971
- versions: {}
1972
- };
1973
- const process$1 = /* @__PURE__ */ new Proxy(rawProcess, {
1974
- get(target, property) {
1975
- if (property in target) {
1976
- return target[property];
1977
- }
1978
- if (property in processShims) {
1979
- return processShims[property];
1980
- }
1981
- return void 0;
2157
+ if (last === words.length) {
2158
+ return string;
1982
2159
  }
1983
- });
1984
- const getMarkerLines = (loc, source, linesAbove, linesBelow) => {
1985
- const startLoc = {
1986
- column: 0,
1987
- // @ts-expect-error Can be overwritten
1988
- line: -1,
1989
- ...loc.start
1990
- };
1991
- const endLoc = {
1992
- ...startLoc,
1993
- ...loc.end
1994
- };
1995
- const startLine = startLoc.line;
1996
- const startColumn = startLoc.column;
1997
- const endLine = endLoc.line;
1998
- const endColumn = endLoc.column;
1999
- let start = Math.max(startLine - (linesAbove + 1), 0);
2000
- let end = Math.min(source.length, endLine + linesBelow);
2001
- if (startLine === -1) {
2002
- start = 0;
2160
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
2161
+ };
2162
+ const wrapWithBreakAtWidth = (string, width, trim) => {
2163
+ if (string.length === 0) {
2164
+ return [""];
2003
2165
  }
2004
- if (endLine === -1) {
2005
- end = source.length;
2166
+ if (width <= 0) {
2167
+ return [string];
2006
2168
  }
2007
- const lineDiff = endLine - startLine;
2008
- const markerLines = {};
2009
- if (lineDiff) {
2010
- for (let index = 0; index <= lineDiff; index++) {
2011
- const lineNumber = index + startLine;
2012
- if (!startColumn) {
2013
- markerLines[lineNumber] = true;
2014
- } else if (index === 0) {
2015
- const sourceLength = source[lineNumber - 1]?.length;
2016
- markerLines[lineNumber] = [startColumn, (sourceLength ?? 0) - startColumn + 1];
2017
- } else if (index === lineDiff) {
2018
- markerLines[lineNumber] = [0, endColumn];
2019
- } else {
2020
- const sourceLength = source[lineNumber - index]?.length;
2021
- markerLines[lineNumber] = [0, sourceLength];
2169
+ const rows = [];
2170
+ const ansiTracker = new AnsiStateTracker();
2171
+ let currentLine = "";
2172
+ let currentWidth = 0;
2173
+ let isInsideEscape = false;
2174
+ let isInsideLinkEscape = false;
2175
+ let escapeBuffer = "";
2176
+ let index = 0;
2177
+ while (index < string.length) {
2178
+ const char = string[index];
2179
+ if (ESCAPES.has(char)) {
2180
+ isInsideEscape = true;
2181
+ escapeBuffer = char;
2182
+ currentLine += char;
2183
+ const escapeInfo = checkEscapeSequence([...string], index);
2184
+ isInsideLinkEscape = escapeInfo.isInsideLinkEscape;
2185
+ index += 1;
2186
+ continue;
2187
+ }
2188
+ if (isInsideEscape) {
2189
+ escapeBuffer += char;
2190
+ currentLine += char;
2191
+ if (isInsideLinkEscape) {
2192
+ if (char === ANSI_ESCAPE_BELL) {
2193
+ isInsideEscape = isInsideLinkEscape = false;
2194
+ }
2195
+ } else if (char === ANSI_SGR_TERMINATOR) {
2196
+ isInsideEscape = false;
2197
+ ansiTracker.processEscape(escapeBuffer);
2198
+ }
2199
+ index += 1;
2200
+ continue;
2201
+ }
2202
+ const charWidth = getStringWidth(char);
2203
+ const isSpace = char === " ";
2204
+ if (charWidth === 0) {
2205
+ currentLine += char;
2206
+ index += 1;
2207
+ continue;
2208
+ }
2209
+ if (currentWidth + charWidth > width) {
2210
+ if (currentLine) {
2211
+ rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
2212
+ }
2213
+ currentLine = ansiTracker.getStartEscapesForAllActiveAttributes();
2214
+ currentWidth = getStringWidth(currentLine);
2215
+ if (isSpace && trim) {
2216
+ while (index < string.length && string[index] === " ") {
2217
+ index += 1;
2218
+ }
2219
+ continue;
2022
2220
  }
2023
2221
  }
2024
- } else if (startColumn === endColumn) {
2025
- markerLines[startLine] = startColumn ? [startColumn, 0] : true;
2026
- } else {
2027
- markerLines[startLine] = [startColumn, (endColumn ?? 0) - (startColumn ?? 0)];
2028
- }
2029
- return { end, markerLines, start };
2030
- };
2031
- const CODE_FRAME_POINTER = process$1.platform === "win32" && !process$1.env?.WT_SESSION ? ">" : "❯";
2032
- const codeFrame = (source, loc, options) => {
2033
- const config = {
2034
- // grab 2 lines before, and 3 lines after focused line
2035
- linesAbove: 2,
2036
- linesBelow: 3,
2037
- prefix: "",
2038
- showGutter: true,
2039
- tabWidth: 4,
2040
- ...options,
2041
- color: {
2042
- gutter: (value) => value,
2043
- marker: (value) => value,
2044
- message: (value) => value,
2045
- ...options?.color
2046
- }
2047
- };
2048
- const hasColumns = typeof loc.start.column === "number";
2049
- let lines = normalizeLF(source).split("\n");
2050
- if (typeof config.tabWidth === "number") {
2051
- lines = lines.map((ln) => ln.replaceAll(" ", " ".repeat(config.tabWidth)));
2052
- }
2053
- const { end, markerLines, start } = getMarkerLines(loc, lines, config.linesAbove, config.linesBelow);
2054
- const numberMaxWidth = String(end).length;
2055
- const { gutter: colorizeGutter, marker: colorizeMarker, message: colorizeMessage } = config.color;
2056
- let frame = lines.slice(start, end).map((line, index) => {
2057
- const number = start + 1 + index;
2058
- const hasMarker = markerLines[number];
2059
- const paddedNumber = ` ${String(number)}`.slice(-numberMaxWidth);
2060
- const lastMarkerLine = !markerLines[number + 1];
2061
- const gutter = ` ${paddedNumber}${config.showGutter ? " |" : ""}`;
2062
- if (hasMarker) {
2063
- let markerLine = "";
2064
- if (Array.isArray(hasMarker)) {
2065
- const markerSpacing = line.replaceAll(/[^\t]/g, " ").slice(0, Math.max(hasMarker[0] - 1, 0));
2066
- const numberOfMarkers = hasMarker[1] || 1;
2067
- markerLine = [
2068
- "\n ",
2069
- config.prefix + colorizeGutter(gutter.replaceAll(/\d/g, " ")),
2070
- " ",
2071
- markerSpacing,
2072
- colorizeMarker("^").repeat(numberOfMarkers)
2073
- ].join("");
2074
- if (lastMarkerLine && config.message) {
2075
- markerLine += ` ${colorizeMessage(config.message)}`;
2222
+ currentLine += char;
2223
+ currentWidth += charWidth;
2224
+ if (currentWidth === width && index < string.length - 1) {
2225
+ rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
2226
+ currentLine = ansiTracker.getStartEscapesForAllActiveAttributes();
2227
+ currentWidth = getStringWidth(currentLine);
2228
+ if (index + 1 < string.length && string[index + 1] === " " && trim) {
2229
+ index += 1;
2230
+ while (index < string.length && string[index] === " ") {
2231
+ index += 1;
2076
2232
  }
2233
+ continue;
2077
2234
  }
2078
- return [config.prefix + colorizeMarker(CODE_FRAME_POINTER), colorizeGutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
2079
2235
  }
2080
- return `${config.prefix} ${colorizeGutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
2081
- }).join("\n");
2082
- if (config.message && !hasColumns) {
2083
- frame = `${config.prefix + " ".repeat(numberMaxWidth + 1) + config.message}
2084
- ${frame}`;
2085
- }
2086
- return frame;
2087
- };
2088
-
2089
- const debugLog = (message, ...arguments_) => {
2090
- if (process.env.DEBUG && process.env.DEBUG === "true") {
2091
- console.debug(`error:parse-stacktrace: ${message}`, ...arguments_);
2236
+ index += 1;
2092
2237
  }
2093
- };
2094
- const UNKNOWN_FUNCTION = "<unknown>";
2095
- const CHROMIUM_REGEX = /^.*?\s*at\s(?:(.+?\)(?:\s\[.+\])?|\(?.*?)\s?\((?:address\sat\s)?)?(?:async\s)?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
2096
- const CHROMIUM_EVAL_REGEX = /\((\S+)\),\s(<[^>]+>)?:(\d+)?:(\d+)?\)?/;
2097
- const CHROMIUM_MAPPED = /(.*?):(\d+):(\d+)(?:\s<-\s.+:\d+:\d+)?/;
2098
- const WINDOWS_EVAL_REGEX = /eval\sat\s(<anonymous>)\s\((.*)\)?:(\d+)?:(\d+)\),\s*<anonymous>?:(\d+)?:(\d+)/;
2099
- const NODE_REGEX = /^\s*in\s(?:([^\\/]+(?:\s\[as\s\S+\])?)\s\(?)?\(at?\s?(.*?):(\d+)(?::(\d+))?\)?\s*$/;
2100
- const NODE_NESTED_REGEX = /in\s(.*)\s\(at\s(.+)\)\sat/;
2101
- const REACT_ANDROID_NATIVE_REGEX = /^(?:.*@)?(.*):(\d+):(\d+)$/;
2102
- const GECKO_REGEX = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. \/=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
2103
- const GECKO_EVAL_REGEX = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
2104
- const FIREFOX_REGEX = /(\S[^\s[]*\[.*\]|.*?)@(.*):(\d+):(\d+)/;
2105
- const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
2106
- const AT_PREFIX_REGEX = /at\s/;
2107
- const CHROMIUM_EVAL_SPLIT_REGEX = /^(\S+):(\d+):(\d+)$|^(\S+):(\d+)$/;
2108
- const TRIM_REGEX = /^\s+|\s+$/g;
2109
- const ERROR_LINE_REGEX = /\S*(?:Error: |AggregateError:)/;
2110
- const ANONYMOUS_FUNCTION_REGEX = /^Anonymous function$/;
2111
- const NODE_LINE_REGEX = /^\s*in\s.*/;
2112
- const CHROMIUM_LINE_REGEX = /^.*?\s*at\s.*/;
2113
- const GECKO_LINE_REGEX = /^.*?\s*@.*|\[native code\]/;
2114
- const extractSafariExtensionDetails = (methodName, url) => {
2115
- const isSafariExtension = methodName.includes("safari-extension");
2116
- const isSafariWebExtension = methodName.includes("safari-web-extension");
2117
- return isSafariExtension || isSafariWebExtension ? [
2118
- methodName.includes("@") ? methodName.split("@")[0] : UNKNOWN_FUNCTION,
2119
- isSafariExtension ? `safari-extension:${url}` : `safari-web-extension:${url}`
2120
- ] : [methodName, url];
2121
- };
2122
- const parseMapped = (trace, maybeMapped) => {
2123
- const match = CHROMIUM_MAPPED.exec(maybeMapped);
2124
- if (match) {
2125
- trace.file = match[1];
2126
- trace.line = +match[2];
2127
- trace.column = +match[3];
2238
+ if (currentLine) {
2239
+ rows.push(currentLine + ansiTracker.getEndEscapesForAllActiveAttributes());
2128
2240
  }
2241
+ return trim ? rows.map((element) => stringVisibleTrimSpacesRight(element)) : rows;
2129
2242
  };
2130
- const parseNode = (line) => {
2131
- const nestedNode = NODE_NESTED_REGEX.exec(line);
2132
- if (nestedNode) {
2133
- debugLog(`parse nested node error stack line: "${line}"`, `found: ${JSON.stringify(nestedNode)}`);
2134
- const split = nestedNode[2].split(":");
2135
- return {
2136
- column: split[2] ? +split[2] : void 0,
2137
- file: split[0],
2138
- line: split[1] ? +split[1] : void 0,
2139
- methodName: nestedNode[1] ?? UNKNOWN_FUNCTION,
2140
- raw: line,
2141
- type: void 0
2142
- };
2243
+ const wrapCharByChar = (string, width, trim) => {
2244
+ if (string.length === 0) {
2245
+ return [];
2143
2246
  }
2144
- const node = NODE_REGEX.exec(line);
2145
- if (node) {
2146
- debugLog(`parse node error stack line: "${line}"`, `found: ${JSON.stringify(node)}`);
2147
- const trace = {
2148
- column: node[4] ? +node[4] : void 0,
2149
- file: node[2] ? node[2].replace(AT_PREFIX_REGEX, "") : void 0,
2150
- line: node[3] ? +node[3] : void 0,
2151
- methodName: node[1] ?? UNKNOWN_FUNCTION,
2152
- raw: line,
2153
- type: line.startsWith("internal") ? "internal" : void 0
2154
- };
2155
- parseMapped(trace, `${node[2]}:${node[3]}:${node[4]}`);
2156
- return trace;
2247
+ const inputToProcess = trim ? string.trim() : string;
2248
+ if (inputToProcess.length === 0) {
2249
+ return [];
2157
2250
  }
2158
- return void 0;
2159
- };
2160
- const parseChromium = (line) => {
2161
- const parts = CHROMIUM_REGEX.exec(line);
2162
- if (parts) {
2163
- debugLog(`parse chrome error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
2164
- const isNative = parts[2]?.startsWith("native");
2165
- const isEval = parts[2]?.startsWith("eval") || parts[1]?.startsWith("eval");
2166
- let evalOrigin;
2167
- let windowsParts;
2168
- if (isEval) {
2169
- const subMatch = CHROMIUM_EVAL_REGEX.exec(line);
2170
- if (subMatch) {
2171
- const split = CHROMIUM_EVAL_SPLIT_REGEX.exec(subMatch[1]);
2172
- if (split) {
2173
- parts[2] = split[4] ?? split[1];
2174
- parts[3] = split[5] ?? split[2];
2175
- parts[4] = split[3];
2176
- } else if (subMatch[2]) {
2177
- parts[2] = subMatch[1];
2178
- }
2179
- if (subMatch[2]) {
2180
- evalOrigin = {
2181
- column: subMatch[4] ? +subMatch[4] : void 0,
2182
- file: subMatch[2],
2183
- line: subMatch[3] ? +subMatch[3] : void 0,
2184
- methodName: "eval",
2185
- raw: line,
2186
- type: "eval"
2187
- };
2188
- }
2251
+ const rows = [];
2252
+ let currentLine = "";
2253
+ let currentWidth = 0;
2254
+ processAnsiString(inputToProcess, {
2255
+ getWidth: getStringWidth,
2256
+ // eslint-disable-next-line sonarjs/cognitive-complexity,sonarjs/no-invariant-returns
2257
+ onSegment: (segment, stateTracker) => {
2258
+ const segText = segment.text ?? "";
2259
+ if (segment.isEscapeSequence) {
2260
+ currentLine += segText;
2189
2261
  } else {
2190
- const windowsSubMatch = WINDOWS_EVAL_REGEX.exec(line);
2191
- if (windowsSubMatch) {
2192
- windowsParts = {
2193
- column: windowsSubMatch[4] ? +windowsSubMatch[4] : void 0,
2194
- file: windowsSubMatch[2],
2195
- line: windowsSubMatch[3] ? +windowsSubMatch[3] : void 0
2196
- };
2197
- evalOrigin = {
2198
- column: windowsSubMatch[6] ? +windowsSubMatch[6] : void 0,
2199
- file: windowsSubMatch[1],
2200
- line: windowsSubMatch[5] ? +windowsSubMatch[5] : void 0,
2201
- methodName: "eval",
2202
- raw: windowsSubMatch[0],
2203
- type: "eval"
2204
- };
2262
+ const isSpace = segText === " ";
2263
+ if (segment.width === 0) {
2264
+ currentLine += segText;
2265
+ return true;
2266
+ }
2267
+ if (currentWidth + segment.width > width) {
2268
+ if (currentLine) {
2269
+ rows.push(currentLine);
2270
+ }
2271
+ currentLine = stateTracker.getStartEscapesForAllActiveAttributes();
2272
+ currentWidth = 0;
2273
+ if (isSpace) {
2274
+ if (trim) {
2275
+ return true;
2276
+ }
2277
+ rows.push(stateTracker.getStartEscapesForAllActiveAttributes() + segText);
2278
+ return true;
2279
+ }
2205
2280
  }
2281
+ currentLine += segText;
2282
+ currentWidth += segment.width;
2283
+ }
2284
+ return true;
2285
+ }
2286
+ });
2287
+ if (currentLine) {
2288
+ rows.push(currentLine);
2289
+ }
2290
+ return trim ? rows.map((row) => stringVisibleTrimSpacesRight(row)) : rows;
2291
+ };
2292
+ const wrapWithWordBoundaries = (string, width, trim) => {
2293
+ if (string.length === 0) {
2294
+ return [];
2295
+ }
2296
+ const inputToProcess = trim ? string.trim() : string;
2297
+ if (inputToProcess.length === 0) {
2298
+ return [];
2299
+ }
2300
+ const tokens = inputToProcess.split(RE_SPLIT_WHITESPACE);
2301
+ const rows = [];
2302
+ let currentLine = "";
2303
+ let currentWidth = 0;
2304
+ let index = 0;
2305
+ while (index < tokens.length) {
2306
+ const token = tokens[index];
2307
+ const isSpace = RE_WHITESPACE_ONLY.test(token);
2308
+ const tokenVisibleWidth = getStringWidth(token);
2309
+ if (token.length === 0) {
2310
+ index += 1;
2311
+ continue;
2312
+ }
2313
+ if (trim && isSpace && currentWidth === 0) {
2314
+ index += 1;
2315
+ continue;
2316
+ }
2317
+ if (currentWidth + tokenVisibleWidth > width && currentWidth > 0) {
2318
+ if (trim) {
2319
+ rows.push(stringVisibleTrimSpacesRight(currentLine));
2320
+ } else {
2321
+ rows.push(currentLine);
2206
2322
  }
2323
+ currentLine = "";
2324
+ currentWidth = 0;
2325
+ continue;
2207
2326
  }
2208
- const [methodName, file] = extractSafariExtensionDetails(
2209
- // Normalize IE's 'Anonymous function'
2210
- parts[1] ? parts[1].replace(ANONYMOUS_FUNCTION_REGEX, "<anonymous>") : UNKNOWN_FUNCTION,
2211
- parts[2]
2212
- );
2213
- const trace = {
2214
- column: parts[4] ? +parts[4] : void 0,
2215
- evalOrigin,
2216
- file,
2217
- line: parts[3] ? +parts[3] : void 0,
2218
- methodName,
2219
- raw: line,
2220
- // eslint-disable-next-line sonarjs/no-nested-conditional
2221
- type: isEval ? "eval" : isNative ? "native" : void 0
2222
- };
2223
- if (windowsParts) {
2224
- trace.column = windowsParts.column;
2225
- trace.file = windowsParts.file;
2226
- trace.line = windowsParts.line;
2327
+ currentLine += token;
2328
+ currentWidth += tokenVisibleWidth;
2329
+ index += 1;
2330
+ }
2331
+ if (currentLine) {
2332
+ if (trim) {
2333
+ rows.push(stringVisibleTrimSpacesRight(currentLine));
2227
2334
  } else {
2228
- parseMapped(trace, `${file}:${parts[3]}:${parts[4]}`);
2335
+ rows.push(currentLine);
2229
2336
  }
2230
- return trace;
2231
2337
  }
2232
- return void 0;
2338
+ return rows;
2233
2339
  };
2234
- const parseGecko = (line, topFrameMeta) => {
2235
- const parts = GECKO_REGEX.exec(line);
2236
- if (parts) {
2237
- debugLog(`parse gecko error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
2238
- const isEval = parts[3]?.includes(" > eval");
2239
- const subMatch = isEval && parts[3] && GECKO_EVAL_REGEX.exec(parts[3]);
2240
- let evalOrigin;
2241
- if (isEval && subMatch) {
2242
- parts[3] = subMatch[1];
2243
- evalOrigin = {
2244
- column: parts[5] ? +parts[5] : void 0,
2245
- file: parts[3],
2246
- line: parts[4] ? +parts[4] : void 0,
2247
- methodName: "eval",
2248
- raw: line,
2249
- type: "eval"
2250
- };
2251
- parts[4] = subMatch[2];
2340
+ const wrapAndBreakWords = (string, width, trim) => {
2341
+ if (string.length === 0) {
2342
+ return [];
2343
+ }
2344
+ const inputToProcess = trim ? string.trim() : string;
2345
+ if (inputToProcess.length === 0) {
2346
+ return [];
2347
+ }
2348
+ const tokens = inputToProcess.split(RE_SPLIT_WHITESPACE);
2349
+ const rows = [];
2350
+ let currentLine = "";
2351
+ let currentWidth = 0;
2352
+ let index = 0;
2353
+ while (index < tokens.length) {
2354
+ const token = tokens[index];
2355
+ const isSpace = RE_WHITESPACE_ONLY.test(token);
2356
+ const tokenVisibleWidth = getStringWidth(token);
2357
+ if (token.length === 0) {
2358
+ index += 1;
2359
+ continue;
2252
2360
  }
2253
- const [methodName, file] = extractSafariExtensionDetails(
2254
- // Normalize IE's 'Anonymous function'
2255
- parts[1] ? parts[1].replace(ANONYMOUS_FUNCTION_REGEX, "<anonymous>") : UNKNOWN_FUNCTION,
2256
- parts[3]
2257
- );
2258
- let column;
2259
- if ((topFrameMeta?.type === "safari" || !isEval && topFrameMeta?.type === "firefox") && topFrameMeta.column) {
2260
- column = topFrameMeta.column;
2261
- } else if (!isEval && parts[5]) {
2262
- column = +parts[5];
2361
+ if (trim && isSpace && currentWidth === 0) {
2362
+ index += 1;
2363
+ continue;
2263
2364
  }
2264
- let lineNumber;
2265
- if ((topFrameMeta?.type === "safari" || !isEval && topFrameMeta?.type === "firefox") && topFrameMeta.line) {
2266
- lineNumber = topFrameMeta.line;
2267
- } else if (parts[4]) {
2268
- lineNumber = +parts[4];
2365
+ if (tokenVisibleWidth > width) {
2366
+ if (currentLine) {
2367
+ rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
2368
+ }
2369
+ const brokenLines = wrapWithBreakAtWidth(token, width, trim);
2370
+ if (brokenLines.length > 0) {
2371
+ for (let brokenLineIndex = 0; brokenLineIndex < brokenLines.length - 1; brokenLineIndex += 1) {
2372
+ rows.push(brokenLines[brokenLineIndex]);
2373
+ }
2374
+ currentLine = brokenLines.at(-1);
2375
+ currentWidth = getStringWidth(currentLine);
2376
+ } else {
2377
+ currentLine = "";
2378
+ currentWidth = 0;
2379
+ }
2380
+ index += 1;
2381
+ continue;
2269
2382
  }
2270
- return {
2271
- column,
2272
- evalOrigin,
2273
- file,
2274
- line: lineNumber,
2275
- methodName,
2276
- raw: line,
2277
- // eslint-disable-next-line sonarjs/no-nested-conditional
2278
- type: isEval ? "eval" : file.includes("[native code]") ? "native" : void 0
2279
- };
2383
+ if (currentWidth + tokenVisibleWidth > width && currentWidth > 0) {
2384
+ rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
2385
+ currentLine = "";
2386
+ currentWidth = 0;
2387
+ if (trim && isSpace) {
2388
+ index += 1;
2389
+ continue;
2390
+ }
2391
+ }
2392
+ currentLine += token;
2393
+ currentWidth += tokenVisibleWidth;
2394
+ index += 1;
2280
2395
  }
2281
- return void 0;
2282
- };
2283
- const parseFirefox = (line, topFrameMeta) => {
2284
- const parts = FIREFOX_REGEX.exec(line);
2285
- const isEval = parts ? parts[2].includes(" > eval") : false;
2286
- if (!isEval && parts) {
2287
- debugLog(`parse firefox error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
2288
- return {
2289
- column: parts[4] ? +parts[4] : topFrameMeta?.column ?? void 0,
2290
- file: parts[2],
2291
- line: parts[3] ? +parts[3] : topFrameMeta?.line ?? void 0,
2292
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- intentionally using || to treat empty string as unknown
2293
- methodName: parts[1] || UNKNOWN_FUNCTION,
2294
- raw: line,
2295
- type: void 0
2296
- };
2396
+ if (currentLine) {
2397
+ rows.push(resetAnsiAtLineBreak(trim ? stringVisibleTrimSpacesRight(currentLine) : currentLine));
2297
2398
  }
2298
- return void 0;
2399
+ return rows;
2299
2400
  };
2300
- const parseReactAndroidNative = (line) => {
2301
- const parts = REACT_ANDROID_NATIVE_REGEX.exec(line);
2302
- if (parts) {
2303
- debugLog(`parse react android native error stack line: "${line}"`, `found: ${JSON.stringify(parts)}`);
2304
- return {
2305
- column: parts[3] ? +parts[3] : void 0,
2306
- file: parts[1],
2307
- line: parts[2] ? +parts[2] : void 0,
2308
- methodName: UNKNOWN_FUNCTION,
2309
- raw: line,
2310
- type: void 0
2311
- };
2312
- }
2313
- return void 0;
2401
+ const WrapMode = {
2402
+ /**
2403
+ * Breaks words at character boundaries to fit the width
2404
+ */
2405
+ BREAK_AT_CHARACTERS: "BREAK_AT_CHARACTERS",
2406
+ /**
2407
+ * Breaks lines at word boundaries. If a word is longer than the width, it will be broken.
2408
+ */
2409
+ BREAK_WORDS: "BREAK_WORDS",
2410
+ /**
2411
+ * Preserves word boundaries, words are kept intact even if they exceed width
2412
+ */
2413
+ PRESERVE_WORDS: "PRESERVE_WORDS",
2414
+ /**
2415
+ * Enforces strict adherence to the width limit by breaking at exact width
2416
+ */
2417
+ STRICT_WIDTH: "STRICT_WIDTH"
2314
2418
  };
2315
- const parseStacktrace = (error, { filter, frameLimit = 50 } = {}) => {
2316
- const errorRecord = error;
2317
- const rawStack = typeof errorRecord.stacktrace === "string" ? errorRecord.stacktrace : error.stack ?? "";
2318
- let lines = rawStack.split("\n").map((line) => {
2319
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
2320
- return cleanedLine.replaceAll(TRIM_REGEX, "");
2321
- }).filter((line) => !ERROR_LINE_REGEX.test(line) && line !== "eval code");
2322
- if (filter) {
2323
- lines = lines.filter((element) => filter(element));
2419
+ const wordWrap = (string, options = {}) => {
2420
+ const { removeZeroWidthCharacters = true, trim = true, width = 80, wrapMode = WrapMode.PRESERVE_WORDS } = options;
2421
+ if (trim && string.trim() === "") {
2422
+ return "";
2324
2423
  }
2325
- lines = lines.slice(0, frameLimit);
2326
- return lines.reduce((stack, line, currentIndex) => {
2327
- if (!line) {
2328
- return stack;
2329
- }
2330
- if (line.length > 1024) {
2331
- return stack;
2424
+ let normalizedString = string.normalize("NFC").replaceAll("\r\n", "\n");
2425
+ if (removeZeroWidthCharacters) {
2426
+ normalizedString = normalizedString.replaceAll(RE_ZERO_WIDTH, "");
2427
+ }
2428
+ const result = normalizedString.split("\n").map((line) => {
2429
+ if (trim && line.trim() === "") {
2430
+ return "";
2332
2431
  }
2333
- let parseResult;
2334
- if (NODE_LINE_REGEX.test(line)) {
2335
- parseResult = parseNode(line);
2336
- } else if (CHROMIUM_LINE_REGEX.test(line)) {
2337
- parseResult = parseChromium(line);
2338
- } else if (GECKO_LINE_REGEX.test(line)) {
2339
- let topFrameMeta;
2340
- if (currentIndex === 0) {
2341
- const browserError = error;
2342
- const columnNumber = browserError.columnNumber;
2343
- const lineNumber = browserError.lineNumber;
2344
- const safariLine = browserError.line;
2345
- const safariColumn = browserError.column;
2346
- if (columnNumber || lineNumber) {
2347
- topFrameMeta = {
2348
- column: columnNumber,
2349
- line: lineNumber,
2350
- type: "firefox"
2351
- };
2352
- } else if (safariLine || safariColumn) {
2353
- topFrameMeta = {
2354
- column: safariColumn,
2355
- line: safariLine,
2356
- type: "safari"
2357
- };
2358
- }
2432
+ let wrappedLines;
2433
+ switch (wrapMode) {
2434
+ case WrapMode.BREAK_AT_CHARACTERS: {
2435
+ wrappedLines = wrapCharByChar(line, width, trim);
2436
+ break;
2437
+ }
2438
+ case WrapMode.BREAK_WORDS: {
2439
+ wrappedLines = wrapAndBreakWords(line, width, trim);
2440
+ break;
2441
+ }
2442
+ case WrapMode.STRICT_WIDTH: {
2443
+ wrappedLines = wrapWithBreakAtWidth(line, width, trim);
2444
+ break;
2445
+ }
2446
+ default: {
2447
+ wrappedLines = wrapWithWordBoundaries(line, width, trim);
2359
2448
  }
2360
- parseResult = parseFirefox(line, topFrameMeta) ?? parseGecko(line, topFrameMeta);
2361
- } else {
2362
- parseResult = parseReactAndroidNative(line);
2363
- }
2364
- if (parseResult) {
2365
- stack.push(parseResult);
2366
- } else {
2367
- debugLog(`parse error stack line: "${line}"`, "not parser found");
2368
2449
  }
2369
- return stack;
2370
- }, []);
2450
+ return preserveAnsi(wrappedLines);
2451
+ });
2452
+ return result.join("\n");
2371
2453
  };
2372
2454
 
2373
- const {
2374
- existsSync,
2375
- readFileSync
2376
- } = __cjs_getBuiltinModule("node:fs");
2377
- const {
2378
- relative
2379
- } = __cjs_getBuiltinModule("node:path");
2380
- const {
2381
- cwd
2382
- } = __cjs_getProcess;
2383
- const {
2384
- fileURLToPath
2385
- } = __cjs_getBuiltinModule("node:url");
2386
- const getPrefix = (prefix, indentation, deep) => {
2387
- if (deep === 0) {
2388
- return prefix;
2389
- }
2390
- if (indentation === " ") {
2391
- return prefix + " ".repeat(deep);
2455
+ const defaultColumns = 80;
2456
+ const defaultRows = 24;
2457
+ const exec = (command, arguments_, { shell, env } = {}) => execFileSync(command, arguments_, {
2458
+ encoding: "utf8",
2459
+ stdio: ["ignore", "pipe", "ignore"],
2460
+ timeout: 500,
2461
+ shell,
2462
+ env
2463
+ }).trim();
2464
+ const create = (columns, rows) => ({
2465
+ columns: Number.parseInt(columns, 10),
2466
+ rows: Number.parseInt(rows, 10)
2467
+ });
2468
+ const createIfNotDefault = (maybeColumns, maybeRows) => {
2469
+ const { columns, rows } = create(maybeColumns, maybeRows);
2470
+ if (Number.isNaN(columns) || Number.isNaN(rows)) {
2471
+ return;
2392
2472
  }
2393
- return prefix + " ".repeat(indentation * deep);
2394
- };
2395
- const getRelativePath = (filePath, cwdPath) => {
2396
- const path = filePath.replace("async file:", "file:");
2397
- return relative(cwdPath, path.startsWith("file:") ? fileURLToPath(path) : path);
2398
- };
2399
- const getTitleText = (error, hideErrorTitle, color) => {
2400
- if (hideErrorTitle) {
2401
- return color.title(error.message);
2473
+ if (columns === defaultColumns && rows === defaultRows) {
2474
+ return;
2402
2475
  }
2403
- const messagePart = error.message ? `: ${error.message}` : "";
2404
- return color.title(error.name + messagePart);
2476
+ return { columns, rows };
2405
2477
  };
2406
- const getMessage = (error, { color, hideErrorTitle, indentation, prefix }, deep) => `${getPrefix(prefix, indentation, deep)}${getTitleText(error, hideErrorTitle, color)}
2407
- `;
2408
- const getHint = (error, { color, indentation, prefix }, deep) => {
2409
- if (error.hint === void 0) {
2410
- return void 0;
2478
+ const isForegroundProcess = () => {
2479
+ if (process$2.platform !== "linux") {
2480
+ return true;
2411
2481
  }
2412
- const spaces = getPrefix(prefix, indentation, deep);
2413
- let message = "";
2414
- if (Array.isArray(error.hint)) {
2415
- for (const line of error.hint) {
2416
- message += `${spaces + line}
2417
- `;
2482
+ try {
2483
+ const statContents = fs.readFileSync("/proc/self/stat", "utf8");
2484
+ const closingParenthesisIndex = statContents.lastIndexOf(") ");
2485
+ if (closingParenthesisIndex === -1) {
2486
+ return false;
2418
2487
  }
2419
- } else {
2420
- message += spaces + error.hint;
2488
+ const statFields = statContents.slice(closingParenthesisIndex + 2).trim().split(/\s+/);
2489
+ const processGroupId = Number.parseInt(statFields[2], 10);
2490
+ const foregroundProcessGroupId = Number.parseInt(statFields[5], 10);
2491
+ if (Number.isNaN(processGroupId) || Number.isNaN(foregroundProcessGroupId)) {
2492
+ return false;
2493
+ }
2494
+ if (foregroundProcessGroupId <= 0) {
2495
+ return false;
2496
+ }
2497
+ return processGroupId === foregroundProcessGroupId;
2498
+ } catch {
2499
+ return false;
2421
2500
  }
2422
- return color.hint(message);
2423
2501
  };
2424
- const getMainFrame = (trace, { color, cwd: cwdPath, displayShortPath, indentation, prefix }, deep = 0) => {
2425
- const filePath = displayShortPath ? getRelativePath(trace.file, cwdPath) : trace.file;
2426
- const { fileLine, method } = color;
2427
- return `${getPrefix(prefix, indentation, deep)}at ${trace.methodName ? `${method(trace.methodName)} ` : ""}${fileLine(filePath)}:${fileLine(
2428
- trace.line?.toString() ?? ""
2429
- )}`;
2430
- };
2431
- const getCode = (trace, { color, indentation, linesAbove, linesBelow, prefix, showGutter, showLineNumbers, tabWidth }, deep) => {
2432
- if (trace.file === void 0) {
2433
- return void 0;
2502
+ function terminalSize() {
2503
+ const { env, stdout, stderr } = process$2;
2504
+ if (stdout?.columns && stdout?.rows) {
2505
+ return create(stdout.columns, stdout.rows);
2434
2506
  }
2435
- const filePath = trace.file.replace("file://", "");
2436
- if (!existsSync(filePath)) {
2437
- return void 0;
2507
+ if (stderr?.columns && stderr?.rows) {
2508
+ return create(stderr.columns, stderr.rows);
2438
2509
  }
2439
- const fileContent = readFileSync(filePath, "utf8");
2440
- return codeFrame(
2441
- fileContent,
2442
- {
2443
- start: { column: trace.column, line: trace.line }
2444
- },
2445
- { color, linesAbove, linesBelow, prefix: getPrefix(prefix, indentation, deep), showGutter, showLineNumbers, tabWidth }
2446
- );
2447
- };
2448
- const getErrors = (error, options, deep) => {
2449
- if (error.errors.length === 0) {
2450
- return void 0;
2510
+ if (env.COLUMNS && env.LINES) {
2511
+ return create(env.COLUMNS, env.LINES);
2451
2512
  }
2452
- let message = `${getPrefix(options.prefix, options.indentation, deep)}Errors:
2453
-
2454
- `;
2455
- let first = true;
2456
- for (const error_ of error.errors) {
2457
- if (first) {
2458
- first = false;
2459
- } else {
2460
- message += "\n\n";
2461
- }
2462
- message += internalRenderError(error_, { ...options, framesMaxLimit: 1, hideErrorCodeView: options.hideErrorErrorsCodeView }, deep + 1);
2513
+ const fallback = {
2514
+ columns: defaultColumns,
2515
+ rows: defaultRows
2516
+ };
2517
+ if (process$2.platform === "win32") {
2518
+ return tput() ?? fallback;
2463
2519
  }
2464
- return `
2465
- ${message}`;
2466
- };
2467
- const getCause = (error, options, deep) => {
2468
- let message = `${getPrefix(options.prefix, options.indentation, deep)}Caused by:
2469
-
2470
- `;
2471
- const cause = error.cause;
2472
- message += getMessage(cause, options, deep);
2473
- const stacktrace = parseStacktrace(cause);
2474
- const mainFrame = stacktrace.shift();
2475
- const hint = getHint(cause, options, deep);
2476
- if (hint) {
2477
- message += `${hint}
2478
- `;
2520
+ if (process$2.platform === "darwin") {
2521
+ return devTty() ?? tput() ?? fallback;
2479
2522
  }
2480
- if (mainFrame) {
2481
- message += getMainFrame(mainFrame, options, deep);
2482
- if (!options.hideErrorCauseCodeView) {
2483
- const code = getCode(mainFrame, options, deep);
2484
- if (code !== void 0) {
2485
- message += `
2486
- ${code}`;
2487
- }
2488
- }
2523
+ return devTty() ?? tput() ?? resize() ?? fallback;
2524
+ }
2525
+ const devTty = () => {
2526
+ try {
2527
+ const flags = process$2.platform === "darwin" ? fs.constants.O_EVTONLY | fs.constants.O_NONBLOCK : fs.constants.O_NONBLOCK;
2528
+ const { columns, rows } = tty.WriteStream(fs.openSync("/dev/tty", flags));
2529
+ return { columns, rows };
2530
+ } catch {
2489
2531
  }
2490
- if (cause.cause) {
2491
- message += `
2492
- ${getCause(cause, options, deep + 1)}`;
2493
- } else if (cause instanceof AggregateError) {
2494
- const errors = getErrors(cause, options, deep);
2495
- if (errors !== void 0) {
2496
- message += `
2497
- ${errors}`;
2532
+ };
2533
+ const tput = () => {
2534
+ try {
2535
+ const columns = exec("tput", ["cols"], { env: { TERM: "dumb", ...process$2.env } });
2536
+ const rows = exec("tput", ["lines"], { env: { TERM: "dumb", ...process$2.env } });
2537
+ if (columns && rows) {
2538
+ return createIfNotDefault(columns, rows);
2498
2539
  }
2540
+ } catch {
2499
2541
  }
2500
- return `
2501
- ${message}`;
2502
2542
  };
2503
- const getStacktrace = (stack, options) => (stack.length > 0 ? "\n" : "") + stack.map((frame) => getMainFrame(frame, options)).join("\n");
2504
- const internalRenderError = (error, options, deep) => {
2505
- const config = {
2506
- cwd: cwd(),
2507
- displayShortPath: false,
2508
- filterStacktrace: void 0,
2509
- framesMaxLimit: Number.POSITIVE_INFINITY,
2510
- hideErrorCauseCodeView: false,
2511
- hideErrorCodeView: false,
2512
- hideErrorErrorsCodeView: false,
2513
- hideErrorTitle: false,
2514
- hideMessage: false,
2515
- indentation: 4,
2516
- linesAbove: 2,
2517
- linesBelow: 3,
2518
- prefix: "",
2519
- showGutter: true,
2520
- showLineNumbers: true,
2521
- tabWidth: 4,
2522
- ...options,
2523
- color: {
2524
- fileLine: (value) => value,
2525
- gutter: (value) => value,
2526
- hint: (value) => value,
2527
- marker: (value) => value,
2528
- message: (value) => value,
2529
- method: (value) => value,
2530
- title: (value) => value,
2531
- ...options.color
2543
+ const resize = () => {
2544
+ try {
2545
+ if (!isForegroundProcess()) {
2546
+ return;
2532
2547
  }
2533
- };
2534
- const stack = parseStacktrace(error, {
2535
- filter: options.filterStacktrace,
2536
- frameLimit: config.framesMaxLimit
2537
- });
2538
- const mainFrame = stack.shift();
2539
- return [
2540
- options.hideMessage ? void 0 : getMessage(error, config, deep),
2541
- getHint(error, config, deep),
2542
- mainFrame ? getMainFrame(mainFrame, config, deep) : void 0,
2543
- mainFrame && !config.hideErrorCodeView ? getCode(mainFrame, config, deep) : void 0,
2544
- error instanceof AggregateError ? getErrors(error, config, deep) : void 0,
2545
- error.cause === void 0 ? void 0 : getCause(error, config, deep),
2546
- stack.length > 0 ? getStacktrace(stack, config) : void 0
2547
- ].filter(Boolean).join("\n").replaceAll("\\", "/");
2548
- };
2549
- const renderError = (error, options = {}) => {
2550
- if (options.framesMaxLimit !== void 0 && options.framesMaxLimit <= 0) {
2551
- throw new RangeError("The 'framesMaxLimit' option must be a positive number");
2548
+ const size = exec("resize", ["-u"]).match(/\d+/g);
2549
+ if (size.length === 2) {
2550
+ return createIfNotDefault(size[0], size[1]);
2551
+ }
2552
+ } catch {
2552
2553
  }
2553
- return internalRenderError(error, options, 0);
2554
2554
  };
2555
2555
 
2556
2556
  const getLongestBadge = (types) => {
@@ -2561,6 +2561,7 @@ const getLongestBadge = (types) => {
2561
2561
  return badges.reduce((x, y) => x.length > y.length ? x : y, "");
2562
2562
  };
2563
2563
 
2564
+ const { bold: bold$1, cyan, green, grey, magenta, red, yellow } = colorize;
2564
2565
  const defaultInspectorConfig = {
2565
2566
  indent: 2,
2566
2567
  quoteStyle: "single",
@@ -2569,7 +2570,7 @@ const defaultInspectorConfig = {
2569
2570
  bigint: yellow,
2570
2571
  boolean: yellow,
2571
2572
  date: magenta,
2572
- null: bold,
2573
+ null: bold$1,
2573
2574
  number: yellow,
2574
2575
  regexp: red,
2575
2576
  special: cyan,
@@ -2577,13 +2578,14 @@ const defaultInspectorConfig = {
2577
2578
  symbol: green,
2578
2579
  undefined: grey
2579
2580
  };
2580
- if (styles[style] === void 0) {
2581
+ if (!Object.hasOwn(styles, style)) {
2581
2582
  return string_;
2582
2583
  }
2583
2584
  return styles[style](string_);
2584
2585
  }
2585
2586
  };
2586
2587
 
2588
+ const { bold, underline } = colorize;
2587
2589
  const formatLabel = (label, styles) => {
2588
2590
  let formattedLabel = styles.uppercase.label ? label.toUpperCase() : label;
2589
2591
  formattedLabel = styles.underline.label ? underline(formattedLabel) : formattedLabel;
@@ -2632,4 +2634,4 @@ class AbstractPrettyReporter {
2632
2634
  }
2633
2635
  }
2634
2636
 
2635
- export { AbstractPrettyReporter as A, EXTENDED_RFC_5424_LOG_LEVELS as E, LOG_TYPES as L, WrapMode as W, EMPTY_SYMBOL as a, writeStream as b, getLongestBadge as c, defaultInspectorConfig as d, getStringWidth as e, formatLabel as f, getLongestLabel as g, inspect as i, renderError as r, terminalSize as t, wordWrap as w };
2637
+ export { AbstractPrettyReporter as A, EXTENDED_RFC_5424_LOG_LEVELS as E, LOG_TYPES as L, WrapMode as W, EMPTY_SYMBOL as a, getLongestBadge as b, getStringWidth as c, defaultInspectorConfig as d, wordWrap as e, formatLabel as f, getLongestLabel as g, inspect as i, renderError as r, terminalSize as t, writeStream as w };