AK-21/Graphite-Industrial-Intelligence
0
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 * ```js5 * import v8 from 'node:v8';6 * ```7 * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js)8 */9declare module "v8" {10 import { NonSharedBuffer } from "node:buffer";11 import { Readable } from "node:stream";12 interface HeapSpaceInfo {13 space_name: string;14 space_size: number;15 space_used_size: number;16 space_available_size: number;17 physical_space_size: number;18 }19 // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */20 type DoesZapCodeSpaceFlag = 0 | 1;21 interface HeapInfo {22 total_heap_size: number;23 total_heap_size_executable: number;24 total_physical_size: number;25 total_available_size: number;26 used_heap_size: number;27 heap_size_limit: number;28 malloced_memory: number;29 peak_malloced_memory: number;30 does_zap_garbage: DoesZapCodeSpaceFlag;31 number_of_native_contexts: number;32 number_of_detached_contexts: number;33 total_global_handles_size: number;34 used_global_handles_size: number;35 external_memory: number;36 }37 interface HeapCodeStatistics {38 code_and_metadata_size: number;39 bytecode_and_metadata_size: number;40 external_script_source_size: number;41 }42 interface HeapSnapshotOptions {43 /**44 * If true, expose internals in the heap snapshot.45 * @default false46 */47 exposeInternals?: boolean | undefined;48 /**49 * If true, expose numeric values in artificial fields.50 * @default false51 */52 exposeNumericValues?: boolean | undefined;53 }54 /**55 * Returns an integer representing a version tag derived from the V8 version,56 * command-line flags, and detected CPU features. This is useful for determining57 * whether a `vm.Script` `cachedData` buffer is compatible with this instance58 * of V8.59 *60 * ```js61 * console.log(v8.cachedDataVersionTag()); // 394723460762 * // The value returned by v8.cachedDataVersionTag() is derived from the V863 * // version, command-line flags, and detected CPU features. Test that the value64 * // does indeed update when flags are toggled.65 * v8.setFlagsFromString('--allow_natives_syntax');66 * console.log(v8.cachedDataVersionTag()); // 18372620167 * ```68 * @since v8.0.069 */70 function cachedDataVersionTag(): number;71 /**72 * Returns an object with the following properties:73 *74 * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap75 * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger76 * because it continuously touches all heap pages and that makes them less likely77 * to get swapped out by the operating system.78 *79 * `number_of_native_contexts` The value of native\_context is the number of the80 * top-level contexts currently active. Increase of this number over time indicates81 * a memory leak.82 *83 * `number_of_detached_contexts` The value of detached\_context is the number84 * of contexts that were detached and not yet garbage collected. This number85 * being non-zero indicates a potential memory leak.86 *87 * `total_global_handles_size` The value of total\_global\_handles\_size is the88 * total memory size of V8 global handles.89 *90 * `used_global_handles_size` The value of used\_global\_handles\_size is the91 * used memory size of V8 global handles.92 *93 * `external_memory` The value of external\_memory is the memory size of array94 * buffers and external strings.95 *96 * ```js97 * {98 * total_heap_size: 7326976,99 * total_heap_size_executable: 4194304,100 * total_physical_size: 7326976,101 * total_available_size: 1152656,102 * used_heap_size: 3476208,103 * heap_size_limit: 1535115264,104 * malloced_memory: 16384,105 * peak_malloced_memory: 1127496,106 * does_zap_garbage: 0,107 * number_of_native_contexts: 1,108 * number_of_detached_contexts: 0,109 * total_global_handles_size: 8192,110 * used_global_handles_size: 3296,111 * external_memory: 318824112 * }113 * ```114 * @since v1.0.0115 */116 function getHeapStatistics(): HeapInfo;117 /**118 * It returns an object with a structure similar to the119 * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html)120 * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html)121 * for more information about the properties of the object.122 *123 * ```js124 * // Detailed125 * ({126 * committed_size_bytes: 131072,127 * resident_size_bytes: 131072,128 * used_size_bytes: 152,129 * space_statistics: [130 * {131 * name: 'NormalPageSpace0',132 * committed_size_bytes: 0,133 * resident_size_bytes: 0,134 * used_size_bytes: 0,135 * page_stats: [{}],136 * free_list_stats: {},137 * },138 * {139 * name: 'NormalPageSpace1',140 * committed_size_bytes: 131072,141 * resident_size_bytes: 131072,142 * used_size_bytes: 152,143 * page_stats: [{}],144 * free_list_stats: {},145 * },146 * {147 * name: 'NormalPageSpace2',148 * committed_size_bytes: 0,149 * resident_size_bytes: 0,150 * used_size_bytes: 0,151 * page_stats: [{}],152 * free_list_stats: {},153 * },154 * {155 * name: 'NormalPageSpace3',156 * committed_size_bytes: 0,157 * resident_size_bytes: 0,158 * used_size_bytes: 0,159 * page_stats: [{}],160 * free_list_stats: {},161 * },162 * {163 * name: 'LargePageSpace',164 * committed_size_bytes: 0,165 * resident_size_bytes: 0,166 * used_size_bytes: 0,167 * page_stats: [{}],168 * free_list_stats: {},169 * },170 * ],171 * type_names: [],172 * detail_level: 'detailed',173 * });174 * ```175 *176 * ```js177 * // Brief178 * ({179 * committed_size_bytes: 131072,180 * resident_size_bytes: 131072,181 * used_size_bytes: 128864,182 * space_statistics: [],183 * type_names: [],184 * detail_level: 'brief',185 * });186 * ```187 * @since v22.15.0188 * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics.189 * Accepted values are:190 * * `'brief'`: Brief statistics contain only the top-level191 * allocated and used192 * memory statistics for the entire heap.193 * * `'detailed'`: Detailed statistics also contain a break194 * down per space and page, as well as freelist statistics195 * and object type histograms.196 */197 function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object;198 /**199 * Returns statistics about the V8 heap spaces, i.e. the segments which make up200 * the V8 heap. Neither the ordering of heap spaces, nor the availability of a201 * heap space can be guaranteed as the statistics are provided via the202 * 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 the203 * next.204 *205 * The value returned is an array of objects containing the following properties:206 *207 * ```json208 * [209 * {210 * "space_name": "new_space",211 * "space_size": 2063872,212 * "space_used_size": 951112,213 * "space_available_size": 80824,214 * "physical_space_size": 2063872215 * },216 * {217 * "space_name": "old_space",218 * "space_size": 3090560,219 * "space_used_size": 2493792,220 * "space_available_size": 0,221 * "physical_space_size": 3090560222 * },223 * {224 * "space_name": "code_space",225 * "space_size": 1260160,226 * "space_used_size": 644256,227 * "space_available_size": 960,228 * "physical_space_size": 1260160229 * },230 * {231 * "space_name": "map_space",232 * "space_size": 1094160,233 * "space_used_size": 201608,234 * "space_available_size": 0,235 * "physical_space_size": 1094160236 * },237 * {238 * "space_name": "large_object_space",239 * "space_size": 0,240 * "space_used_size": 0,241 * "space_available_size": 1490980608,242 * "physical_space_size": 0243 * }244 * ]245 * ```246 * @since v6.0.0247 */248 function getHeapSpaceStatistics(): HeapSpaceInfo[];249 /**250 * The `v8.setFlagsFromString()` method can be used to programmatically set251 * V8 command-line flags. This method should be used with care. Changing settings252 * after the VM has started may result in unpredictable behavior, including253 * crashes and data loss; or it may simply do nothing.254 *255 * The V8 options available for a version of Node.js may be determined by running `node --v8-options`.256 *257 * Usage:258 *259 * ```js260 * // Print GC events to stdout for one minute.261 * import v8 from 'node:v8';262 * v8.setFlagsFromString('--trace_gc');263 * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);264 * ```265 * @since v1.0.0266 */267 function setFlagsFromString(flags: string): void;268 /**269 * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function)270 * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain271 * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should272 * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the273 * application.274 *275 * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects276 * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided277 * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the278 * target objects during the search.279 *280 * Only objects created in the current execution context are included in the results.281 *282 * ```js283 * import { queryObjects } from 'node:v8';284 * class A { foo = 'bar'; }285 * console.log(queryObjects(A)); // 0286 * const a = new A();287 * console.log(queryObjects(A)); // 1288 * // [ "A { foo: 'bar' }" ]289 * console.log(queryObjects(A, { format: 'summary' }));290 *291 * class B extends A { bar = 'qux'; }292 * const b = new B();293 * console.log(queryObjects(B)); // 1294 * // [ "B { foo: 'bar', bar: 'qux' }" ]295 * console.log(queryObjects(B, { format: 'summary' }));296 *297 * // Note that, when there are child classes inheriting from a constructor,298 * // the constructor also shows up in the prototype chain of the child299 * // classes's prototoype, so the child classes's prototoype would also be300 * // included in the result.301 * console.log(queryObjects(A)); // 3302 * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]303 * console.log(queryObjects(A, { format: 'summary' }));304 * ```305 * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap.306 * @since v20.13.0307 */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 Readable313 * Stream that may be used to read the JSON serialized representation.314 * This JSON stream format is intended to be used with tools such as315 * Chrome DevTools. The JSON schema is undocumented and specific to the316 * 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 at319 * the time the snapshot is created. This results in the risk of OOM killers320 * terminating the process.321 *322 * Generating a snapshot is a synchronous operation which blocks the event loop323 * for a duration depending on the heap size.324 *325 * ```js326 * // Print heap snapshot to the console327 * import v8 from 'node:v8';328 * const stream = v8.getHeapSnapshot();329 * stream.pipe(process.stdout);330 * ```331 * @since v11.13.0332 * @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 JSON337 * file. This file is intended to be used with tools such as Chrome338 * DevTools. The JSON schema is undocumented and specific to the V8339 * 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 will342 * 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 at345 * the time the snapshot is created. This results in the risk of OOM killers346 * terminating the process.347 *348 * Generating a snapshot is a synchronous operation which blocks the event loop349 * for a duration depending on the heap size.350 *351 * ```js352 * 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 worker374 * // and return the filename to the parent.375 * parentPort.postMessage(writeHeapSnapshot());376 * }377 * });378 * }379 * ```380 * @since v11.13.0381 * @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 be382 * 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 a383 * 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, see389 * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the390 * following properties:391 *392 * ```js393 * {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.0401 */402 function getHeapCodeStatistics(): HeapCodeStatistics;403 /**404 * @since v24.12.0405 */406 interface SyncCPUProfileHandle {407 /**408 * Stopping collecting the profile and return the profile data.409 * @since v24.12.0410 */411 stop(): string;412 /**413 * Stopping collecting the profile and the profile will be discarded.414 * @since v24.12.0415 */416 [Symbol.dispose](): void;417 }418 /**419 * @since v24.8.0420 */421 interface CPUProfileHandle {422 /**423 * Stopping collecting the profile, then return a Promise that fulfills with an error or the424 * profile data.425 * @since v24.8.0426 */427 stop(): Promise<string>;428 /**429 * Stopping collecting the profile and the profile will be discarded.430 * @since v24.8.0431 */432 [Symbol.asyncDispose](): Promise<void>;433 }434 /**435 * @since v24.9.0436 */437 interface HeapProfileHandle {438 /**439 * Stopping collecting the profile, then return a Promise that fulfills with an error or the440 * profile data.441 * @since v24.9.0442 */443 stop(): Promise<string>;444 /**445 * Stopping collecting the profile and the profile will be discarded.446 * @since v24.9.0447 */448 [Symbol.asyncDispose](): Promise<void>;449 }450 /**451 * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.452 * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;453 * otherwise, it returns false.454 *455 * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.456 * Sometimes a `Latin-1` string may also be represented as `UTF16`.457 *458 * ```js459 * const { isStringOneByteRepresentation } = require('node:v8');460 *461 * const Encoding = {462 * latin1: 1,463 * utf16le: 2,464 * };465 * const buffer = Buffer.alloc(100);466 * function writeString(input) {467 * if (isStringOneByteRepresentation(input)) {468 * buffer.writeUint8(Encoding.latin1);469 * buffer.writeUint32LE(input.length, 1);470 * buffer.write(input, 5, 'latin1');471 * } else {472 * buffer.writeUint8(Encoding.utf16le);473 * buffer.writeUint32LE(input.length * 2, 1);474 * buffer.write(input, 5, 'utf16le');475 * }476 * }477 * writeString('hello');478 * writeString('你好');479 * ```480 * @since v23.10.0, v22.15.0481 */482 function isStringOneByteRepresentation(content: string): boolean;483 /**484 * Starting a CPU profile then return a `SyncCPUProfileHandle` object. This API supports `using` syntax.485 *486 * ```js487 * const handle = v8.startCpuProfile();488 * const profile = handle.stop();489 * console.log(profile);490 * ```491 * @since v24.12.0492 */493 function startCpuProfile(): SyncCPUProfileHandle;494 /**495 * @since v8.0.0496 */497 class Serializer {498 /**499 * Writes out a header, which includes the serialization format version.500 */501 writeHeader(): void;502 /**503 * Serializes a JavaScript value and adds the serialized representation to the504 * internal buffer.505 *506 * This throws an error if `value` cannot be serialized.507 */508 writeValue(val: any): boolean;509 /**510 * Returns the stored internal buffer. This serializer should not be used once511 * the buffer is released. Calling this method results in undefined behavior512 * if a previous write has failed.513 */514 releaseBuffer(): NonSharedBuffer;515 /**516 * Marks an `ArrayBuffer` as having its contents transferred out of band.517 * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`.518 * @param id A 32-bit unsigned integer.519 * @param arrayBuffer An `ArrayBuffer` instance.520 */521 transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;522 /**523 * Write a raw 32-bit unsigned integer.524 * For use inside of a custom `serializer._writeHostObject()`.525 */526 writeUint32(value: number): void;527 /**528 * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.529 * For use inside of a custom `serializer._writeHostObject()`.530 */531 writeUint64(hi: number, lo: number): void;532 /**533 * Write a JS `number` value.534 * For use inside of a custom `serializer._writeHostObject()`.535 */536 writeDouble(value: number): void;537 /**538 * Write raw bytes into the serializer's internal buffer. The deserializer539 * will require a way to compute the length of the buffer.540 * For use inside of a custom `serializer._writeHostObject()`.541 */542 writeRawBytes(buffer: NodeJS.ArrayBufferView): void;543 }544 /**545 * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only546 * stores the part of their underlying `ArrayBuffer`s that they are referring to.547 * @since v8.0.0548 */549 class DefaultSerializer extends Serializer {}550 /**551 * @since v8.0.0552 */553 class Deserializer {554 constructor(data: NodeJS.TypedArray);555 /**556 * Reads and validates a header (including the format version).557 * May, for example, reject an invalid or unsupported wire format. In that case,558 * an `Error` is thrown.559 */560 readHeader(): boolean;561 /**562 * Deserializes a JavaScript value from the buffer and returns it.563 */564 readValue(): any;565 /**566 * Marks an `ArrayBuffer` as having its contents transferred out of band.567 * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of568 * `SharedArrayBuffer`s).569 * @param id A 32-bit unsigned integer.570 * @param arrayBuffer An `ArrayBuffer` instance.571 */572 transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void;573 /**574 * Reads the underlying wire format version. Likely mostly to be useful to575 * legacy code reading old wire format versions. May not be called before `.readHeader()`.576 */577 getWireFormatVersion(): number;578 /**579 * Read a raw 32-bit unsigned integer and return it.580 * For use inside of a custom `deserializer._readHostObject()`.581 */582 readUint32(): number;583 /**584 * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries.585 * For use inside of a custom `deserializer._readHostObject()`.586 */587 readUint64(): [number, number];588 /**589 * Read a JS `number` value.590 * For use inside of a custom `deserializer._readHostObject()`.591 */592 readDouble(): number;593 /**594 * Read raw bytes from the deserializer's internal buffer. The `length` parameter595 * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`.596 * For use inside of a custom `deserializer._readHostObject()`.597 */598 readRawBytes(length: number): Buffer;599 }600 /**601 * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`.602 * @since v8.0.0603 */604 class DefaultDeserializer extends Deserializer {}605 /**606 * Uses a `DefaultSerializer` to serialize `value` into a buffer.607 *608 * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to609 * serialize a huge object which requires buffer610 * larger than `buffer.constants.MAX_LENGTH`.611 * @since v8.0.0612 */613 function serialize(value: any): NonSharedBuffer;614 /**615 * Uses a `DefaultDeserializer` with default options to read a JS value616 * from a buffer.617 * @since v8.0.0618 * @param buffer A buffer returned by {@link serialize}.619 */620 function deserialize(buffer: NodeJS.ArrayBufferView): any;621 /**622 * 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 multiple623 * times during the lifetime of the process. Each time the execution counter will624 * be reset and a new coverage report will be written to the directory specified625 * by `NODE_V8_COVERAGE`.626 *627 * When the process is about to exit, one last coverage will still be written to628 * disk unless {@link stopCoverage} is invoked before the process exits.629 * @since v15.1.0, v14.18.0, v12.22.0630 */631 function takeCoverage(): void;632 /**633 * The `v8.stopCoverage()` method allows the user to stop the coverage collection634 * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count635 * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand.636 * @since v15.1.0, v14.18.0, v12.22.0637 */638 function stopCoverage(): void;639 /**640 * 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.641 * `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.642 * @since v18.10.0, v16.18.0643 */644 function setHeapSnapshotNearHeapLimit(limit: number): void;645 /**646 * This API collects GC data in current thread.647 * @since v19.6.0, v18.15.0648 */649 class GCProfiler {650 /**651 * Start collecting GC data.652 * @since v19.6.0, v18.15.0653 */654 start(): void;655 /**656 * Stop collecting GC data and return an object. The content of object657 * is as follows.658 *659 * ```json660 * {661 * "version": 1,662 * "startTime": 1674059033862,663 * "statistics": [664 * {665 * "gcType": "Scavenge",666 * "beforeGC": {667 * "heapStatistics": {668 * "totalHeapSize": 5005312,669 * "totalHeapSizeExecutable": 524288,670 * "totalPhysicalSize": 5226496,671 * "totalAvailableSize": 4341325216,672 * "totalGlobalHandlesSize": 8192,673 * "usedGlobalHandlesSize": 2112,674 * "usedHeapSize": 4883840,675 * "heapSizeLimit": 4345298944,676 * "mallocedMemory": 254128,677 * "externalMemory": 225138,678 * "peakMallocedMemory": 181760679 * },680 * "heapSpaceStatistics": [681 * {682 * "spaceName": "read_only_space",683 * "spaceSize": 0,684 * "spaceUsedSize": 0,685 * "spaceAvailableSize": 0,686 * "physicalSpaceSize": 0687 * }688 * ]689 * },690 * "cost": 1574.14,691 * "afterGC": {692 * "heapStatistics": {693 * "totalHeapSize": 6053888,694 * "totalHeapSizeExecutable": 524288,695 * "totalPhysicalSize": 5500928,696 * "totalAvailableSize": 4341101384,697 * "totalGlobalHandlesSize": 8192,698 * "usedGlobalHandlesSize": 2112,699 * "usedHeapSize": 4059096,700 * "heapSizeLimit": 4345298944,701 * "mallocedMemory": 254128,702 * "externalMemory": 225138,703 * "peakMallocedMemory": 181760704 * },705 * "heapSpaceStatistics": [706 * {707 * "spaceName": "read_only_space",708 * "spaceSize": 0,709 * "spaceUsedSize": 0,710 * "spaceAvailableSize": 0,711 * "physicalSpaceSize": 0712 * }713 * ]714 * }715 * }716 * ],717 * "endTime": 1674059036865718 * }719 * ```720 *721 * Here's an example.722 *723 * ```js724 * import { GCProfiler } from 'node:v8';725 * const profiler = new GCProfiler();726 * profiler.start();727 * setTimeout(() => {728 * console.log(profiler.stop());729 * }, 1000);730 * ```731 * @since v19.6.0, v18.15.0732 */733 stop(): GCProfilerResult;734 /**735 * Stop collecting GC data, and discard the profile.736 * @since v24.13.0737 */738 [Symbol.dispose](): void;739 }740 interface GCProfilerResult {741 version: number;742 startTime: number;743 endTime: number;744 statistics: Array<{745 gcType: string;746 cost: number;747 beforeGC: {748 heapStatistics: HeapStatistics;749 heapSpaceStatistics: HeapSpaceStatistics[];750 };751 afterGC: {752 heapStatistics: HeapStatistics;753 heapSpaceStatistics: HeapSpaceStatistics[];754 };755 }>;756 }757 interface HeapStatistics {758 totalHeapSize: number;759 totalHeapSizeExecutable: number;760 totalPhysicalSize: number;761 totalAvailableSize: number;762 totalGlobalHandlesSize: number;763 usedGlobalHandlesSize: number;764 usedHeapSize: number;765 heapSizeLimit: number;766 mallocedMemory: number;767 externalMemory: number;768 peakMallocedMemory: number;769 }770 interface HeapSpaceStatistics {771 spaceName: string;772 spaceSize: number;773 spaceUsedSize: number;774 spaceAvailableSize: number;775 physicalSpaceSize: number;776 }777 /**778 * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will779 * happen if a promise is created without ever getting a continuation.780 * @since v17.1.0, v16.14.0781 * @param promise The promise being created.782 * @param parent The promise continued from, if applicable.783 */784 interface Init {785 (promise: Promise<unknown>, parent: Promise<unknown>): void;786 }787 /**788 * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming.789 *790 * 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.791 * The before callback may be called many times in the case where many continuations have been made from the same promise.792 * @since v17.1.0, v16.14.0793 */794 interface Before {795 (promise: Promise<unknown>): void;796 }797 /**798 * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await.799 * @since v17.1.0, v16.14.0800 */801 interface After {802 (promise: Promise<unknown>): void;803 }804 /**805 * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or806 * {@link Promise.reject()}.807 * @since v17.1.0, v16.14.0808 */809 interface Settled {810 (promise: Promise<unknown>): void;811 }812 /**813 * 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 or814 * around an await, and when the promise resolves or rejects.815 *816 * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and817 * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop.818 * @since v17.1.0, v16.14.0819 */820 interface HookCallbacks {821 init?: Init;822 before?: Before;823 after?: After;824 settled?: Settled;825 }826 interface PromiseHooks {827 /**828 * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.829 * @since v17.1.0, v16.14.0830 * @param init The {@link Init | `init` callback} to call when a promise is created.831 * @return Call to stop the hook.832 */833 onInit: (init: Init) => Function;834 /**835 * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.836 * @since v17.1.0, v16.14.0837 * @param settled The {@link Settled | `settled` callback} to call when a promise is created.838 * @return Call to stop the hook.839 */840 onSettled: (settled: Settled) => Function;841 /**842 * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.843 * @since v17.1.0, v16.14.0844 * @param before The {@link Before | `before` callback} to call before a promise continuation executes.845 * @return Call to stop the hook.846 */847 onBefore: (before: Before) => Function;848 /**849 * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop.850 * @since v17.1.0, v16.14.0851 * @param after The {@link After | `after` callback} to call after a promise continuation executes.852 * @return Call to stop the hook.853 */854 onAfter: (after: After) => Function;855 /**856 * Registers functions to be called for different lifetime events of each promise.857 * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime.858 * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed.859 * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop.860 * @since v17.1.0, v16.14.0861 * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register862 * @return Used for disabling hooks863 */864 createHook: (callbacks: HookCallbacks) => Function;865 }866 /**867 * The `promiseHooks` interface can be used to track promise lifecycle events.868 * @since v17.1.0, v16.14.0869 */870 const promiseHooks: PromiseHooks;871 type StartupSnapshotCallbackFn = (args: any) => any;872 /**873 * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.874 *875 * ```bash876 * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js877 * # This launches a process with the snapshot878 * $ node --snapshot-blob snapshot.blob879 * ```880 *881 * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects882 * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot.883 * For example, if the `entry.js` contains the following script:884 *885 * ```js886 * 'use strict';887 *888 * import fs from 'node:fs';889 * import zlib from 'node:zlib';890 * import path from 'node:path';891 * import assert from 'node:assert';892 *893 * import v8 from 'node:v8';894 *895 * class BookShelf {896 * storage = new Map();897 *898 * // Reading a series of files from directory and store them into storage.899 * constructor(directory, books) {900 * for (const book of books) {901 * this.storage.set(book, fs.readFileSync(path.join(directory, book)));902 * }903 * }904 *905 * static compressAll(shelf) {906 * for (const [ book, content ] of shelf.storage) {907 * shelf.storage.set(book, zlib.gzipSync(content));908 * }909 * }910 *911 * static decompressAll(shelf) {912 * for (const [ book, content ] of shelf.storage) {913 * shelf.storage.set(book, zlib.gunzipSync(content));914 * }915 * }916 * }917 *918 * // __dirname here is where the snapshot script is placed919 * // during snapshot building time.920 * const shelf = new BookShelf(__dirname, [921 * 'book1.en_US.txt',922 * 'book1.es_ES.txt',923 * 'book2.zh_CN.txt',924 * ]);925 *926 * assert(v8.startupSnapshot.isBuildingSnapshot());927 * // On snapshot serialization, compress the books to reduce size.928 * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);929 * // On snapshot deserialization, decompress the books.930 * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);931 * v8.startupSnapshot.setDeserializeMainFunction((shelf) => {932 * // process.env and process.argv are refreshed during snapshot933 * // deserialization.934 * const lang = process.env.BOOK_LANG || 'en_US';935 * const book = process.argv[1];936 * const name = `${book}.${lang}.txt`;937 * console.log(shelf.storage.get(name));938 * }, shelf);939 * ```940 *941 * 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:942 *943 * ```bash944 * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1945 * # Prints content of book1.es_ES.txt deserialized from the snapshot.946 * ```947 *948 * 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.949 *950 * @since v18.6.0, v16.17.0951 */952 namespace startupSnapshot {953 /**954 * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit.955 * 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.956 * @since v18.6.0, v16.17.0957 */958 function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;959 /**960 * Add a callback that will be called when the Node.js instance is deserialized from a snapshot.961 * 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 or962 * to re-acquire resources that the application needs when the application is restarted from the snapshot.963 * @since v18.6.0, v16.17.0964 */965 function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void;966 /**967 * 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.968 * 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 deserialized969 * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application.970 * @since v18.6.0, v16.17.0971 */972 function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void;973 /**974 * Returns true if the Node.js instance is run to build a snapshot.975 * @since v18.6.0, v16.17.0976 */977 function isBuildingSnapshot(): boolean;978 }979}980declare module "node:v8" {981 export * from "v8";982}983 