@nomicfoundation/hardhat-utils 3.0.2 → 3.0.4

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,24 @@
1
+ export function panicErrorCodeToReason(errorCode) {
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
+ }
24
+ //# sourceMappingURL=panic-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"panic-errors.js","sourceRoot":"","sources":["../../../src/internal/panic-errors.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,sBAAsB,CAAC,SAAiB;IACtD,4HAA4H;IAC5H,QAAQ,SAAS,EAAE,CAAC;QAClB,KAAK,IAAI;YACP,OAAO,iBAAiB,CAAC;QAC3B,KAAK,KAAK;YACR,OAAO,+DAA+D,CAAC;QACzE,KAAK,KAAK;YACR,OAAO,qCAAqC,CAAC;QAC/C,KAAK,KAAK;YACR,OAAO,8EAA8E,CAAC;QACxF,KAAK,KAAK;YACR,OAAO,wCAAwC,CAAC;QAClD,KAAK,KAAK;YACR,OAAO,qCAAqC,CAAC;QAC/C,KAAK,KAAK;YACR,OAAO,sDAAsD,CAAC;QAChE,KAAK,KAAK;YACR,OAAO,0EAA0E,CAAC;QACpF,KAAK,KAAK;YACR,OAAO,8DAA8D,CAAC;IAC1E,CAAC;AACH,CAAC"}
@@ -1,2 +1,15 @@
1
+ /**
2
+ * Converts a Solidity panic error code into a human-readable revert message.
3
+ *
4
+ * Solidity defines a set of standardized panic codes (0x01, 0x11, etc.)
5
+ * that represent specific runtime errors (e.g. arithmetic overflow).
6
+ * This function looks up the corresponding reason string and formats it
7
+ * into a message similar to what clients like Hardhat or ethers.js display.
8
+ *
9
+ * @param errorCode The panic error code returned by the EVM as a bigint.
10
+ * @returns A formatted message string:
11
+ * - `"reverted with panic code <hex> (<reason>)"` if the code is recognized.
12
+ * - `"reverted with unknown panic code <hex>"` if the code is not recognized.
13
+ */
1
14
  export declare function panicErrorCodeToMessage(errorCode: bigint): string;
2
15
  //# sourceMappingURL=panic-errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"panic-errors.d.ts","sourceRoot":"","sources":["../../src/panic-errors.ts"],"names":[],"mappings":"AAEA,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAQjE"}
