@nomicfoundation/hardhat-utils 3.0.3 → 3.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,260 @@
1
+ import type { TableItemV2 } from "../format.js";
2
+
3
+ /**
4
+ * Calculate the display width of a string by removing ANSI escape codes.
5
+ *
6
+ * NOTE: This implementation only removes basic ANSI color/style codes and may
7
+ * not handle all escape sequences (e.g., cursor movement, complex control
8
+ * sequences).
9
+ */
10
+ export function getStringWidth(str: string): number {
11
+ // Remove ANSI escape codes if present
12
+ const stripped = str.replace(/\u001b\[[0-9;]*m/g, "");
13
+ return stripped.length;
14
+ }
15
+
16
+ /**
17
+ * Calculates the minimum width needed by each column in the table
18
+ * to fit its content (accounting for ANSI color codes).
19
+ */
20
+ export function getColumnWidths(items: TableItemV2[]): number[] {
21
+ const columnWidths: number[] = [];
22
+
23
+ for (const item of items) {
24
+ if (item.type === "row" || item.type === "header") {
25
+ item.cells.forEach((cell, i) => {
26
+ columnWidths[i] = Math.max(columnWidths[i] ?? 0, getStringWidth(cell));
27
+ });
28
+ }
29
+ }
30
+
31
+ return columnWidths;
32
+ }
33
+
34
+ /**
35
+ * Calculates the inner width needed to fit the rows and headers
36
+ * (excludes borders, which are added during rendering).
37
+ *
38
+ * Each column is padded by 1 space on each side, and columns are
39
+ * separated by " │ " (3 spaces).
40
+ */
41
+ export function getContentWidth(columnWidths: number[]): number {
42
+ return (
43
+ columnWidths.reduce((sum, w) => sum + w, 0) +
44
+ (columnWidths.length - 1) * 3 +
45
+ 2
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Calculates the inner width needed to fit titles and section headers
51
+ * (excludes borders, which are added during rendering).
52
+ *
53
+ * Each title/header is padded by 1 space on each side.
54
+ * Accounts for ANSI color codes.
55
+ */
56
+ export function getHeadingWidth(items: TableItemV2[]): number {
57
+ let headingWidth = 0;
58
+ for (const item of items) {
59
+ if (item.type === "section-header" || item.type === "title") {
60
+ headingWidth = Math.max(headingWidth, getStringWidth(item.text) + 2);
61
+ }
62
+ }
63
+ return headingWidth;
64
+ }
65
+
66
+ /**
67
+ * Calculates the width needed for unused columns when a row/header has fewer
68
+ * cells than the total column count (e.g., if table has 6 columns but row
69
+ * only has 2 cells, calculates space for the remaining 4 columns).
70
+ */
71
+ export function getUnusedColumnsWidth(
72
+ columnWidths: number[],
73
+ previousCellCount: number,
74
+ ): number {
75
+ const remainingWidths = columnWidths.slice(previousCellCount);
76
+ return remainingWidths.reduce((sum, w) => sum + w + 3, 0) - 3;
77
+ }
78
+
79
+ /**
80
+ * Renders a horizontal rule segment by repeating a character for each column
81
+ * with padding, joined by a separator (e.g., "─────┼─────┼─────").
82
+ */
83
+ export function renderRuleSegment(
84
+ columnWidths: number[],
85
+ char: string,
86
+ joiner: string,
87
+ ): string {
88
+ return columnWidths.map((w) => char.repeat(w + 2)).join(joiner);
89
+ }
90
+
91
+ /**
92
+ * Renders a complete horizontal rule with left and right borders
93
+ * (e.g., "╟─────┼─────┼─────╢").
94
+ */
95
+ export function renderHorizontalRule(
96
+ leftBorder: string,
97
+ columnWidths: number[],
98
+ char: string,
99
+ joiner: string,
100
+ rightBorder: string,
101
+ ): string {
102
+ return (
103
+ leftBorder + renderRuleSegment(columnWidths, char, joiner) + rightBorder
104
+ );
105
+ }
106
+
107
+ /**
108
+ * Renders a content line containing cells from either a header or row.
109
+ *
110
+ * Handles two cases:
111
+ * - Full width: When all columns are used, cells are separated by " │ " and
112
+ * line ends with " ║" (e.g., "║ cell1 │ cell2 │ cell3 ║")
113
+ * - Short line: When fewer columns are used, active cells are followed by
114
+ * " │ " and empty space, ending with "║" (e.g., "║ cell1 │ cell2 │ ║")
115
+ *
116
+ * Accounts for ANSI color codes when padding cells.
117
+ */
118
+ export function renderContentLine(
119
+ cells: string[],
120
+ columnWidths: number[],
121
+ currentCellCount: number,
122
+ ): string {
123
+ if (currentCellCount === columnWidths.length) {
124
+ return (
125
+ "║ " +
126
+ cells
127
+ .map((cell, j) => {
128
+ const displayWidth = getStringWidth(cell);
129
+ const actualLength = cell.length;
130
+ // Adjust padding to account for ANSI escape codes
131
+ return cell.padEnd(columnWidths[j] + actualLength - displayWidth);
132
+ })
133
+ .join(" │ ") +
134
+ " ║"
135
+ );
136
+ } else {
137
+ const usedWidths = columnWidths.slice(0, currentCellCount);
138
+ const remainingWidth = getUnusedColumnsWidth(
139
+ columnWidths,
140
+ currentCellCount,
141
+ );
142
+ return (
143
+ "║ " +
144
+ cells
145
+ .map((cell, j) => {
146
+ const displayWidth = getStringWidth(cell);
147
+ const actualLength = cell.length;
148
+ // Adjust padding to account for ANSI escape codes
149
+ return cell.padEnd(usedWidths[j] + actualLength - displayWidth);
150
+ })
151
+ .join(" │ ") +
152
+ " │ " +
153
+ " ".repeat(remainingWidth + 1) +
154
+ "║"
155
+ );
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Renders the horizontal rule that appears above a header row.
161
+ *
162
+ * Handles three cases:
163
+ * - Transition rule: When going from more columns to fewer, shows ┴ marks
164
+ * where columns collapse (e.g., "╟───┼───┼───┴───┴───╢")
165
+ * - Full width: When header uses all columns (e.g., "╟───┬───┬───╢" or "╟───┼───┼───╢")
166
+ * - Short header: When header uses fewer columns than max (e.g., "╟───┬─────────╢")
167
+ *
168
+ * The innerJoiner determines the separator character: ┬ after section-header, ┼ otherwise.
169
+ */
170
+ export function renderHeaderOpen(
171
+ columnWidths: number[],
172
+ currentCellCount: number,
173
+ innerJoiner: string,
174
+ needsTransition: boolean,
175
+ ): string {
176
+ if (needsTransition) {
177
+ const usedWidths = columnWidths.slice(0, currentCellCount);
178
+ const collapsingWidths = columnWidths.slice(currentCellCount);
179
+ return (
180
+ "╟" +
181
+ renderRuleSegment(usedWidths, "─", "┼") +
182
+ "┼" +
183
+ renderRuleSegment(collapsingWidths, "─", "┴") +
184
+ "╢"
185
+ );
186
+ } else if (currentCellCount === columnWidths.length) {
187
+ return renderHorizontalRule("╟", columnWidths, "─", innerJoiner, "╢");
188
+ } else {
189
+ const usedWidths = columnWidths.slice(0, currentCellCount);
190
+ const remainingWidth = getUnusedColumnsWidth(
191
+ columnWidths,
192
+ currentCellCount,
193
+ );
194
+ return (
195
+ "╟" +
196
+ renderRuleSegment(usedWidths, "─", innerJoiner) +
197
+ innerJoiner +
198
+ "─".repeat(remainingWidth + 2) +
199
+ "╢"
200
+ );
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Renders the horizontal rule that appears above a row.
206
+ *
207
+ * Handles two cases:
208
+ * - Full width: When row uses all columns, renders with ┼ joiners and
209
+ * ends with ╢ (e.g., "╟───┼───┼───╢")
210
+ * - Short row: When row uses fewer columns, renders active columns with
211
+ * ┼ joiners, ends with ┤, then fills remaining space and ends with ║
212
+ * (e.g., "╟───┼───┤ ║")
213
+ */
214
+ export function renderRowSeparator(
215
+ columnWidths: number[],
216
+ currentCellCount: number,
217
+ ): string {
218
+ if (currentCellCount === columnWidths.length) {
219
+ return renderHorizontalRule("╟", columnWidths, "─", "┼", "╢");
220
+ } else {
221
+ // Short row - ends with ┤ instead of ╢
222
+ const usedWidths = columnWidths.slice(0, currentCellCount);
223
+ const remainingWidth = getUnusedColumnsWidth(
224
+ columnWidths,
225
+ currentCellCount,
226
+ );
227
+ return (
228
+ "╟" +
229
+ renderRuleSegment(usedWidths, "─", "┼") +
230
+ "┤" +
231
+ " ".repeat(remainingWidth + 2) +
232
+ "║"
233
+ );
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Renders the section's bottom border, placing ╧ marks under column
239
+ * separators where the last row/header had cells (e.g., if the last row
240
+ * looked like "║ a │ b │ ║", the bottom border would be
241
+ * "╚═══╧═══╧═══════╝").
242
+ */
243
+ export function renderSectionClose(
244
+ columnWidths: number[],
245
+ previousCellCount: number,
246
+ ): string {
247
+ if (previousCellCount === columnWidths.length) {
248
+ return renderHorizontalRule("╚", columnWidths, "═", "╧", "╝");
249
+ } else {
250
+ const usedWidths = columnWidths.slice(0, previousCellCount);
251
+ const unusedWidth = getUnusedColumnsWidth(columnWidths, previousCellCount);
252
+ return (
253
+ "╚" +
254
+ renderRuleSegment(usedWidths, "═", "╧") +
255
+ "╧" +
256
+ renderRuleSegment([unusedWidth], "═", "") +
257
+ "╝"
258
+ );
259
+ }
260
+ }
@@ -13,36 +13,41 @@ export async function getDeepCloneFunction(): Promise<<T>(input: T) => T> {
13
13
  return clone;
14
14
  }
15
15
 
16
- export function deepMergeImpl<T extends object, U extends object>(
16
+ export function deepMergeImpl<T extends object, S extends object>(
17
17
  target: T,
18
- source: U,
19
- ): T & U {
18
+ source: S,
19
+ shouldOverwriteUndefined: boolean,
20
+ ): T & S {
20
21
  /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
21
- -- The result is expected to include properties from both target and source,
22
- but initially only target is spread in, so a cast is needed. */
23
- const result = { ...target } as T & U;
22
+ -- Result will include properties from both T and S, but starts with only T */
23
+ const result = { ...target } as T & S;
24
24
 
25
- /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
26
- -- TypeScript cannot infer the correct union of string and symbol keys, but all keys come from U */
25
+ /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
26
+ -- All keys come from S, TypeScript can't infer the union of string and symbol keys */
27
27
  const keys = [
28
28
  ...Object.keys(source),
29
29
  ...Object.getOwnPropertySymbols(source),
30
- ] as Array<keyof U>;
30
+ ] as Array<keyof S>;
31
31
 
32
32
  for (const key of keys) {
33
33
  if (
34
34
  isObject(source[key]) &&
35
- // Only merge recursively objects that are not class instances
35
+ // Only merge plain objects, not class instances
36
36
  Object.getPrototypeOf(source[key]) === Object.prototype
37
37
  ) {
38
38
  /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
39
- -- The call signature expects the second argument to be of type U; the type is correct, but TypeScript can't infer it here. */
40
- result[key] = deepMergeImpl(result[key] ?? {}, source[key] as U) as (T &
41
- U)[Extract<keyof U, string>];
42
- } else {
39
+ -- result[key] will have the correct type after assignment but TS can't infer it */
40
+ result[key] = deepMergeImpl(
41
+ result[key] ?? {},
42
+ /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
43
+ -- source[key] is known to be from S but TS can't infer it */
44
+ source[key] as S,
45
+ shouldOverwriteUndefined,
46
+ ) as (T & S)[Extract<keyof S, string>];
47
+ } else if (shouldOverwriteUndefined || source[key] !== undefined) {
43
48
  /* eslint-disable-next-line @typescript-eslint/consistent-type-assertions
44
- -- Cast required because TypeScript can't guarantee that a dynamic key from `U` exists in `T & U` or has the correct value type. */
45
- result[key] = source[key] as (T & U)[Extract<keyof U, string>];
49
+ -- result[key] will have the correct type after assignment but TS can't infer it */
50
+ result[key] = source[key] as (T & S)[Extract<keyof S, string>];
46
51
  }
47
52
  }
48
53
 
@@ -0,0 +1,23 @@
1
+ export function panicErrorCodeToReason(errorCode: bigint): string | undefined {
2
+ // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- we are only covering some of the integer range
3
+ switch (errorCode) {
4
+ case 0x1n:
5
+ return "Assertion error";
6
+ case 0x11n:
7
+ return "Arithmetic operation overflowed outside of an unchecked block";
8
+ case 0x12n:
9
+ return "Division or modulo division by zero";
10
+ case 0x21n:
11
+ return "Tried to convert a value into an enum, but the value was too big or negative";
12
+ case 0x22n:
13
+ return "Incorrectly encoded storage byte array";
14
+ case 0x31n:
15
+ return ".pop() was called on an empty array";
16
+ case 0x32n:
17
+ return "Array accessed at an out-of-bounds or negative index";
18
+ case 0x41n:
19
+ return "Too much memory was allocated, or an array was created that is too large";
20
+ case 0x51n:
21
+ return "Called a zero-initialized variable of internal function type";
22
+ }
23
+ }
package/src/lang.ts CHANGED
@@ -30,24 +30,33 @@ export async function deepEqual<T>(x: T, y: T): Promise<boolean> {
30
30
  *
31
31
  * @remarks
32
32
  * - Arrays or `undefined` values are not valid inputs.
33
- * - Functions: If a function exists in both the target and source, the source function overwrites the target.
34
- * - Symbol properties: Symbol-keyed properties are merged just like string keys.
35
- * - Class instances: Class instances are not merged recursively. If a class instance exists in the source, it will replace the one in the target.
33
+ * - Functions: If a function exists in both the target and source, the source
34
+ * function overwrites the target.
35
+ * - Symbol properties: Symbol-keyed properties are merged just like string
36
+ * keys.
37
+ * - Class instances: Class instances are not merged recursively. If a class
38
+ * instance exists in the source, it will replace the one in the target.
36
39
  *
37
40
  * @param target The target object to merge into.
38
41
  * @param source The source object to merge from.
42
+ * @param shouldOverwriteUndefined If true, properties with `undefined` values
43
+ * in the source will overwrite those in the target. Default is true.
39
44
  * @returns A new object containing the deeply merged properties.
40
45
  *
41
46
  * @example
42
47
  * deepMerge({ a: { b: 1 } }, { a: { c: 2 } }) // => { a: { b: 1, c: 2 } }
43
48
  *
44
- * deepMerge({ a: { fn: () => "from target" } }, { a: { fn: () => "from source" } }) // => { a: { fn: () => "from source" } }
49
+ * deepMerge(
50
+ * { a: { fn: () => "from target" } },
51
+ * { a: { fn: () => "from source" } }
52
+ * ) // => { a: { fn: () => "from source" } }
45
53
  */
46
54
  export function deepMerge<T extends object, U extends object>(
47
55
  target: T,
48
56
  source: U,
57
+ shouldOverwriteUndefined: boolean = true,
49
58
  ): T & U {
50
- return deepMergeImpl(target, source);
59
+ return deepMergeImpl(target, source, shouldOverwriteUndefined);
51
60
  }
52
61
 
53
62
  /**
@@ -1,5 +1,19 @@
1
1
  import { numberToHexString } from "./hex.js";
2
+ import { panicErrorCodeToReason } from "./internal/panic-errors.js";
2
3
 
4
+ /**
5
+ * Converts a Solidity panic error code into a human-readable revert message.
6
+ *
7
+ * Solidity defines a set of standardized panic codes (0x01, 0x11, etc.)
8
+ * that represent specific runtime errors (e.g. arithmetic overflow).
9
+ * This function looks up the corresponding reason string and formats it
10
+ * into a message similar to what clients like Hardhat or ethers.js display.
11
+ *
12
+ * @param errorCode The panic error code returned by the EVM as a bigint.
13
+ * @returns A formatted message string:
14
+ * - `"reverted with panic code <hex> (<reason>)"` if the code is recognized.
15
+ * - `"reverted with unknown panic code <hex>"` if the code is not recognized.
16
+ */
3
17
  export function panicErrorCodeToMessage(errorCode: bigint): string {
4
18
  const reason = panicErrorCodeToReason(errorCode);
5
19
 
@@ -9,27 +23,3 @@ export function panicErrorCodeToMessage(errorCode: bigint): string {
9
23
 
10
24
  return `reverted with unknown panic code ${numberToHexString(errorCode)}`;
11
25
  }
12
-
13
- function panicErrorCodeToReason(errorCode: bigint): string | undefined {
14
- // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- we are only covering some of the integer range
15
- switch (errorCode) {
16
- case 0x1n:
17
- return "Assertion error";
18
- case 0x11n:
19
- return "Arithmetic operation overflowed outside of an unchecked block";
20
- case 0x12n:
21
- return "Division or modulo division by zero";
22
- case 0x21n:
23
- return "Tried to convert a value into an enum, but the value was too big or negative";
24
- case 0x22n:
25
- return "Incorrectly encoded storage byte array";
26
- case 0x31n:
27
- return ".pop() was called on an empty array";
28
- case 0x32n:
29
- return "Array accessed at an out-of-bounds or negative index";
30
- case 0x41n:
31
- return "Too much memory was allocated, or an array was created that is too large";
32
- case 0x51n:
33
- return "Called a zero-initialized variable of internal function type";
34
- }
35
- }