c94010a5234e8a123a6d3e980a71f22c503bedf884173b97c552054f8c89c3efbca1dba0e28077702997a81c05fee68ef4f50f83c220b99a4628e62e160462 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. /**
  2. * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using:
  3. *
  4. * ```js
  5. * import v8 from 'node:v8';
  6. * ```
  7. * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js)
  8. */
  9. declare module "v8" {
  10. import { Readable } from "node:stream";
  11. interface HeapSpaceInfo {
  12. space_name: string;
  13. space_size: number;
  14. space_used_size: number;
  15. space_available_size: number;
  16. physical_space_size: number;
  17. }
  18. // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */
  19. type DoesZapCodeSpaceFlag = 0 | 1;
  20. interface HeapInfo {
  21. total_heap_size: number;
  22. total_heap_size_executable: number;
  23. total_physical_size: number;
  24. total_available_size: number;
  25. used_heap_size: number;
  26. heap_size_limit: number;
  27. malloced_memory: number;
  28. peak_malloced_memory: number;
  29. does_zap_garbage: DoesZapCodeSpaceFlag;
  30. number_of_native_contexts: number;
  31. number_of_detached_contexts: number;
  32. total_global_handles_size: number;
  33. used_global_handles_size: number;
  34. external_memory: number;
  35. }
  36. interface HeapCodeStatistics {
  37. code_and_metadata_size: number;
  38. bytecode_and_metadata_size: number;
  39. external_script_source_size: number;
  40. }
  41. interface HeapSnapshotOptions {
  42. /**
  43. * If true, expose internals in the heap snapshot.
  44. * @default false
  45. */
  46. exposeInternals?: boolean;
  47. /**
  48. * If true, expose numeric values in artificial fields.
  49. * @default false
  50. */
  51. exposeNumericValues?: boolean;
  52. }
  53. /**
  54. * Returns an integer representing a version tag derived from the V8 version,
  55. * command-line flags, and detected CPU features. This is useful for determining
  56. * whether a `vm.Script` `cachedData` buffer is compatible with this instance
  57. * of V8.
  58. *
  59. * ```js
  60. * console.log(v8.cachedDataVersionTag()); // 3947234607
  61. * // The value returned by v8.cachedDataVersionTag() is derived from the V8
  62. * // version, command-line flags, and detected CPU features. Test that the value
  63. * // does indeed update when flags are toggled.
  64. * v8.setFlagsFromString('--allow_natives_syntax');
  65. * console.log(v8.cachedDataVersionTag()); // 183726201
  66. * ```
  67. * @since v8.0.0
  68. */
  69. function cachedDataVersionTag(): number;
  70. /**
  71. * Returns an object with the following properties:
  72. *
  73. * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap
  74. * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
  75. * because it continuously touches all heap pages and that makes them less likely
  76. * to get swapped out by the operating system.
  77. *
  78. * `number_of_native_contexts` The value of native\_context is the number of the
  79. * top-level contexts currently active. Increase of this number over time indicates
  80. * a memory leak.
  81. *
  82. * `number_of_detached_contexts` The value of detached\_context is the number
  83. * of contexts that were detached and not yet garbage collected. This number
  84. * being non-zero indicates a potential memory leak.
  85. *
  86. * `total_global_handles_size` The value of total\_global\_handles\_size is the
  87. * total memory size of V8 global handles.
  88. *
  89. * `used_global_handles_size` The value of used\_global\_handles\_size is the
  90. * used memory size of V8 global handles.
  91. *
  92. * `external_memory` The value of external\_memory is the memory size of array
  93. * buffers and external strings.
  94. *
  95. * ```js
  96. * {
  97. * total_heap_size: 7326976,
  98. * total_heap_size_executable: 4194304,
  99. * total_physical_size: 7326976,
  100. * total_available_size: 1152656,
  101. * used_heap_size: 3476208,
  102. * heap_size_limit: 1535115264,
  103. * malloced_memory: 16384,
  104. * peak_malloced_memory: 1127496,
  105. * does_zap_garbage: 0,
  106. * number_of_native_contexts: 1,
  107. * number_of_detached_contexts: 0,
  108. * total_global_handles_size: 8192,
  109. * used_global_handles_size: 3296,
  110. * external_memory: 318824
  111. * }
  112. * ```
  113. * @since v1.0.0
  114. */
  115. function getHeapStatistics(): HeapInfo;
  116. /**
  117. * It returns an object with a structure similar to the
  118. * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html)
  119. * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html)
  120. * for more information about the properties of the object.
  121. *
  122. * ```js
  123. * // Detailed
  124. * ({
  125. * committed_size_bytes: 131072,
  126. * resident_size_bytes: 131072,
  127. * used_size_bytes: 152,
  128. * space_statistics: [
  129. * {
  130. * name: 'NormalPageSpace0',
  131. * committed_size_bytes: 0,
  132. * resident_size_bytes: 0,
  133. * used_size_bytes: 0,
  134. * page_stats: [{}],
  135. * free_list_stats: {},
  136. * },
  137. * {
  138. * name: 'NormalPageSpace1',
  139. * committed_size_bytes: 131072,
  140. * resident_size_bytes: 131072,
  141. * used_size_bytes: 152,
  142. * page_stats: [{}],
  143. * free_list_stats: {},
  144. * },
  145. * {
  146. * name: 'NormalPageSpace2',
  147. * committed_size_bytes: 0,
  148. * resident_size_bytes: 0,
  149. * used_size_bytes: 0,
  150. * page_stats: [{}],
  151. * free_list_stats: {},
  152. * },
  153. * {
  154. * name: 'NormalPageSpace3',
  155. * committed_size_bytes: 0,
  156. * resident_size_bytes: 0,
  157. * used_size_bytes: 0,
  158. * page_stats: [{}],
  159. * free_list_stats: {},
  160. * },
  161. * {
  162. * name: 'LargePageSpace',
  163. * committed_size_bytes: 0,
  164. * resident_size_bytes: 0,
  165. * used_size_bytes: 0,
  166. * page_stats: [{}],
  167. * free_list_stats: {},
  168. * },
  169. * ],
  170. * type_names: [],
  171. * detail_level: 'detailed',
  172. * });
  173. * ```
  174. *
  175. * ```js
  176. * // Brief
  177. * ({
  178. * committed_size_bytes: 131072,
  179. * resident_size_bytes: 131072,
  180. * used_size_bytes: 128864,
  181. * space_statistics: [],
  182. * type_names: [],
  183. * detail_level: 'brief',
  184. * });
  185. * ```
  186. * @since v22.15.0
  187. * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics.
  188. * Accepted values are:
  189. * * `'brief'`: Brief statistics contain only the top-level
  190. * allocated and used
  191. * memory statistics for the entire heap.
  192. * * `'detailed'`: Detailed statistics also contain a break
  193. * down per space and page, as well as freelist statistics
  194. * and object type histograms.
  195. */
  196. function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object;
  197. /**
  198. * Returns statistics about the V8 heap spaces, i.e. the segments which make up
  199. * the V8 heap. Neither the ordering of heap spaces, nor the availability of a
  200. * heap space can be guaranteed as the statistics are provided via the
  201. * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the
  202. * next.
  203. *
  204. * The value returned is an array of objects containing the following properties:
  205. *
  206. * ```json
  207. * [
  208. * {
  209. * "space_name": "new_space",
  210. * "space_size": 2063872,
  211. * "space_used_size": 951112,
  212. * "space_available_size": 80824,
  213. * "physical_space_size": 2063872
  214. * },
  215. * {
  216. * "space_name": "old_space",
  217. * "space_size": 3090560,
  218. * "space_used_size": 2493792,
  219. * "space_available_size": 0,
  220. * "physical_space_size": 3090560
  221. * },
  222. * {
  223. * "space_name": "code_space",
  224. * "space_size": 1260160,
  225. * "space_used_size": 644256,
  226. * "space_available_size": 960,
  227. * "physical_space_size": 1260160
  228. * },
  229. * {
  230. * "space_name": "map_space",
  231. * "space_size": 1094160,
  232. * "space_used_size": 201608,
  233. * "space_available_size": 0,
  234. * "physical_space_size": 1094160
  235. * },
  236. * {
  237. * "space_name": "large_object_space",
  238. * "space_size": 0,
  239. * "space_used_size": 0,
  240. * "space_available_size": 1490980608,
  241. * "physical_space_size": 0
  242. * }
  243. * ]
  244. * ```
  245. * @since v6.0.0
  246. */
  247. function getHeapSpaceStatistics(): HeapSpaceInfo[];
  248. /**
  249. * The `v8.setFlagsFromString()` method can be used to programmatically set
  250. * V8 command-line flags. This method should be used with care. Changing settings
  251. * after the VM has started may result in unpredictable behavior, including
  252. * crashes and data loss; or it may simply do nothing.
  253. *
  254. * The V8 options available for a version of Node.js may be determined by running `node --v8-options`.
  255. *
  256. * Usage:
  257. *
  258. * ```js
  259. * // Print GC events to stdout for one minute.
  260. * import v8 from 'node:v8';
  261. * v8.setFlagsFromString('--trace_gc');
  262. * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
  263. * ```
  264. * @since v1.0.0
  265. */
  266. function setFlagsFromString(flags: string): void;
  267. /**
  268. * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function)
  269. * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain
  270. * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should
  271. * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the
  272. * application.
  273. *
  274. * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects
  275. * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided
  276. * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the
  277. * target objects during the search.
  278. *
  279. * Only objects created in the current execution context are included in the results.
  280. *
  281. * ```js
  282. * import { queryObjects } from 'node:v8';
  283. * class A { foo = 'bar'; }
  284. * console.log(queryObjects(A)); // 0
  285. * const a = new A();
  286. * console.log(queryObjects(A)); // 1
  287. * // [ "A { foo: 'bar' }" ]
  288. * console.log(queryObjects(A, { format: 'summary' }));
  289. *
  290. * class B extends A { bar = 'qux'; }
  291. * const b = new B();
  292. * console.log(queryObjects(B)); // 1
  293. * // [ "B { foo: 'bar', bar: 'qux' }" ]
  294. * console.log(queryObjects(B, { format: 'summary' }));
  295. *
  296. * // Note that, when there are child classes inheriting from a constructor,
  297. * // the constructor also shows up in the prototype chain of the child
  298. * // classes's prototoype, so the child classes's prototoype would also be
  299. * // included in the result.
  300. * console.log(queryObjects(A)); // 3
  301. * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]
  302. * console.log(queryObjects(A, { format: 'summary' }));
  303. * ```
  304. * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap.
  305. * @since v20.13.0
  306. * @experimental
  307. */
  308. function queryObjects(ctor: Function): number | string[];
  309. function queryObjects(ctor: Function, options: { format: "count" }): number;
  310. function queryObjects(ctor: Function, options: { format: "summary" }): string[];
  311. /**
  312. * Generates a snapshot of the current V8 heap and returns a Readable
  313. * Stream that may be used to read the JSON serialized representation.
  314. * This JSON stream format is intended to be used with tools such as
  315. * Chrome DevTools. The JSON schema is undocumented and specific to the
  316. * V8 engine. Therefore, the schema may change from one version of V8 to the next.
  317. *
  318. * Creating a heap snapshot requires memory about twice the size of the heap at
  319. * the time the snapshot is created. This results in the risk of OOM killers
  320. * terminating the process.
  321. *
  322. * Generating a snapshot is a synchronous operation which blocks the event loop
  323. * for a duration depending on the heap size.
  324. *
  325. * ```js
  326. * // Print heap snapshot to the console
  327. * import v8 from 'node:v8';
  328. * const stream = v8.getHeapSnapshot();
  329. * stream.pipe(process.stdout);
  330. * ```
  331. * @since v11.13.0
  332. * @return A Readable containing the V8 heap snapshot.
  333. */
  334. function getHeapSnapshot(options?: HeapSnapshotOptions): Readable;
  335. /**
  336. * Generates a snapshot of the current V8 heap and writes it to a JSON
  337. * file. This file is intended to be used with tools such as Chrome
  338. * DevTools. The JSON schema is undocumented and specific to the V8
  339. * engine, and may change from one version of V8 to the next.
  340. *
  341. * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will
  342. * not contain any information about the workers, and vice versa.
  343. *
  344. * Creating a heap snapshot requires memory about twice the size of the heap at
  345. * the time the snapshot is created. This results in the risk of OOM killers
  346. * terminating the process.
  347. *
  348. * Generating a snapshot is a synchronous operation which blocks the event loop
  349. * for a duration depending on the heap size.
  350. *
  351. * ```js
  352. * import { writeHeapSnapshot } from 'node:v8';
  353. * import {
  354. * Worker,
  355. * isMainThread,
  356. * parentPort,
  357. * } from 'node:worker_threads';
  358. *
  359. * if (isMainThread) {
  360. * const worker = new Worker(__filename);
  361. *
  362. * worker.once('message', (filename) => {
  363. * console.log(`worker heapdump: ${filename}`);
  364. * // Now get a heapdump for the main thread.
  365. * console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
  366. * });
  367. *
  368. * // Tell the worker to create a heapdump.
  369. * worker.postMessage('heapdump');
  370. * } else {
  371. * parentPort.once('message', (message) => {
  372. * if (message === 'heapdump') {
  373. * // Generate a heapdump for the worker
  374. * // and return the filename to the parent.
  375. * parentPort.postMessage(writeHeapSnapshot());
  376. * }
  377. * });
  378. * }
  379. * ```
  380. * @since v11.13.0
  381. * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be
  382. * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a
  383. * worker thread.
  384. * @return The filename where the snapshot was saved.
  385. */
  386. function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string;
  387. /**
  388. * Get statistics about code and its metadata in the heap, see
  389. * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the
  390. * following properties:
  391. *
  392. * ```js
  393. * {
  394. * code_and_metadata_size: 212208,
  395. * bytecode_and_metadata_size: 161368,
  396. * external_script_source_size: 1410794,
  397. * cpu_profiler_metadata_size: 0,
  398. * }
  399. * ```
  400. * @since v12.8.0
  401. */
  402. function getHeapCodeStatistics(): HeapCodeStatistics;
  403. /**
  404. * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.
  405. * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;
  406. * otherwise, it returns false.
  407. *
  408. * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.
  409. * Sometimes a `Latin-1` string may also be represented as `UTF16`.
  410. *
  411. * ```js
  412. * const { isStringOneByteRepresentation } = require('node:v8');
  413. *
  414. * const Encoding = {
  415. * latin1: 1,
  416. * utf16le: 2,
  417. * };
  418. * const buffer = Buffer.alloc(100);
  419. * function writeString(input) {
  420. * if (isStringOneByteRepresentation(input)) {
  421. * buffer.writeUint8(Encoding.latin1);
  422. * buffer.writeUint32LE(input.length, 1);
  423. * buffer.write(input, 5, 'latin1');
  424. * } else {
  425. * buffer.writeUint8(Encoding.utf16le);
  426. * buffer.writeUint32LE(input.length * 2, 1);
  427. * buffer.write(input, 5, 'utf16le');
  428. * }
  429. * }
  430. * writeString('hello');
  431. * writeString('你好');
  432. * ```
  433. * @since v23.10.0, v22.15.0
  434. */
  435. function isStringOneByteRepresentation(content: string): boolean;
  436. /**
  437. * @since v8.0.0
  438. */
  439. class Serializer {
  440. /**
  441. * Writes out a header, which includes the serialization format version.
  442. */
  443. writeHeader(): void;
  444. /**
  445. * Serializes a JavaScript value and adds the serialized representation to the
  446. * internal buffer.
  447. *
  448. * This throws an error if `value` cannot be serialized.
  449. */
  450. writeValue(val: any): boolean;
  451. /**
  452. * Returns the stored internal buffer. This serializer should not be used once
  453. * the buffer is released. Calling this method results in undefined behavior
  454. * if a previous write has failed.
  455. */
  456. releaseBuffer(): Buffer;
  457. /**
  458. * Marks an `ArrayBuffer` as having its contents transferred out of band.
  459. * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`.
  460. * @param id A 32-bit unsigned integer.
  461. * @param arrayBuffer An `ArrayBuffer` instance.
  462. */
  463. transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
  464. /**
  465. * Write a raw 32-bit unsigned integer.
  466. * For use inside of a custom `serializer._writeHostObject()`.
  467. */
  468. writeUint32(value: number): void;
  469. /**
  470. * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
  471. * For use inside of a custom `serializer._writeHostObject()`.
  472. */
  473. writeUint64(hi: number, lo: number): void;
  474. /**
  475. * Write a JS `number` value.
  476. * For use inside of a custom `serializer._writeHostObject()`.
  477. */
  478. writeDouble(value: number): void;
  479. /**
  480. * Write raw bytes into the serializer's internal buffer. The deserializer
  481. * will require a way to compute the length of the buffer.
  482. * For use inside of a custom `serializer._writeHostObject()`.
  483. */
  484. writeRawBytes(buffer: NodeJS.TypedArray): void;
  485. }
  486. /**
  487. * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only
  488. * stores the part of their underlying `ArrayBuffer`s that they are referring to.
  489. * @since v8.0.0
  490. */
  491. class DefaultSerializer extends Serializer {}
  492. /**
  493. * @since v8.0.0
  494. */
  495. class Deserializer {
  496. constructor(data: NodeJS.TypedArray);
  497. /**
  498. * Reads and validates a header (including the format version).
  499. * May, for example, reject an invalid or unsupported wire format. In that case,
  500. * an `Error` is thrown.
  501. */
  502. readHeader(): boolean;
  503. /**
  504. * Deserializes a JavaScript value from the buffer and returns it.
  505. */
  506. readValue(): any;
  507. /**
  508. * Marks an `ArrayBuffer` as having its contents transferred out of band.
  509. * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of
  510. * `SharedArrayBuffer`s).
  511. * @param id A 32-bit unsigned integer.
  512. * @param arrayBuffer An `ArrayBuffer` instance.
  513. */
  514. transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;
  515. /**
  516. * Reads the underlying wire format version. Likely mostly to be useful to
  517. * legacy code reading old wire format versions. May not be called before `.readHeader()`.
  518. */
  519. getWireFormatVersion(): number;
  520. /**
  521. * Read a raw 32-bit unsigned integer and return it.
  522. * For use inside of a custom `deserializer._readHostObject()`.
  523. */
  524. readUint32(): number;
  525. /**
  526. * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries.
  527. * For use inside of a custom `deserializer._readHostObject()`.
  528. */
  529. readUint64(): [number, number];
  530. /**
  531. * Read a JS `number` value.
  532. * For use inside of a custom `deserializer._readHostObject()`.
  533. */
  534. readDouble(): number;
  535. /**
  536. * Read raw bytes from the deserializer's internal buffer. The `length` parameter
  537. * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`.
  538. * For use inside of a custom `deserializer._readHostObject()`.
  539. */
  540. readRawBytes(length: number): Buffer;
  541. }
  542. /**
  543. * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`.
  544. * @since v8.0.0
  545. */
  546. class DefaultDeserializer extends Deserializer {}
  547. /**
  548. * Uses a `DefaultSerializer` to serialize `value` into a buffer.
  549. *
  550. * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to
  551. * serialize a huge object which requires buffer
  552. * larger than `buffer.constants.MAX_LENGTH`.
  553. * @since v8.0.0
  554. */
  555. function serialize(value: any): Buffer;
  556. /**
  557. * Uses a `DefaultDeserializer` with default options to read a JS value
  558. * from a buffer.
  559. * @since v8.0.0
  560. * @param buffer A buffer returned by {@link serialize}.
  561. */
  562. function deserialize(buffer: NodeJS.ArrayBufferView): any;
  563. /**
  564. * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple
  565. * times during the lifetime of the process. Each time the execution counter will
  566. * be reset and a new coverage report will be written to the directory specified
  567. * by `NODE_V8_COVERAGE`.
  568. *
  569. * When the process is about to exit, one last coverage will still be written to
  570. * disk unless {@link stopCoverage} is invoked before the process exits.
  571. * @since v15.1.0, v14.18.0, v12.22.0
  572. */
  573. function takeCoverage(): void;
  574. /**
  575. * The `v8.stopCoverage()` method allows the user to stop the coverage collection
  576. * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count
  577. * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand.
  578. * @since v15.1.0, v14.18.0, v12.22.0
  579. */
  580. function stopCoverage(): void;
  581. /**
  582. * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once.
  583. * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
  584. * @since v18.10.0, v16.18.0
  585. */
  586. function setHeapSnapshotNearHeapLimit(limit: number): void;
  587. /**
  588. * This API collects GC data in current thread.
  589. * @since v19.6.0, v18.15.0
  590. */
  591. class GCProfiler {
  592. /**
  593. * Start collecting GC data.
  594. * @since v19.6.0, v18.15.0
  595. */
  596. start(): void;
  597. /**
  598. * Stop collecting GC data and return an object. The content of object
  599. * is as follows.
  600. *
  601. * ```json
  602. * {
  603. * "version": 1,
  604. * "startTime": 1674059033862,
  605. * "statistics": [
  606. * {
  607. * "gcType": "Scavenge",
  608. * "beforeGC": {
  609. * "heapStatistics": {
  610. * "totalHeapSize": 5005312,
  611. * "totalHeapSizeExecutable": 524288,
  612. * "totalPhysicalSize": 5226496,
  613. * "totalAvailableSize": 4341325216,
  614. * "totalGlobalHandlesSize": 8192,
  615. * "usedGlobalHandlesSize": 2112,
  616. * "usedHeapSize": 4883840,
  617. * "heapSizeLimit": 4345298944,
  618. * "mallocedMemory": 254128,
  619. * "externalMemory": 225138,
  620. * "peakMallocedMemory": 181760
  621. * },
  622. * "heapSpaceStatistics": [
  623. * {
  624. * "spaceName": "read_only_space",
  625. * "spaceSize": 0,
  626. * "spaceUsedSize": 0,
  627. * "spaceAvailableSize": 0,
  628. * "physicalSpaceSize": 0
  629. * }
  630. * ]
  631. * },
  632. * "cost": 1574.14,
  633. * "afterGC": {
  634. * "heapStatistics": {
  635. * "totalHeapSize": 6053888,
  636. * "totalHeapSizeExecutable": 524288,
  637. * "totalPhysicalSize": 5500928,
  638. * "totalAvailableSize": 4341101384,
  639. * "totalGlobalHandlesSize": 8192,
  640. * "usedGlobalHandlesSize": 2112,
  641. * "usedHeapSize": 4059096,
  642. * "heapSizeLimit": 4345298944,
  643. * "mallocedMemory": 254128,
  644. * "externalMemory": 225138,
  645. * "peakMallocedMemory": 181760
  646. * },
  647. * "heapSpaceStatistics": [
  648. * {
  649. * "spaceName": "read_only_space",
  650. * "spaceSize": 0,
  651. * "spaceUsedSize": 0,
  652. * "spaceAvailableSize": 0,
  653. * "physicalSpaceSize": 0
  654. * }
  655. * ]
  656. * }
  657. * }
  658. * ],
  659. * "endTime": 1674059036865
  660. * }
  661. * ```
  662. *
  663. * Here's an example.
  664. *
  665. * ```js
  666. * import { GCProfiler } from 'node:v8';
  667. * const profiler = new GCProfiler();
  668. * profiler.start();
  669. * setTimeout(() => {
  670. * console.log(profiler.stop());
  671. * }, 1000);
  672. * ```
  673. * @since v19.6.0, v18.15.0
  674. */
  675. stop(): GCProfilerResult;
  676. }
  677. interface GCProfilerResult {
  678. version: number;
  679. startTime: number;
  680. endTime: number;
  681. statistics: Array<{
  682. gcType: string;
  683. cost: number;
  684. beforeGC: {
  685. heapStatistics: HeapStatistics;
  686. heapSpaceStatistics: HeapSpaceStatistics[];
  687. };
  688. afterGC: {
  689. heapStatistics: HeapStatistics;
  690. heapSpaceStatistics: HeapSpaceStatistics[];
  691. };
  692. }>;
  693. }
  694. interface HeapStatistics {
  695. totalHeapSize: number;
  696. totalHeapSizeExecutable: number;
  697. totalPhysicalSize: number;
  698. totalAvailableSize: number;
  699. totalGlobalHandlesSize: number;
  700. usedGlobalHandlesSize: number;
  701. usedHeapSize: number;
  702. heapSizeLimit: number;
  703. mallocedMemory: number;
  704. externalMemory: number;
  705. peakMallocedMemory: number;
  706. }
  707. interface HeapSpaceStatistics {
  708. spaceName: string;
  709. spaceSize: number;
  710. spaceUsedSize: number;
  711. spaceAvailableSize: number;
  712. physicalSpaceSize: number;
  713. }
  714. /**
  715. * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will
  716. * happen if a promise is created without ever getting a continuation.
  717. * @since v17.1.0, v16.14.0
  718. * @param promise The promise being created.
  719. * @param parent The promise continued from, if applicable.
  720. */
  721. interface Init {
  722. (promise: Promise<unknown>, parent: Promise<unknown>): void;
  723. }
  724. /**
  725. * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming.
  726. *
  727. * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise.
  728. * The before callback may be called many times in the case where many continuations have been made from the same promise.
  729. * @since v17.1.0, v16.14.0
  730. */
  731. interface Before {
  732. (promise: Promise<unknown>): void;
  733. }
  734. /**
  735. * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await.
  736. * @since v17.1.0, v16.14.0
  737. */
  738. interface After {
  739. (promise: Promise<unknown>): void;
  740. }
  741. /**
  742. * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or
  743. * {@link Promise.reject()}.
  744. * @since v17.1.0, v16.14.0
  745. */
  746. interface Settled {
  747. (promise: Promise<unknown>): void;
  748. }
  749. /**
  750. * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or
  751. * around an await, and when the promise resolves or rejects.
  752. *
  753. * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and
  754. * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop.
  755. * @since v17.1.0, v16.14.0
  756. */
  757. interface HookCallbacks {
  758. init?: Init;
  759. before?: Before;
  760. after?: After;
  761. settled?: Settled;
  762. }
  763. interface PromiseHooks {
  764. /**
  765. * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  766. * @since v17.1.0, v16.14.0
  767. * @param init The {@link Init | `init` callback} to call when a promise is created.
  768. * @return Call to stop the hook.
  769. */
  770. onInit: (init: Init) => Function;
  771. /**
  772. * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  773. * @since v17.1.0, v16.14.0
  774. * @param settled The {@link Settled | `settled` callback} to call when a promise is created.
  775. * @return Call to stop the hook.
  776. */
  777. onSettled: (settled: Settled) => Function;
  778. /**
  779. * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  780. * @since v17.1.0, v16.14.0
  781. * @param before The {@link Before | `before` callback} to call before a promise continuation executes.
  782. * @return Call to stop the hook.
  783. */
  784. onBefore: (before: Before) => Function;
  785. /**
  786. * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.
  787. * @since v17.1.0, v16.14.0
  788. * @param after The {@link After | `after` callback} to call after a promise continuation executes.
  789. * @return Call to stop the hook.
  790. */
  791. onAfter: (after: After) => Function;
  792. /**
  793. * Registers functions to be called for different lifetime events of each promise.
  794. * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime.
  795. * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed.
  796. * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop.
  797. * @since v17.1.0, v16.14.0
  798. * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register
  799. * @return Used for disabling hooks
  800. */
  801. createHook: (callbacks: HookCallbacks) => Function;
  802. }
  803. /**
  804. * The `promiseHooks` interface can be used to track promise lifecycle events.
  805. * @since v17.1.0, v16.14.0
  806. */
  807. const promiseHooks: PromiseHooks;
  808. type StartupSnapshotCallbackFn = (args: any) => any;
  809. /**
  810. * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.
  811. *
  812. * ```bash
  813. * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js
  814. * # This launches a process with the snapshot
  815. * $ node --snapshot-blob snapshot.blob
  816. * ```
  817. *
  818. * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects
  819. * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot.
  820. * For example, if the `entry.js` contains the following script:
  821. *
  822. * ```js
  823. * 'use strict';
  824. *
  825. * import fs from 'node:fs';
  826. * import zlib from 'node:zlib';
  827. * import path from 'node:path';
  828. * import assert from 'node:assert';
  829. *
  830. * import v8 from 'node:v8';
  831. *
  832. * class BookShelf {
  833. * storage = new Map();
  834. *
  835. * // Reading a series of files from directory and store them into storage.
  836. * constructor(directory, books) {
  837. * for (const book of books) {
  838. * this.storage.set(book, fs.readFileSync(path.join(directory, book)));
  839. * }
  840. * }
  841. *
  842. * static compressAll(shelf) {
  843. * for (const [ book, content ] of shelf.storage) {
  844. * shelf.storage.set(book, zlib.gzipSync(content));
  845. * }
  846. * }
  847. *
  848. * static decompressAll(shelf) {
  849. * for (const [ book, content ] of shelf.storage) {
  850. * shelf.storage.set(book, zlib.gunzipSync(content));
  851. * }
  852. * }
  853. * }
  854. *
  855. * // __dirname here is where the snapshot script is placed
  856. * // during snapshot building time.
  857. * const shelf = new BookShelf(__dirname, [
  858. * 'book1.en_US.txt',
  859. * 'book1.es_ES.txt',
  860. * 'book2.zh_CN.txt',
  861. * ]);
  862. *
  863. * assert(v8.startupSnapshot.isBuildingSnapshot());
  864. * // On snapshot serialization, compress the books to reduce size.
  865. * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
  866. * // On snapshot deserialization, decompress the books.
  867. * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
  868. * v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
  869. * // process.env and process.argv are refreshed during snapshot
  870. * // deserialization.
  871. * const lang = process.env.BOOK_LANG || 'en_US';
  872. * const book = process.argv[1];
  873. * const name = `${book}.${lang}.txt`;
  874. * console.log(shelf.storage.get(name));
  875. * }, shelf);
  876. * ```
  877. *
  878. * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process:
  879. *
  880. * ```bash
  881. * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1
  882. * # Prints content of book1.es_ES.txt deserialized from the snapshot.
  883. * ```
  884. *
  885. * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.
  886. *
  887. * @since v18.6.0, v16.17.0
  888. */
  889. namespace startupSnapshot {
  890. /**
  891. * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.
  892. * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization.
  893. * @since v18.6.0, v16.17.0
  894. */
  895. function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
  896. /**
  897. * Add a callback that will be called when the Node.js instance is deserialized from a snapshot.
  898. * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or
  899. * to re-acquire resources that the application needs when the application is restarted from the snapshot.
  900. * @since v18.6.0, v16.17.0
  901. */
  902. function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;
  903. /**
  904. * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script.
  905. * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized
  906. * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.
  907. * @since v18.6.0, v16.17.0
  908. */
  909. function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;
  910. /**
  911. * Returns true if the Node.js instance is run to build a snapshot.
  912. * @since v18.6.0, v16.17.0
  913. */
  914. function isBuildingSnapshot(): boolean;
  915. }
  916. }
  917. declare module "node:v8" {
  918. export * from "v8";
  919. }