@nomicfoundation/hardhat-utils 4.4.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/fs.ts CHANGED
@@ -1,11 +1,11 @@
1
- import type * as JsonStreamStringify from "json-stream-stringify";
2
1
  import type { FileHandle } from "node:fs/promises";
3
2
 
3
+ import { constants as bufferConstants } from "node:buffer";
4
4
  import fsPromises from "node:fs/promises";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
- import { pipeline } from "node:stream/promises";
8
7
 
8
+ import { parseJsonBytes } from "./bytes.js";
9
9
  import { ensureError, ensureNodeErrnoExceptionError } from "./error.js";
10
10
  import {
11
11
  FileNotFoundError,
@@ -21,11 +21,20 @@ import { parseJsonStream } from "./internal/bytes.js";
21
21
  import {
22
22
  collectAllDirectoriesMatching,
23
23
  collectAllFilesMatching,
24
+ streamJsonToFile,
24
25
  } from "./internal/fs.js";
25
-
26
- // We don't load json-stream-stringify on startup because it's only
27
- // used by writeJsonFileAsStream for very large JSON objects.
28
- let jsonStreamStringify: typeof JsonStreamStringify | undefined;
26
+ import {
27
+ hasHeapHeadroomFor,
28
+ READ_HEAP_BYTES_PER_JSON_BYTE,
29
+ WRITE_HEAP_BYTES_PER_JSON_BYTE,
30
+ } from "./internal/json.js";
31
+ import { AsyncMutex } from "./synchronization.js";
32
+
33
+ // Lets only one call of writeLargeJsonFile use JSON.stringify at a time, so
34
+ // that their strings don't use up each other's heap headroom.
35
+ // NOTE: Created on first use: synchronization.ts imports this file, so
36
+ // AsyncMutex may not be initialized yet while this file is first loading.
37
+ let bufferedWriteMutex: AsyncMutex | undefined;
29
38
 
30
39
  const AMBIGUOUS_CASING_DIR_ENTRY = Symbol("ambiguous");
31
40
 
@@ -343,25 +352,6 @@ export async function getAllDirectoriesMatching(
343
352
  return results;
344
353
  }
345
354
 
346
- /**
347
- * Determines the true case path of a given relative path from a specified
348
- * directory, without resolving symbolic links, and returns it.
349
- *
350
- * @param from The absolute path of the directory to start the search from.
351
- * @param relativePath The relative path to get the true case of.
352
- * @returns The true case of the relative path.
353
- * @throws FileNotFoundError if the starting directory or the relative path doesn't exist.
354
- * @throws NotADirectoryError if the starting directory is not a directory.
355
- * @throws FileSystemAccessError for any other error.
356
- * @deprecated Use {@link TrueCasePathResolver} instead.
357
- */
358
- export async function getFileTrueCase(
359
- from: string,
360
- relativePath: string,
361
- ): Promise<string> {
362
- return await new TrueCasePathResolver().getFileTrueCase(from, relativePath);
363
- }
364
-
365
355
  /**
366
356
  * Checks if a given path is a directory.
367
357
  *
@@ -386,26 +376,10 @@ export async function isDirectory(absolutePath: string): Promise<boolean> {
386
376
  /**
387
377
  * Reads a JSON file and parses it. The encoding used is "utf8".
388
378
  *
389
- * @param absolutePathToFile The path to the file.
390
- * @returns The parsed JSON object.
391
- * @throws FileNotFoundError if the file doesn't exist.
392
- * @throws InvalidFileFormatError if the file is not a valid JSON file.
393
- * @throws IsDirectoryError if the path is a directory instead of a file.
394
- * @throws FileSystemAccessError for any other error.
395
- */
396
- export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
397
- const content = await readUtf8File(absolutePathToFile);
398
- try {
399
- return JSON.parse(content.toString());
400
- } catch (e) {
401
- ensureError(e);
402
- throw new InvalidFileFormatError(absolutePathToFile, e);
403
- }
404
- }
405
-
406
- /**
407
- * Reads a JSON file as a stream and parses it. The encoding used is "utf8".
408
- * This function should be used when parsing very large JSON files.
379
+ * Files of any size are supported. The file is parsed with `JSON.parse`,
380
+ * which is much faster, when its text fits in a single string and the heap has
381
+ * room for it. Otherwise, it's parsed as a stream, which never holds the whole
382
+ * text as one string. Both give the same result.
409
383
  *
410
384
  * @param absolutePathToFile The path to the file.
411
385
  * @returns The parsed JSON object.
@@ -414,20 +388,37 @@ export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
414
388
  * @throws IsDirectoryError if the path is a directory instead of a file.
415
389
  * @throws FileSystemAccessError for any other error.
416
390
  */