1
+ {"version":3,"file":"panic-errors.d.ts","sourceRoot":"","sources":["../../src/panic-errors.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAQjE"}
@@ -1,4 +1,18 @@
1
1
  import { numberToHexString } from "./hex.js";
2
+ import { panicErrorCodeToReason } from "./internal/panic-errors.js";
3
+ /**
4
+ * Converts a Solidity panic error code into a human-readable revert message.
5
+ *
6
+ * Solidity defines a set of standardized panic codes (0x01, 0x11, etc.)
7
+ * that represent specific runtime errors (e.g. arithmetic overflow).
8
+ * This function looks up the corresponding reason string and formats it
9
+ * into a message similar to what clients like Hardhat or ethers.js display.
10
+ *
11
+ * @param errorCode The panic error code returned by the EVM as a bigint.
12
+ * @returns A formatted message string:
13
+ * - `"reverted with panic code <hex> (<reason>)"` if the code is recognized.
14
+ * - `"reverted with unknown panic code <hex>"` if the code is not recognized.
15
+ */
2
16
  export function panicErrorCodeToMessage(errorCode) {
3
17
  const reason = panicErrorCodeToReason(errorCode);
4
18
  if (reason !== undefined) {
@@ -6,27 +20,4 @@ export function panicErrorCodeToMessage(errorCode) {
6
20
  }
7
21
  return `reverted with unknown panic code ${numberToHexString(errorCode)}`;
8
22
  }
9
- function panicErrorCodeToReason(errorCode) {
10
- // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check -- we are only covering some of the integer range
11
- switch (errorCode) {
12
- case 0x1n:
13
- return "Assertion error";
14
- case 0x11n:
15
- return "Arithmetic operation overflowed outside of an unchecked block";
16
- case 0x12n:
17
- return "Division or modulo division by zero";
18
- case 0x21n:
19
- return "Tried to convert a value into an enum, but the value was too big or negative";
20
- case 0x22n:
21
- return "Incorrectly encoded storage byte array";
22
- case 0x31n:
23
- return ".pop() was called on an empty array";
24
- case 0x32n:
25
- return "Array accessed at an out-of-bounds or negative index";
26
- case 0x41n:
27
- return "Too much memory was allocated, or an array was created that is too large";
28
- case 0x51n:
29
- return "Called a zero-initialized variable of internal function type";
30
- }
31
- }
32
23
  //# sourceMappingURL=panic-errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"panic-errors.js","sourceRoot":"","sources":["../../src/panic-errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE7C,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACvD,MAAM,MAAM,GAAG,sBAAsB,CAAC,SAAS,CAAC,CAAC;IAEjD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,4BAA4B,iBAAiB,CAAC,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC;IAChF,CAAC;IAED,OAAO,oCAAoC,iBAAiB,CAAC,SAAS,CAAC,EAAE,CAAC;AAC5E,CAAC;AAED,SAAS,sBAAsB,CAAC,SAAiB;IAC/C,4HAA4H;IAC5H,QAAQ,SAAS,EAAE,CAAC;QAClB,KAAK,IAAI;YACP,OAAO,iBAAiB,CAAC;QAC3B,KAAK,KAAK;YACR,OAAO,+DAA+D,CAAC;QACzE,KAAK,KAAK;YACR,OAAO,qCAAqC,CAAC;QAC/C,KAAK,KAAK;YACR,OAAO,8EAA8E,CAAC;QACxF,KAAK,KAAK;YACR,OAAO,wCAAwC,CAAC;QAClD,KAAK,KAAK;YACR,OAAO,qCAAqC,CAAC;QAC/C,KAAK,KAAK;YACR,OAAO,sDAAsD,CAAC;QAChE,KAAK,KAAK;YACR,OAAO,0EAA0E,CAAC;QACpF,KAAK,KAAK;YACR,OAAO,8DAA8D,CAAC;IAC1E,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"panic-errors.js","sourceRoot":"","sources":["../../src/panic-errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAEpE;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,uBAAuB,CAAC,SAAiB;IACvD,MAAM,MAAM,GAAG,sBAAsB,CAAC,SAAS,CAAC,CAAC;IAEjD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,OAAO,4BAA4B,iBAAiB,CAAC,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC;IAChF,CAAC;IAED,OAAO,oCAAoC,iBAAiB,CAAC,SAAS,CAAC,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,46 @@
1
+ export declare const FRAME_INTERVAL_MS = 80;
2
+ export interface ISpinner {
3
+ readonly isEnabled: boolean;
4
+ start(): void;
5
+ stop(): void;
6
+ }
7
+ /**
8
+ * Optional settings when creating a spinner.
9
+ */
10
+ export interface SpinnerOptions {
11
+ /**
12
+ * Text shown next to the spinner.
13
+ */
14
+ text?: string;
15
+ /**
16
+ * Stream used to write frames.
17
+ */
18
+ stream?: NodeJS.WriteStream;
19
+ /**
20
+ * Whether the spinner is enabled.
21
+ */
22
+ enabled?: boolean;
23
+ }
24
+ /**
25
+ * Create a spinner instance.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const spinner = createSpinner({ text: "Compiling…" });
30
+ * spinner.start();
31
+ *
32
+ * try {
33
+ * await compileContracts();
34
+ * spinner.stop();
35
+ * console.log("Compiled 12 contracts");
36
+ * } catch (error) {
37
+ * spinner.stop();
38
+ * console.error("Compilation failed");
39
+ * }
40
+ * ```
41
+ *
42
+ * @param options Optional spinner configuration.
43
+ * @returns {Spinner} A spinner instance.
44
+ */
45
+ export declare function createSpinner(options?: SpinnerOptions): ISpinner;
46
+ //# sourceMappingURL=spinner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spinner.d.ts","sourceRoot":"","sources":["../../src/spinner.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAEpC,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,KAAK,IAAI,IAAI,CAAC;IACd,IAAI,IAAI,IAAI,CAAC;CACd;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,WAAW,CAAC;IAE5B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAmED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,cAAmB,GAAG,QAAQ,CAcpE"}
@@ -0,0 +1,91 @@
1
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
2
+ export const FRAME_INTERVAL_MS = 80;
3
+ /**
4
+ * Spinner that writes frames to a stream.
5
+ */
6
+ class Spinner {
7
+ isEnabled;
8
+ #text;
9
+ #interval = null;
10
+ #stream;
11
+ constructor(options) {
12
+ this.isEnabled = options.enabled;
13
+ this.#stream = options.stream;
14
+ this.#text = options.text;
15
+ }
16
+ /**
17
+ * Begin rendering frames when enabled.
18
+ */
19
+ start() {
20
+ if (!this.isEnabled) {
21
+ return;
22
+ }
23
+ this.#stopAnimation();
24
+ let frameIndex = 0;
25
+ this.#interval = setInterval(() => {
26
+ this.#render(FRAMES[frameIndex]);
27
+ frameIndex = (frameIndex + 1) % FRAMES.length;
28
+ }, FRAME_INTERVAL_MS);
29
+ }
30
+ /**
31
+ * Stop the spinner without printing a final line.
32
+ */
33
+ stop() {
34
+ this.#stopAnimation();
35
+ }
36
+ #clearLine() {
37
+ this.#stream.clearLine(0);
38
+ this.#stream.cursorTo(0);
39
+ }
40
+ #render(frame) {
41
+ if (!this.isEnabled) {
42
+ return;
43
+ }
44
+ this.#clearLine();
45
+ this.#stream.write(`${frame} ${this.#text}`);
46
+ }
47
+ #stopAnimation() {
48
+ if (this.#interval === null) {
49
+ return;
50
+ }
51
+ clearInterval(this.#interval);
52
+ this.#interval = null;
53
+ if (this.isEnabled) {
54
+ this.#clearLine();
55
+ }
56
+ }
57
+ }
58
+ /**
59
+ * Create a spinner instance.
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const spinner = createSpinner({ text: "Compiling…" });
64
+ * spinner.start();
65
+ *
66
+ * try {
67
+ * await compileContracts();
68
+ * spinner.stop();
69
+ * console.log("Compiled 12 contracts");
70
+ * } catch (error) {
71
+ * spinner.stop();
72
+ * console.error("Compilation failed");
73
+ * }
74
+ * ```
75
+ *
76
+ * @param options Optional spinner configuration.
77
+ * @returns {Spinner} A spinner instance.
78
+ */
79
+ export function createSpinner(options = {}) {
80
+ const stream = options.stream ?? process.stdout;
81
+ const enabled = stream.isTTY === true &&
82
+ process.env.TERM !== "dumb" &&
83
+ (options.enabled ?? true);
84
+ const text = options.text ?? "";
85
+ return new Spinner({
86
+ enabled,
87
+ stream,
88
+ text,
89
+ });
90
+ }
91
+ //# sourceMappingURL=spinner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spinner.js","sourceRoot":"","sources":["../../src/spinner.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAClE,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AA4BpC;;GAEG;AACH,MAAM,OAAO;IACK,SAAS,CAAU;IAC1B,KAAK,CAAS;IACvB,SAAS,GAA0B,IAAI,CAAC;IAC/B,OAAO,CAAqB;IAErC,YAAY,OAAiC;QAC3C,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC;QACjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAC5B,CAAC;IACD;;OAEG;IACI,KAAK;QACV,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,cAAc,EAAE,CAAC;QACtB,IAAI,UAAU,GAAG,CAAC,CAAC;QAEnB,IAAI,CAAC,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE;YAChC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;YACjC,UAAU,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC;QAChD,CAAC,EAAE,iBAAiB,CAAC,CAAC;IACxB,CAAC;IAED;;OAEG;IACI,IAAI;QACT,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED,UAAU;QACR,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,CAAC,KAAa;QACnB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,cAAc;QACZ,IAAI,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE,CAAC;YAC5B,OAAO;QACT,CAAC;QAED,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC9B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,CAAC;IACH,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,aAAa,CAAC,UAA0B,EAAE;IACxD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC;IAEhD,MAAM,OAAO,GACX,MAAM,CAAC,KAAK,KAAK,IAAI;QACrB,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,MAAM;QAC3B,CAAC,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;IAE5B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;IAChC,OAAO,IAAI,OAAO,CAAC;QACjB,OAAO;QACP,MAAM;QACN,IAAI;KACL,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomicfoundation/hardhat-utils",
3
- "version": "3.0.2",
3
+ "version": "3.0.4",
4
4
  "description": "Utilities for Hardhat and its plugins",