417
- export async function readJsonFileAsStream<T>(
418
- absolutePathToFile: string,
419
- ): Promise<T> {
391
+ export async function readJsonFile<T>(absolutePathToFile: string): Promise<T> {
420
392
  let fileHandle: FileHandle | undefined;
421
393
 
422
394
  try {
423
395
  fileHandle = await fsPromises.open(absolutePathToFile, "r");
424
396
 
425
- return await parseJsonStream<T>(fileHandle.createReadStream());
397
+ // Each UTF-8 byte decodes to at most one character, so the file's size
398
+ // tells us whether its text could fit in a string. If it can't, or the
399
+ // heap has no room for it right now, we stream it from disk instead of
400
+ // reading it all into memory.
401
+ const { size } = await fileHandle.stat();
402
+ if (
403
+ size > bufferConstants.MAX_STRING_LENGTH ||
404
+ !hasHeapHeadroomFor(size * READ_HEAP_BYTES_PER_JSON_BYTE)
405
+ ) {
406
+ return await parseJsonStream<T>(fileHandle.createReadStream());
407
+ }
408
+
409
+ // The bytes are stored outside of the heap. parseJsonBytes checks the heap
410
+ // again, as other code may have used it while we were reading.
411
+ return await parseJsonBytes<T>(await fileHandle.readFile());
426
412
  } catch (e) {
427
413
  ensureError(e);
428
414
 
429
415
  // If the code is defined, we assume the error to be related to the file system
430
416
  if ("code" in e) {
417
+ // Except for invalid UTF-8, which is a problem with the file's contents
418
+ if (e.code === "ERR_ENCODING_INVALID_ENCODED_DATA") {
419
+ throw new InvalidFileFormatError(absolutePathToFile, e);
420
+ }
421
+
431
422
  if (e.code === "ENOENT") {
432
423
  throw new FileNotFoundError(absolutePathToFile, e);
433
424
  }
@@ -438,7 +429,7 @@ export async function readJsonFileAsStream<T>(
438
429
 
439
430
  // If the code is defined, we assume the error to be related to the file system
440
431
  if (e.code !== undefined) {
441
- throw new FileSystemAccessError(absolutePathToFile, e);
432
+ throw new FileSystemAccessError(e.message, e);
442
433
  }
443
434
  }
444
435
 
@@ -475,59 +466,77 @@ export async function writeJsonFile<T>(
475
466
  }
476
467
 
477
468
  /**
478
- * Writes an object to a JSON file as stream. The encoding used is "utf8" and the file is overwritten.
479
- * If part of the path doesn't exist, it will be created.
480
- * This function should be used when stringifying very large JSON objects.
469
+ * Writes an object to a JSON file, supporting objects whose JSON is too large
470
+ * to be held in a single string. The JSON is compact (not indented), the
471
+ * encoding used is "utf8", and the file is overwritten. If part of the path
472
+ * doesn't exist, it will be created.
473
+ *
474
+ * Use this function for objects whose JSON can be very large, like solc's
475
+ * output, and {@link writeJsonFile} for everything else.
476
+ *
477
+ * The object is serialized with `JSON.stringify`, which is much faster, when
478
+ * the heap has room for the longest string it could build. Otherwise, or if
479
+ * its JSON doesn't fit in a single string, it's serialized as a stream, which
480
+ * never holds the whole JSON as one string. Only one call uses
481
+ * `JSON.stringify` at a time: concurrent calls take turns.
482
+ *
483
+ * Both write the same JSON, except for objects that contain a BigInt, a
484
+ * Promise, or a `toJSON` method that throws. `JSON.stringify` throws a
485
+ * `JsonSerializationError` for a BigInt or a throwing `toJSON`, and writes a
486
+ * Promise as `{}`. The stream writes a BigInt as a plain number, writes a
487
+ * Promise's resolved value, and crashes the process if a `toJSON` throws.
481
488
  *
482
489
  * @param absolutePathToFile The path to the file. If the file exists, it will be overwritten.
483
490
  * @param object The object to write.
484
491
  * @throws JsonSerializationError if the object can't be serialized to JSON.
485
492
  * @throws FileSystemAccessError for any other error.
486
493
  */
487
- export async function writeJsonFileAsStream<T>(
494
+ export async function writeLargeJsonFile<T>(
488
495
  absolutePathToFile: string,
489
496
  object: T,
490
497
  ): Promise<void> {
491
- const dirPath = path.dirname(absolutePathToFile);
492
- const dirExists = await exists(dirPath);
493
- if (!dirExists) {
494
- await mkdir(dirPath);
495
- }
496
-
497
- let fileHandle: FileHandle | undefined;
498
-
499
- try {
500
- fileHandle = await fsPromises.open(absolutePathToFile, "w");
498
+ bufferedWriteMutex ??= new AsyncMutex();
501
499
 
502
- if (jsonStreamStringify === undefined) {
503
- jsonStreamStringify = await import("json-stream-stringify");
500
+ const written = await bufferedWriteMutex.exclusiveRun(async () => {
501
+ // We can't know the JSON's length before building it, so we require room
502
+ // for the longest string V8 can build. JSON.stringify throws a RangeError
503
+ // instead of going past it, so with this much heap free, it can't run out.
504
+ if (
505
+ !hasHeapHeadroomFor(
506
+ bufferConstants.MAX_STRING_LENGTH * WRITE_HEAP_BYTES_PER_JSON_BYTE,
507
+ )
508
+ ) {
509
+ return false;
504
510
  }
505
511
 
506
- const jsonStream = new jsonStreamStringify.JsonStreamStringify(object);
507
- const fileWriteStream = fileHandle.createWriteStream();
512
+ let json: string;
513
+ try {
514
+ json = JSON.stringify(object);
515
+ } catch (e) {
516
+ ensureError(e);
508
517
 
509
- await pipeline(jsonStream, fileWriteStream);
510
- } catch (e) {
511
- ensureError(e);
512
- // if the directory was created, we should remove it
513
- if (dirExists === false) {
514
- try {
515
- await remove(dirPath);
516
- // we don't want to override the original error
517
- } catch (_error) {}
518
- }
518
+ // The JSON is too long for a string, or the object is nested too deeply
519
+ // for JSON.stringify. Streaming handles both.
520
+ if (e instanceof RangeError) {
521
+ return false;
522
+ }
519
523
 
520
- // If the code is defined, we assume the error to be related to the file system
521
- if ("code" in e && e.code !== undefined) {
522
- throw new FileSystemAccessError(e.message, e);
524
+ // Anything else isn't about size, so streaming wouldn't help:
525
+ // - A circular object (TypeError): streaming detects it too.
526
+ // - A BigInt (TypeError): streaming writes it as a plain number, which
527
+ // is read back as a rounded number if it's too large. Failing is safer.
528
+ // - An error thrown by a toJSON method: streaming can't report it, and
529
+ // crashes the process instead.
530
+ throw new JsonSerializationError(absolutePathToFile, e);
523
531
  }
524
532
 
525
- // Otherwise, we assume the error to be related to the file formatting
526
- throw new JsonSerializationError(absolutePathToFile, e);
527
- } finally {
528
- // NOTE: Historically, not closing the file handle caused issues on Windows,
529
- // for example, when trying to move the file previously written to by this function
530
- await fileHandle?.close();
533
+ await writeUtf8File(absolutePathToFile, json);
534
+ return true;
535
+ });
536
+
537
+ if (!written) {
538
+ // Streaming uses little memory, so it doesn't need to take turns.
539
+ await streamJsonToFile(absolutePathToFile, object);
531
540
  }
532
541
  }
533
542
 
@@ -1,11 +1,22 @@
1
+ import type * as JsonStreamStringify from "json-stream-stringify";
1
2
  import type { Dirent } from "node:fs";
3
+ import type { FileHandle } from "node:fs/promises";
2
4
 
3
5
  import fsPromises from "node:fs/promises";
4
6
  import path from "node:path";
7
+ import { pipeline } from "node:stream/promises";
5
8
 
6
- import { ensureNodeErrnoExceptionError } from "../error.js";
7
- import { FileSystemAccessError, NotADirectoryError } from "../errors/fs.js";
8
- import { isDirectory } from "../fs.js";
9
+ import { ensureError, ensureNodeErrnoExceptionError } from "../error.js";
10
+ import {
11
+ FileSystemAccessError,
12
+ JsonSerializationError,
13
+ NotADirectoryError,
14
+ } from "../errors/fs.js";
15
+ import { exists, isDirectory, mkdir, remove } from "../fs.js";
16
+
17
+ // We don't load json-stream-stringify on startup because it's only used by
18
+ // writeLargeJsonFile when it can't use JSON.stringify.
19
+ let jsonStreamStringify: typeof JsonStreamStringify | undefined;
9
20
 
10
21
  /**
11
22
  * Like `readdirOrEmpty`, but returns `Dirent` entries to know if an entry is a
@@ -125,3 +136,55 @@ export async function collectAllDirectoriesMatching(
125
136
  }),
126
137
  );
127
138
  }
139
+
140
+ /**
141
+ * Writes an object to a JSON file as a stream, which never holds the whole
142
+ * JSON as a single string. It's used by `writeLargeJsonFile` when it can't use
143
+ * `JSON.stringify`.
144
+ */
145
+ export async function streamJsonToFile(
146
+ absolutePathToFile: string,
147
+ object: unknown,
148
+ ): Promise<void> {
149
+ const dirPath = path.dirname(absolutePathToFile);
150
+ const dirExists = await exists(dirPath);
151
+ if (!dirExists) {
152
+ await mkdir(dirPath);
153
+ }
154
+
155
+ let fileHandle: FileHandle | undefined;
156
+
157
+ try {
158
+ fileHandle = await fsPromises.open(absolutePathToFile, "w");
159
+
160
+ if (jsonStreamStringify === undefined) {
161
+ jsonStreamStringify = await import("json-stream-stringify");
162
+ }
163
+
164
+ const jsonStream = new jsonStreamStringify.JsonStreamStringify(object);
165
+ const fileWriteStream = fileHandle.createWriteStream();
166
+
167
+ await pipeline(jsonStream, fileWriteStream);
168
+ } catch (e) {
169
+ ensureError(e);
170
+ // if the directory was created, we should remove it
171
+ if (dirExists === false) {
172
+ try {
173
+ await remove(dirPath);
174
+ // we don't want to override the original error
175
+ } catch (_error) {}
176
+ }
177
+
178
+ // If the code is defined, we assume the error to be related to the file system
179
+ if ("code" in e && e.code !== undefined) {
180
+ throw new FileSystemAccessError(e.message, e);
181
+ }
182
+
183
+ // Otherwise, we assume the error to be related to the file formatting
184
+ throw new JsonSerializationError(absolutePathToFile, e);
185
+ } finally {
186
+ // NOTE: Historically, not closing the file handle caused issues on Windows,
187
+ // for example, when trying to move the file previously written to by this function
188
+ await fileHandle?.close();
189
+ }
190
+ }
@@ -0,0 +1,59 @@
1
+ // NOTE: We use the default import so that tests can mock getHeapStatistics.
2
+ import v8 from "node:v8";
3
+
4
+ /**
5
+ * The heap needed per byte of JSON to parse it with `JSON.parse`.
6
+ *
7
+ * At its peak, `JSON.parse` holds both the whole text, as a single string, and
8
+ * the objects it builds:
9
+ * - V8 stores a string with 1 byte per character only if every character is
10
+ * in Latin-1, and otherwise with 2. Real-world JSON rarely qualifies: solc's
11
+ * output, for example, usually includes NatSpec comments, which can use
12
+ * characters like `’`, `→` or `—`. Each UTF-8 byte decodes to at most one
13
+ * character, so the string takes at most 2 bytes per byte of JSON.
14
+ * - The objects add about 1.6 bytes per byte of JSON.
15
+ *
16
+ * Measured on real solc output (19 and 95 MB) as the smallest
17
+ * `--max-old-space-size` the parse succeeds with, the peak was about 3.6 bytes
18
+ * per byte, the worst of Node 22, 24 and 26. Rounded up.
19
+ */
20
+ export const READ_HEAP_BYTES_PER_JSON_BYTE = 4;
21
+
22
+ /**
23
+ * The heap needed per byte of JSON to serialize it with `JSON.stringify`.
24
+ *
25
+ * The objects already exist, so it's just the output string, at 2 bytes per
26
+ * character (see above). Measured the same way on Node 22, 24 and 26, a
27
+ * ~400M-character output needed exactly the string's size, with no extra
28
+ * peak.
29
+ */
30
+ export const WRITE_HEAP_BYTES_PER_JSON_BYTE = 2;
31
+
32
+ /**
33
+ * Extra heap we require on top of our own allocation, for everything else that
34
+ * needs it while that allocation is alive, like garbage collection and the
35
+ * rest of the program, and to absorb small errors in the estimates above.
36
+ *
37
+ * It isn't measured: it's a cautious round number, small next to Node's
38
+ * default heap limits (about 2 to 4 GiB, depending on the machine's memory).
39
+ */
40
+ export const HEAP_MARGIN_BYTES: number = 256 * 1024 * 1024;
41
+
42
+ /**
43
+ * Checks whether the heap can grow by `bytes`, plus a safety margin, before
44
+ * reaching its limit.
45
+ *
46
+ * Running out of heap crashes the process, and can't be caught, so this must
47
+ * be called right before the allocation. At each `await` in between, other
48
+ * code can run and use memory.
49
+ *
50
+ * @param bytes The number of bytes about to be allocated in the heap.
51
+ * @returns `true` if there's enough room for them.
52
+ */
53
+ export function hasHeapHeadroomFor(bytes: number): boolean {
54
+ // `total_available_size` counts garbage that hasn't been collected yet as
55
+ // used, so this errs toward `false`, which is the safe direction.
56
+ return (
57
+ bytes + HEAP_MARGIN_BYTES <= v8.getHeapStatistics().total_available_size
58
+ );
59
+ }
@@ -3,7 +3,6 @@ import type EventEmitter from "node:events";
3
3
  import type * as UndiciT from "undici";
4
4
 
5
5
  import crypto from "node:crypto";
6
- import { STATUS_CODES } from "node:http";
7
6
  import path from "node:path";
8
7
 
9
8
  import { mkdir } from "../fs.js";
@@ -376,7 +375,9 @@ function describeResponseError(e: Error): void {
376
375
  return;
377
376
  }
378
377
 
379
- const reason = STATUS_CODES[statusCode];
378
+ // Importing `node:http` loads Node's whole HTTP stack, so we defer
379
+ // using `process.getBuiltinModule` as a dynamic load.
380
+ const reason = process.getBuiltinModule("node:http").STATUS_CODES[statusCode];
380
381
 
381
382
  e.message = `Response status code ${statusCode}${
382
383
  reason !== undefined ? `: ${reason}` : ""
package/src/request.ts CHANGED
@@ -389,6 +389,39 @@ export function isValidUrl(url: string): boolean {
389
389
  }
390
390
  }
391
391
 
392
+ /**
393
+ * Splits the query params out of a url, so they can be merged with other
394
+ * params and passed as `queryParams` to the request functions. A request
395
+ * fails if its url has a query string and `queryParams` is also passed.
396
+ *
397
+ * Urls without a query string, and invalid urls, are returned unchanged, with
398
+ * no query params.
399
+ *
400
+ * @param url The url to split.
401
+ * @returns The url without its query string and fragment, and its query
402
+ * params. If a param is repeated, its last value is kept.
403
+ */
404
+ export function splitQueryParams(url: string): {
405
+ url: string;
406
+ queryParams: Record<string, string>;
407
+ } {
408
+ if (!isValidUrl(url)) {
409
+ return { url, queryParams: {} };
410
+ }
411
+
412
+ const { search, searchParams } = new URL(url);
413
+ if (search === "") {
414
+ return { url, queryParams: {} };
415
+ }
416
+
417
+ return {
418
+ // Slicing keeps the rest of the url as it was, while serializing the URL
419
+ // object would normalize it
420
+ url: url.slice(0, url.indexOf("?")),
421
+ queryParams: Object.fromEntries(searchParams),
422
+ };
423
+ }
424
+
392
425
  /**
393
426
  * Returns the proxy url from environment variables based on the target url.
394
427
  * For HTTPS urls, checks `https_proxy` then `HTTPS_PROXY`.