5
5
  "homepage": "https://github.com/nomicfoundation/hardhat/tree/v-next/v-next/hardhat-utils",
6
6
  "repository": {
@@ -23,6 +23,7 @@
23
23
  "./env": "./dist/src/env.js",
24
24
  "./error": "./dist/src/error.js",
25
25
  "./eth": "./dist/src/eth.js",
26
+ "./format": "./dist/src/format.js",
26
27
  "./fs": "./dist/src/fs.js",
27
28
  "./global-dir": "./dist/src/global-dir.js",
28
29
  "./hex": "./dist/src/hex.js",
@@ -35,7 +36,8 @@
35
36
  "./string": "./dist/src/string.js",
36
37
  "./stream": "./dist/src/stream.js",
37
38
  "./subprocess": "./dist/src/subprocess.js",
38
- "./synchronization": "./dist/src/synchronization.js"
39
+ "./synchronization": "./dist/src/synchronization.js",
40
+ "./spinner": "./dist/src/spinner.js"
39
41
  },
40
42
  "keywords": [
41
43
  "ethereum",
package/src/format.ts ADDED
@@ -0,0 +1,267 @@
1
+ import {
2
+ getColumnWidths,
3
+ getContentWidth,
4
+ getHeadingWidth,
5
+ getStringWidth,
6
+ renderContentLine,
7
+ renderHeaderOpen,
8
+ renderRowSeparator,
9
+ renderSectionClose,
10
+ } from "./internal/format.js";
11
+
12
+ export type TableRow = string[];
13
+ export interface TableDivider {
14
+ type: "divider";
15
+ }
16
+ export type TableItem = TableRow | TableDivider;
17
+
18
+ export const divider: TableDivider = { type: "divider" };
19
+
20
+ /**
21
+ * Formats an array of rows and dividers into a table string.
22
+ *
23
+ * @param items An array of table rows (string arrays) and dividers.
24
+ * Dividers are objects with type: "divider" and will be rendered as table dividers.
25
+ * @returns The formatted table as a string, ready to be rendered.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * formatTable([
30
+ * ["Name", "Age"],
31
+ * divider,
32
+ * ["Alice", "30"],
33
+ * ["Bob", "25"],
34
+ * divider,
35
+ * ["Average", "27.5"]
36
+ * ]);
37
+ *
38
+ * // =>
39
+ * // | Name | Age |
40
+ * // | ------- | ---- |
41
+ * // | Alice | 30 |
42
+ * // | Bob | 25 |
43
+ * // | ------- | ---- |
44
+ * // | Average | 27.5 |
45
+ * ```
46
+ */
47
+ export function formatTable(items: TableItem[]): string {
48
+ const widths: number[] = [];
49
+ const dataRows: string[][] = [];
50
+
51
+ for (const item of items) {
52
+ if (Array.isArray(item)) {
53
+ dataRows.push([...item]);
54
+ }
55
+ }
56
+
57
+ // Calculate maximum width for each column
58
+ for (const row of dataRows) {
59
+ for (let i = 0; i < row.length; i++) {
60
+ while (i >= widths.length) {
61
+ widths.push(0);
62
+ }
63
+ widths[i] = Math.max(widths[i], getStringWidth(row[i]));
64
+ }
65
+ }
66
+
67
+ const dividerRow = widths.map((width) => "-".repeat(width));
68
+ const outputRows: string[][] = [];
69
+
70
+ for (const item of items) {
71
+ if (Array.isArray(item)) {
72
+ const row = [...item];
73
+ // Pad the row to match the number of columns
74
+ while (row.length < widths.length) {
75
+ row.push("");
76
+ }
77
+ outputRows.push(row);
78
+ } else {
79
+ outputRows.push([...dividerRow]);
80
+ }
81
+ }
82
+
83
+ outputRows.forEach((row) => {
84
+ for (let i = 0; i < row.length; i++) {
85
+ const displayWidth = getStringWidth(row[i]);
86
+ const actualLength = row[i].length;
87
+ // Adjust padding to account for difference between display width and actual length
88
+ row[i] = row[i].padEnd(widths[i] + actualLength - displayWidth);
89
+ }
90
+ });
91
+
92
+ return outputRows.map((row) => `| ${row.join(" | ")} |`).join("\n");
93
+ }
94
+
95
+ export interface TableTitleV2 {
96
+ type: "title";
97
+ text: string;
98
+ }
99
+
100
+ export interface TableSectionHeaderV2 {
101
+ type: "section-header";
102
+ text: string;
103
+ }
104
+
105
+ export interface TableHeaderV2 {
106
+ type: "header";
107
+ cells: string[];
108
+ }
109
+
110
+ export interface TableRowV2 {
111
+ type: "row";
112
+ cells: string[];
113
+ }
114
+
115
+ export type TableItemV2 =
116
+ | TableTitleV2
117
+ | TableSectionHeaderV2
118
+ | TableHeaderV2
119
+ | TableRowV2;
120
+
121
+ /**
122
+ * Formats an array of titles, section headers, headers, and rows into a table
123
+ * string with box-drawing characters.
124
+ *
125
+ * Features:
126
+ * - Titles are centered in a standalone box with double borders (╔═╗)
127
+ * - Section headers group related content with automatic closing
128
+ * - Headers and rows can have different numbers of cells
129
+ * - Rows with fewer cells than max columns are handled with special rendering
130
+ *
131
+ * @param items An array of table items (titles, section headers, headers, and rows).
132
+ * Sections are automatically closed when a new section-header or title appears, or
133
+ * at the end of the table.
134
+ * @returns The formatted table as a string, ready to be rendered.
135
+ *
136
+ * @example
137
+ * ```ts
138
+ * formatTableV2([
139
+ * { type: "title", text: "My Table" },
140
+ * { type: "section-header", text: "User Data" },
141
+ * { type: "header", cells: ["Name", "Age", "City"] },
142
+ * { type: "row", cells: ["Alice", "30", "NYC"] },
143
+ * { type: "row", cells: ["Bob", "25", "LA"] },
144
+ * { type: "section-header", text: "Summary" },
145
+ * { type: "header", cells: ["Total", "Count"] },
146
+ * { type: "row", cells: ["55", "2"] }
147
+ * ]);
148
+ *
149
+ * // =>
150
+ * // ╔═══════════════════╗
151
+ * // ║ My Table ║
152
+ * // ╚═══════════════════╝
153
+ * // ╔═══════════════════╗
154
+ * // ║ User Data ║
155
+ * // ╟───────┬─────┬─────╢
156
+ * // ║ Name │ Age │ City║
157
+ * // ╟───────┼─────┼─────╢
158
+ * // ║ Alice │ 30 │ NYC ║
159
+ * // ╟───────┼─────┼─────╢
160
+ * // ║ Bob │ 25 │ LA ║
161
+ * // ╚═══════╧═════╧═════╝
162
+ * // ╔═══════════════════╗
163
+ * // ║ Summary ║
164
+ * // ╟───────┬───────────╢
165
+ * // ║ Total │ Count ║
166
+ * // ╟───────┼───────────╢
167
+ * // ║ 55 │ 2 ║
168
+ * // ╚═══════╧═══════════╝
169
+ * ```
170
+ */
171
+ export function formatTableV2(items: TableItemV2[]): string {
172
+ if (items.length === 0) {
173
+ return "";
174
+ }
175
+
176
+ const columnWidths = getColumnWidths(items);
177
+ const contentWidth = getContentWidth(columnWidths);
178
+ const headingWidth = getHeadingWidth(items);
179
+
180
+ // If heading is wider than content, expand last column to fit
181
+ if (headingWidth > contentWidth && columnWidths.length > 0) {
182
+ const extraSpace = headingWidth - contentWidth;
183
+ columnWidths[columnWidths.length - 1] += extraSpace;
184
+ }
185
+
186
+ const tableWidth = Math.max(contentWidth, headingWidth);
187
+
188
+ const lines: string[] = [];
189
+ let previousCellCount = 0; // Keep track of previous row/header cell count
190
+ let inSection = false;
191
+
192
+ for (let i = 0; i < items.length; i++) {
193
+ const [previous, current] = [items[i - 1], items[i]];
194
+
195
+ if (current.type === "title") {
196
+ if (inSection) {
197
+ lines.push(renderSectionClose(columnWidths, previousCellCount));
198
+ inSection = false;
199
+ }
200
+
201
+ lines.push("╔" + "═".repeat(tableWidth) + "╗");
202
+ const titleDisplayWidth = getStringWidth(current.text);
203
+ const titleActualLength = current.text.length;
204
+ const centeredTitle = current.text
205
+ .padStart(
206
+ (tableWidth + titleDisplayWidth) / 2 +
207
+ (titleActualLength - titleDisplayWidth),
208
+ )
209
+ .padEnd(tableWidth + (titleActualLength - titleDisplayWidth));
210
+ lines.push("║" + centeredTitle + "║");
211
+ lines.push("╚" + "═".repeat(tableWidth) + "╝");
212
+ } else if (current.type === "section-header") {
213
+ if (inSection) {
214
+ lines.push(renderSectionClose(columnWidths, previousCellCount));
215
+ }
216
+
217
+ lines.push("╔" + "═".repeat(tableWidth) + "╗");
218
+ const headerDisplayWidth = getStringWidth(current.text);
219
+ const headerActualLength = current.text.length;
220
+ const paddedHeader = current.text.padEnd(
221
+ tableWidth - 2 + (headerActualLength - headerDisplayWidth),
222
+ );
223
+ lines.push("║ " + paddedHeader + " ║");
224
+ inSection = true;
225
+ } else if (current.type === "header") {
226
+ const currentCellCount = current.cells.length;
227
+ const innerJoiner =
228
+ previous !== undefined && previous.type === "section-header"
229
+ ? "┬"
230
+ : "┼";
231
+ const needsTransition =
232
+ previous !== undefined &&
233
+ previous.type !== "section-header" &&
234
+ currentCellCount < previousCellCount;
235
+
236
+ lines.push(
237
+ renderHeaderOpen(
238
+ columnWidths,
239
+ currentCellCount,
240
+ innerJoiner,
241
+ needsTransition,
242
+ ),
243
+ );
244
+ lines.push(
245
+ renderContentLine(current.cells, columnWidths, currentCellCount),
246
+ );
247
+ previousCellCount = currentCellCount;
248
+ } else if (current.type === "row") {
249
+ const currentCellCount = current.cells.length;
250
+
251
+ // Only add separator if previous wasn't a row
252
+ if (previous === undefined || previous.type !== "row") {
253
+ lines.push(renderRowSeparator(columnWidths, currentCellCount));
254
+ }
255
+ lines.push(
256
+ renderContentLine(current.cells, columnWidths, currentCellCount),
257
+ );
258
+ previousCellCount = currentCellCount;
259
+ }
260
+ }
261
+
262
+ if (inSection) {
263
+ lines.push(renderSectionClose(columnWidths, previousCellCount));
264
+ }
265
+
266
+ return lines.join("\n");
267
+ }