Pinsave/counterstrike
1
1/**2 * The `node:vm` module enables compiling and running code within V8 Virtual3 * Machine contexts.4 *5 * **The `node:vm` module is not a security**6 * **mechanism. Do not use it to run untrusted code.**7 *8 * JavaScript code can be compiled and run immediately or9 * compiled, saved, and run later.10 *11 * A common use case is to run the code in a different V8 Context. This means12 * invoked code has a different global object than the invoking code.13 *14 * One can provide the context by `contextifying` an15 * object. The invoked code treats any property in the context like a16 * global variable. Any changes to global variables caused by the invoked17 * code are reflected in the context object.18 *19 * ```js20 * import vm from 'node:vm';21 *22 * const x = 1;23 *24 * const context = { x: 2 };25 * vm.createContext(context); // Contextify the object.26 *27 * const code = 'x += 40; var y = 17;';28 * // `x` and `y` are global variables in the context.29 * // Initially, x has the value 2 because that is the value of context.x.30 * vm.runInContext(code, context);31 *32 * console.log(context.x); // 4233 * console.log(context.y); // 1734 *35 * console.log(x); // 1; y is not defined.36 * ```37 * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js)38 */39declare module "vm" {40 import { ImportAttributes } from "node:module";41 interface Context extends NodeJS.Dict<any> {}42 interface BaseOptions {43 /**44 * Specifies the filename used in stack traces produced by this script.45 * @default ''46 */47 filename?: string | undefined;48 /**49 * Specifies the line number offset that is displayed in stack traces produced by this script.50 * @default 051 */52 lineOffset?: number | undefined;53 /**54 * Specifies the column number offset that is displayed in stack traces produced by this script.55 * @default 056 */57 columnOffset?: number | undefined;58 }59 type DynamicModuleLoader<T> = (60 specifier: string,61 referrer: T,62 importAttributes: ImportAttributes,63 phase: "source" | "evaluation",64 ) => Module | Promise<Module>;65 interface ScriptOptions extends BaseOptions {66 /**67 * Provides an optional data with V8's code cache data for the supplied source.68 */69 cachedData?: Buffer | NodeJS.ArrayBufferView | undefined;70 /** @deprecated in favor of `script.createCachedData()` */71 produceCachedData?: boolean | undefined;72 /**73 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is74 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see75 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).76 * @experimental77 */78 importModuleDynamically?:79 | DynamicModuleLoader<Script>80 | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER81 | undefined;82 }83 interface RunningScriptOptions extends BaseOptions {84 /**85 * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace.86 * @default true87 */88 displayErrors?: boolean | undefined;89 /**90 * Specifies the number of milliseconds to execute code before terminating execution.91 * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer.92 */93 timeout?: number | undefined;94 /**95 * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received.96 * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that.97 * If execution is terminated, an `Error` will be thrown.98 * @default false99 */100 breakOnSigint?: boolean | undefined;101 }102 interface RunningScriptInNewContextOptions extends RunningScriptOptions {103 /**104 * Human-readable name of the newly created context.105 */106 contextName?: CreateContextOptions["name"];107 /**108 * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL,109 * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object.110 * Most notably, this string should omit the trailing slash, as that denotes a path.111 */112 contextOrigin?: CreateContextOptions["origin"];113 contextCodeGeneration?: CreateContextOptions["codeGeneration"];114 /**115 * If set to `afterEvaluate`, microtasks will be run immediately after the script has run.116 */117 microtaskMode?: CreateContextOptions["microtaskMode"];118 }119 interface RunningCodeOptions extends RunningScriptOptions {120 /**121 * Provides an optional data with V8's code cache data for the supplied source.122 */123 cachedData?: ScriptOptions["cachedData"] | undefined;124 /**125 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is126 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see127 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).128 * @experimental129 */130 importModuleDynamically?:131 | DynamicModuleLoader<Script>132 | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER133 | undefined;134 }135 interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions {136 /**137 * Provides an optional data with V8's code cache data for the supplied source.138 */139 cachedData?: ScriptOptions["cachedData"] | undefined;140 /**141 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is142 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see143 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).144 * @experimental145 */146 importModuleDynamically?:147 | DynamicModuleLoader<Script>148 | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER149 | undefined;150 }151 interface CompileFunctionOptions extends BaseOptions {152 /**153 * Provides an optional data with V8's code cache data for the supplied source.154 */155 cachedData?: ScriptOptions["cachedData"] | undefined;156 /**157 * Specifies whether to produce new cache data.158 * @default false159 */160 produceCachedData?: boolean | undefined;161 /**162 * The sandbox/context in which the said function should be compiled in.163 */164 parsingContext?: Context | undefined;165 /**166 * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling167 */168 contextExtensions?: Object[] | undefined;169 /**170 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is171 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see172 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).173 * @experimental174 */175 importModuleDynamically?:176 | DynamicModuleLoader<ReturnType<typeof compileFunction>>177 | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER178 | undefined;179 }180 interface CreateContextOptions {181 /**182 * Human-readable name of the newly created context.183 * @default 'VM Context i' Where i is an ascending numerical index of the created context.184 */185 name?: string | undefined;186 /**187 * Corresponds to the newly created context for display purposes.188 * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary),189 * like the value of the `url.origin` property of a URL object.190 * Most notably, this string should omit the trailing slash, as that denotes a path.191 * @default ''192 */193 origin?: string | undefined;194 codeGeneration?:195 | {196 /**197 * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc)198 * will throw an EvalError.199 * @default true200 */201 strings?: boolean | undefined;202 /**203 * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError.204 * @default true205 */206 wasm?: boolean | undefined;207 }208 | undefined;209 /**210 * If set to `afterEvaluate`, microtasks will be run immediately after the script has run.211 */212 microtaskMode?: "afterEvaluate" | undefined;213 /**214 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is215 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see216 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).217 * @experimental218 */219 importModuleDynamically?:220 | DynamicModuleLoader<Context>221 | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER222 | undefined;223 }224 type MeasureMemoryMode = "summary" | "detailed";225 interface MeasureMemoryOptions {226 /**227 * @default 'summary'228 */229 mode?: MeasureMemoryMode | undefined;230 /**231 * @default 'default'232 */233 execution?: "default" | "eager" | undefined;234 }235 interface MemoryMeasurement {236 total: {237 jsMemoryEstimate: number;238 jsMemoryRange: [number, number];239 };240 }241 /**242 * Instances of the `vm.Script` class contain precompiled scripts that can be243 * executed in specific contexts.244 * @since v0.3.1245 */246 class Script {247 constructor(code: string, options?: ScriptOptions | string);248 /**249 * Runs the compiled code contained by the `vm.Script` object within the given `contextifiedObject` and returns the result. Running code does not have access250 * to local scope.251 *252 * The following example compiles code that increments a global variable, sets253 * the value of another global variable, then execute the code multiple times.254 * The globals are contained in the `context` object.255 *256 * ```js257 * import vm from 'node:vm';258 *259 * const context = {260 * animal: 'cat',261 * count: 2,262 * };263 *264 * const script = new vm.Script('count += 1; name = "kitty";');265 *266 * vm.createContext(context);267 * for (let i = 0; i < 10; ++i) {268 * script.runInContext(context);269 * }270 *271 * console.log(context);272 * // Prints: { animal: 'cat', count: 12, name: 'kitty' }273 * ```274 *275 * Using the `timeout` or `breakOnSigint` options will result in new event loops276 * and corresponding threads being started, which have a non-zero performance277 * overhead.278 * @since v0.3.1279 * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method.280 * @return the result of the very last statement executed in the script.281 */282 runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any;283 /**284 * This method is a shortcut to `script.runInContext(vm.createContext(options), options)`.285 * It does several things at once:286 *287 * 1. Creates a new context.288 * 2. If `contextObject` is an object, contextifies it with the new context.289 * If `contextObject` is undefined, creates a new object and contextifies it.290 * If `contextObject` is `vm.constants.DONT_CONTEXTIFY`, don't contextify anything.291 * 3. Runs the compiled code contained by the `vm.Script` object within the created context. The code292 * does not have access to the scope in which this method is called.293 * 4. Returns the result.294 *295 * The following example compiles code that sets a global variable, then executes296 * the code multiple times in different contexts. The globals are set on and297 * contained within each individual `context`.298 *299 * ```js300 * const vm = require('node:vm');301 *302 * const script = new vm.Script('globalVar = "set"');303 *304 * const contexts = [{}, {}, {}];305 * contexts.forEach((context) => {306 * script.runInNewContext(context);307 * });308 *309 * console.log(contexts);310 * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]311 *312 * // This would throw if the context is created from a contextified object.313 * // vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary314 * // global objects that can be frozen.315 * const freezeScript = new vm.Script('Object.freeze(globalThis); globalThis;');316 * const frozenContext = freezeScript.runInNewContext(vm.constants.DONT_CONTEXTIFY);317 * ```318 * @since v0.3.1319 * @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.320 * If `undefined`, an empty contextified object will be created for backwards compatibility.321 * @return the result of the very last statement executed in the script.322 */323 runInNewContext(324 contextObject?: Context | typeof constants.DONT_CONTEXTIFY,325 options?: RunningScriptInNewContextOptions,326 ): any;327 /**328 * Runs the compiled code contained by the `vm.Script` within the context of the329 * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object.330 *331 * The following example compiles code that increments a `global` variable then332 * executes that code multiple times:333 *334 * ```js335 * import vm from 'node:vm';336 *337 * global.globalVar = 0;338 *339 * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });340 *341 * for (let i = 0; i < 1000; ++i) {342 * script.runInThisContext();343 * }344 *345 * console.log(globalVar);346 *347 * // 1000348 * ```349 * @since v0.3.1350 * @return the result of the very last statement executed in the script.351 */352 runInThisContext(options?: RunningScriptOptions): any;353 /**354 * Creates a code cache that can be used with the `Script` constructor's `cachedData` option. Returns a `Buffer`. This method may be called at any355 * time and any number of times.356 *357 * The code cache of the `Script` doesn't contain any JavaScript observable358 * states. The code cache is safe to be saved along side the script source and359 * used to construct new `Script` instances multiple times.360 *361 * Functions in the `Script` source can be marked as lazily compiled and they are362 * not compiled at construction of the `Script`. These functions are going to be363 * compiled when they are invoked the first time. The code cache serializes the364 * metadata that V8 currently knows about the `Script` that it can use to speed up365 * future compilations.366 *367 * ```js368 * const script = new vm.Script(`369 * function add(a, b) {370 * return a + b;371 * }372 *373 * const x = add(1, 2);374 * `);375 *376 * const cacheWithoutAdd = script.createCachedData();377 * // In `cacheWithoutAdd` the function `add()` is marked for full compilation378 * // upon invocation.379 *380 * script.runInThisContext();381 *382 * const cacheWithAdd = script.createCachedData();383 * // `cacheWithAdd` contains fully compiled function `add()`.384 * ```385 * @since v10.6.0386 */387 createCachedData(): Buffer;388 /** @deprecated in favor of `script.createCachedData()` */389 cachedDataProduced?: boolean | undefined;390 /**391 * When `cachedData` is supplied to create the `vm.Script`, this value will be set392 * to either `true` or `false` depending on acceptance of the data by V8.393 * Otherwise the value is `undefined`.394 * @since v5.7.0395 */396 cachedDataRejected?: boolean | undefined;397 cachedData?: Buffer | undefined;398 /**399 * When the script is compiled from a source that contains a source map magic400 * comment, this property will be set to the URL of the source map.401 *402 * ```js403 * import vm from 'node:vm';404 *405 * const script = new vm.Script(`406 * function myFunc() {}407 * //# sourceMappingURL=sourcemap.json408 * `);409 *410 * console.log(script.sourceMapURL);411 * // Prints: sourcemap.json412 * ```413 * @since v19.1.0, v18.13.0414 */415 sourceMapURL?: string | undefined;416 }417 /**418 * If the given `contextObject` is an object, the `vm.createContext()` method will419 * [prepare that object](https://nodejs.org/docs/latest-v24.x/api/vm.html#what-does-it-mean-to-contextify-an-object)420 * and return a reference to it so that it can be used in calls to {@link runInContext} or421 * [`script.runInContext()`](https://nodejs.org/docs/latest-v24.x/api/vm.html#scriptrunincontextcontextifiedobject-options).422 * Inside such scripts, the global object will be wrapped by the `contextObject`, retaining all of its423 * existing properties but also having the built-in objects and functions any standard424 * [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global425 * variables will remain unchanged.426 *427 * ```js428 * const vm = require('node:vm');429 *430 * global.globalVar = 3;431 *432 * const context = { globalVar: 1 };433 * vm.createContext(context);434 *435 * vm.runInContext('globalVar *= 2;', context);436 *437 * console.log(context);438 * // Prints: { globalVar: 2 }439 *440 * console.log(global.globalVar);441 * // Prints: 3442 * ```443 *444 * If `contextObject` is omitted (or passed explicitly as `undefined`), a new,445 * empty contextified object will be returned.446 *447 * When the global object in the newly created context is contextified, it has some quirks448 * compared to ordinary global objects. For example, it cannot be frozen. To create a context449 * without the contextifying quirks, pass `vm.constants.DONT_CONTEXTIFY` as the `contextObject`450 * argument. See the documentation of `vm.constants.DONT_CONTEXTIFY` for details.451 *452 * The `vm.createContext()` method is primarily useful for creating a single453 * context that can be used to run multiple scripts. For instance, if emulating a454 * web browser, the method can be used to create a single context representing a455 * window's global object, then run all `<script>` tags together within that456 * context.457 *458 * The provided `name` and `origin` of the context are made visible through the459 * Inspector API.460 * @since v0.3.1461 * @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.462 * If `undefined`, an empty contextified object will be created for backwards compatibility.463 * @return contextified object.464 */465 function createContext(466 contextObject?: Context | typeof constants.DONT_CONTEXTIFY,467 options?: CreateContextOptions,468 ): Context;469 /**470 * Returns `true` if the given `object` object has been contextified using {@link createContext},471 * or if it's the global object of a context created using `vm.constants.DONT_CONTEXTIFY`.472 * @since v0.11.7473 */474 function isContext(sandbox: Context): boolean;475 /**476 * The `vm.runInContext()` method compiles `code`, runs it within the context of477 * the `contextifiedObject`, then returns the result. Running code does not have478 * access to the local scope. The `contextifiedObject` object _must_ have been479 * previously `contextified` using the {@link createContext} method.480 *481 * If `options` is a string, then it specifies the filename.482 *483 * The following example compiles and executes different scripts using a single `contextified` object:484 *485 * ```js486 * import vm from 'node:vm';487 *488 * const contextObject = { globalVar: 1 };489 * vm.createContext(contextObject);490 *491 * for (let i = 0; i < 10; ++i) {492 * vm.runInContext('globalVar *= 2;', contextObject);493 * }494 * console.log(contextObject);495 * // Prints: { globalVar: 1024 }496 * ```497 * @since v0.3.1498 * @param code The JavaScript code to compile and run.499 * @param contextifiedObject The `contextified` object that will be used as the `global` when the `code` is compiled and run.500 * @return the result of the very last statement executed in the script.501 */502 function runInContext(code: string, contextifiedObject: Context, options?: RunningCodeOptions | string): any;503 /**504 * This method is a shortcut to505 * `(new vm.Script(code, options)).runInContext(vm.createContext(options), options)`.506 * If `options` is a string, then it specifies the filename.507 *508 * It does several things at once:509 *510 * 1. Creates a new context.511 * 2. If `contextObject` is an object, contextifies it with the new context.512 * If `contextObject` is undefined, creates a new object and contextifies it.513 * If `contextObject` is `vm.constants.DONT_CONTEXTIFY`, don't contextify anything.514 * 3. Compiles the code as a`vm.Script`515 * 4. Runs the compield code within the created context. The code does not have access to the scope in516 * which this method is called.517 * 5. Returns the result.518 *519 * The following example compiles and executes code that increments a global520 * variable and sets a new one. These globals are contained in the `contextObject`.521 *522 * ```js523 * const vm = require('node:vm');524 *525 * const contextObject = {526 * animal: 'cat',527 * count: 2,528 * };529 *530 * vm.runInNewContext('count += 1; name = "kitty"', contextObject);531 * console.log(contextObject);532 * // Prints: { animal: 'cat', count: 3, name: 'kitty' }533 *534 * // This would throw if the context is created from a contextified object.535 * // vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that536 * // can be frozen.537 * const frozenContext = vm.runInNewContext('Object.freeze(globalThis); globalThis;', vm.constants.DONT_CONTEXTIFY);538 * ```539 * @since v0.3.1540 * @param code The JavaScript code to compile and run.541 * @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified.542 * If `undefined`, an empty contextified object will be created for backwards compatibility.543 * @return the result of the very last statement executed in the script.544 */545 function runInNewContext(546 code: string,547 contextObject?: Context | typeof constants.DONT_CONTEXTIFY,548 options?: RunningCodeInNewContextOptions | string,549 ): any;550 /**551 * `vm.runInThisContext()` compiles `code`, runs it within the context of the552 * current `global` and returns the result. Running code does not have access to553 * local scope, but does have access to the current `global` object.554 *555 * If `options` is a string, then it specifies the filename.556 *557 * The following example illustrates using both `vm.runInThisContext()` and558 * the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code:559 *560 * ```js561 * import vm from 'node:vm';562 * let localVar = 'initial value';563 *564 * const vmResult = vm.runInThisContext('localVar = "vm";');565 * console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);566 * // Prints: vmResult: 'vm', localVar: 'initial value'567 *568 * const evalResult = eval('localVar = "eval";');569 * console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);570 * // Prints: evalResult: 'eval', localVar: 'eval'571 * ```572 *573 * Because `vm.runInThisContext()` does not have access to the local scope, `localVar` is unchanged. In contrast,574 * [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) _does_ have access to the575 * local scope, so the value `localVar` is changed. In this way `vm.runInThisContext()` is much like an [indirect `eval()` call](https://es5.github.io/#x10.4.2), e.g.`(0,eval)('code')`.576 *577 * ## Example: Running an HTTP server within a VM578 *579 * When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global580 * context. The code passed to this VM context will have its own isolated scope.581 *582 * In order to run a simple web server using the `node:http` module the code passed583 * to the context must either import `node:http` on its own, or have a584 * reference to the `node:http` module passed to it. For instance:585 *586 * ```js587 * 'use strict';588 * import vm from 'node:vm';589 *590 * const code = `591 * ((require) => {592 * const http = require('node:http');593 *594 * http.createServer((request, response) => {595 * response.writeHead(200, { 'Content-Type': 'text/plain' });596 * response.end('Hello World\\n');597 * }).listen(8124);598 *599 * console.log('Server running at http://127.0.0.1:8124/');600 * })`;601 *602 * vm.runInThisContext(code)(require);603 * ```604 *605 * The `require()` in the above case shares the state with the context it is606 * passed from. This may introduce risks when untrusted code is executed, e.g.607 * altering objects in the context in unwanted ways.608 * @since v0.3.1609 * @param code The JavaScript code to compile and run.610 * @return the result of the very last statement executed in the script.611 */612 function runInThisContext(code: string, options?: RunningCodeOptions | string): any;613 /**614 * Compiles the given code into the provided context (if no context is615 * supplied, the current context is used), and returns it wrapped inside a616 * function with the given `params`.617 * @since v10.10.0618 * @param code The body of the function to compile.619 * @param params An array of strings containing all parameters for the function.620 */621 function compileFunction(622 code: string,623 params?: readonly string[],624 options?: CompileFunctionOptions,625 ): Function & {626 cachedData?: Script["cachedData"] | undefined;627 cachedDataProduced?: Script["cachedDataProduced"] | undefined;628 cachedDataRejected?: Script["cachedDataRejected"] | undefined;629 };630 /**631 * Measure the memory known to V8 and used by all contexts known to the632 * current V8 isolate, or the main context.633 *634 * The format of the object that the returned Promise may resolve with is635 * specific to the V8 engine and may change from one version of V8 to the next.636 *637 * The returned result is different from the statistics returned by `v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measure the638 * memory reachable by each V8 specific contexts in the current instance of639 * the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure640 * the memory occupied by each heap space in the current V8 instance.641 *642 * ```js643 * import vm from 'node:vm';644 * // Measure the memory used by the main context.645 * vm.measureMemory({ mode: 'summary' })646 * // This is the same as vm.measureMemory()647 * .then((result) => {648 * // The current format is:649 * // {650 * // total: {651 * // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]652 * // }653 * // }654 * console.log(result);655 * });656 *657 * const context = vm.createContext({ a: 1 });658 * vm.measureMemory({ mode: 'detailed', execution: 'eager' })659 * .then((result) => {660 * // Reference the context here so that it won't be GC'ed661 * // until the measurement is complete.662 * console.log(context.a);663 * // {664 * // total: {665 * // jsMemoryEstimate: 2574732,666 * // jsMemoryRange: [ 2574732, 2904372 ]667 * // },668 * // current: {669 * // jsMemoryEstimate: 2438996,670 * // jsMemoryRange: [ 2438996, 2768636 ]671 * // },672 * // other: [673 * // {674 * // jsMemoryEstimate: 135736,675 * // jsMemoryRange: [ 135736, 465376 ]676 * // }677 * // ]678 * // }679 * console.log(result);680 * });681 * ```682 * @since v13.10.0683 * @experimental684 */685 function measureMemory(options?: MeasureMemoryOptions): Promise<MemoryMeasurement>;686 interface ModuleEvaluateOptions {687 timeout?: RunningScriptOptions["timeout"] | undefined;688 breakOnSigint?: RunningScriptOptions["breakOnSigint"] | undefined;689 }690 type ModuleLinker = (691 specifier: string,692 referencingModule: Module,693 extra: {694 attributes: ImportAttributes;695 },696 ) => Module | Promise<Module>;697 type ModuleStatus = "unlinked" | "linking" | "linked" | "evaluating" | "evaluated" | "errored";698 /**699 * This feature is only available with the `--experimental-vm-modules` command700 * flag enabled.701 *702 * The `vm.Module` class provides a low-level interface for using703 * ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script` class that closely mirrors [Module Record](https://262.ecma-international.org/14.0/#sec-abstract-module-records) s as704 * defined in the ECMAScript705 * specification.706 *707 * Unlike `vm.Script` however, every `vm.Module` object is bound to a context from708 * its creation. Operations on `vm.Module` objects are intrinsically asynchronous,709 * in contrast with the synchronous nature of `vm.Script` objects. The use of710 * 'async' functions can help with manipulating `vm.Module` objects.711 *712 * Using a `vm.Module` object requires three distinct steps: creation/parsing,713 * linking, and evaluation. These three steps are illustrated in the following714 * example.715 *716 * This implementation lies at a lower level than the `ECMAScript Module717 * loader`. There is also no way to interact with the Loader yet, though718 * support is planned.719 *720 * ```js721 * import vm from 'node:vm';722 *723 * const contextifiedObject = vm.createContext({724 * secret: 42,725 * print: console.log,726 * });727 *728 * // Step 1729 * //730 * // Create a Module by constructing a new `vm.SourceTextModule` object. This731 * // parses the provided source text, throwing a `SyntaxError` if anything goes732 * // wrong. By default, a Module is created in the top context. But here, we733 * // specify `contextifiedObject` as the context this Module belongs to.734 * //735 * // Here, we attempt to obtain the default export from the module "foo", and736 * // put it into local binding "secret".737 *738 * const bar = new vm.SourceTextModule(`739 * import s from 'foo';740 * s;741 * print(s);742 * `, { context: contextifiedObject });743 *744 * // Step 2745 * //746 * // "Link" the imported dependencies of this Module to it.747 * //748 * // The provided linking callback (the "linker") accepts two arguments: the749 * // parent module (`bar` in this case) and the string that is the specifier of750 * // the imported module. The callback is expected to return a Module that751 * // corresponds to the provided specifier, with certain requirements documented752 * // in `module.link()`.753 * //754 * // If linking has not started for the returned Module, the same linker755 * // callback will be called on the returned Module.756 * //757 * // Even top-level Modules without dependencies must be explicitly linked. The758 * // callback provided would never be called, however.759 * //760 * // The link() method returns a Promise that will be resolved when all the761 * // Promises returned by the linker resolve.762 * //763 * // Note: This is a contrived example in that the linker function creates a new764 * // "foo" module every time it is called. In a full-fledged module system, a765 * // cache would probably be used to avoid duplicated modules.766 *767 * async function linker(specifier, referencingModule) {768 * if (specifier === 'foo') {769 * return new vm.SourceTextModule(`770 * // The "secret" variable refers to the global variable we added to771 * // "contextifiedObject" when creating the context.772 * export default secret;773 * `, { context: referencingModule.context });774 *775 * // Using `contextifiedObject` instead of `referencingModule.context`776 * // here would work as well.777 * }778 * throw new Error(`Unable to resolve dependency: ${specifier}`);779 * }780 * await bar.link(linker);781 *782 * // Step 3783 * //784 * // Evaluate the Module. The evaluate() method returns a promise which will785 * // resolve after the module has finished evaluating.786 *787 * // Prints 42.788 * await bar.evaluate();789 * ```790 * @since v13.0.0, v12.16.0791 * @experimental792 */793 class Module {794 /**795 * The specifiers of all dependencies of this module. The returned array is frozen796 * to disallow any changes to it.797 *798 * Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in799 * the ECMAScript specification.800 */801 dependencySpecifiers: readonly string[];802 /**803 * If the `module.status` is `'errored'`, this property contains the exception804 * thrown by the module during evaluation. If the status is anything else,805 * accessing this property will result in a thrown exception.806 *807 * The value `undefined` cannot be used for cases where there is not a thrown808 * exception due to possible ambiguity with `throw undefined;`.809 *810 * Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s811 * in the ECMAScript specification.812 */813 error: any;814 /**815 * The identifier of the current module, as set in the constructor.816 */817 identifier: string;818 context: Context;819 /**820 * The namespace object of the module. This is only available after linking821 * (`module.link()`) has completed.822 *823 * Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript824 * specification.825 */826 namespace: Object;827 /**828 * The current status of the module. Will be one of:829 *830 * * `'unlinked'`: `module.link()` has not yet been called.831 * * `'linking'`: `module.link()` has been called, but not all Promises returned832 * by the linker function have been resolved yet.833 * * `'linked'`: The module has been linked successfully, and all of its834 * dependencies are linked, but `module.evaluate()` has not yet been called.835 * * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on836 * itself or a parent module.837 * * `'evaluated'`: The module has been successfully evaluated.838 * * `'errored'`: The module has been evaluated, but an exception was thrown.839 *840 * Other than `'errored'`, this status string corresponds to the specification's [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'`841 * corresponds to `'evaluated'` in the specification, but with `[[EvaluationError]]` set to a842 * value that is not `undefined`.843 */844 status: ModuleStatus;845 /**846 * Evaluate the module.847 *848 * This must be called after the module has been linked; otherwise it will reject.849 * It could be called also when the module has already been evaluated, in which850 * case it will either do nothing if the initial evaluation ended in success851 * (`module.status` is `'evaluated'`) or it will re-throw the exception that the852 * initial evaluation resulted in (`module.status` is `'errored'`).853 *854 * This method cannot be called while the module is being evaluated855 * (`module.status` is `'evaluating'`).856 *857 * Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in the858 * ECMAScript specification.859 * @return Fulfills with `undefined` upon success.860 */861 evaluate(options?: ModuleEvaluateOptions): Promise<void>;862 /**863 * Link module dependencies. This method must be called before evaluation, and864 * can only be called once per module.865 *866 * The function is expected to return a `Module` object or a `Promise` that867 * eventually resolves to a `Module` object. The returned `Module` must satisfy the868 * following two invariants:869 *870 * * It must belong to the same context as the parent `Module`.871 * * Its `status` must not be `'errored'`.872 *873 * If the returned `Module`'s `status` is `'unlinked'`, this method will be874 * recursively called on the returned `Module` with the same provided `linker` function.875 *876 * `link()` returns a `Promise` that will either get resolved when all linking877 * instances resolve to a valid `Module`, or rejected if the linker function either878 * throws an exception or returns an invalid `Module`.879 *880 * The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the881 * ECMAScript882 * specification, with a few key differences:883 *884 * * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous.885 *886 * The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module887 * linking is one that returns the modules linked during linking. Since at888 * that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per889 * specification.890 *891 * Corresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in892 * the ECMAScript specification.893 */894 link(linker: ModuleLinker): Promise<void>;895 }896 interface SourceTextModuleOptions {897 /**898 * String used in stack traces.899 * @default 'vm:module(i)' where i is a context-specific ascending index.900 */901 identifier?: string | undefined;902 /**903 * Provides an optional data with V8's code cache data for the supplied source.904 */905 cachedData?: ScriptOptions["cachedData"] | undefined;906 context?: Context | undefined;907 lineOffset?: BaseOptions["lineOffset"] | undefined;908 columnOffset?: BaseOptions["columnOffset"] | undefined;909 /**910 * Called during evaluation of this module to initialize the `import.meta`.911 */912 initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined;913 /**914 * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is915 * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see916 * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).917 * @experimental918 */919 importModuleDynamically?: DynamicModuleLoader<SourceTextModule> | undefined;920 }921 /**922 * This feature is only available with the `--experimental-vm-modules` command923 * flag enabled.924 *925 * The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as926 * defined in the ECMAScript specification.927 * @since v9.6.0928 * @experimental929 */930 class SourceTextModule extends Module {931 /**932 * Creates a new `SourceTextModule` instance.933 * @param code JavaScript Module code to parse934 */935 constructor(code: string, options?: SourceTextModuleOptions);936 }937 interface SyntheticModuleOptions {938 /**939 * String used in stack traces.940 * @default 'vm:module(i)' where i is a context-specific ascending index.941 */942 identifier?: string | undefined;943 /**944 * The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in.945 */946 context?: Context | undefined;947 }948 /**949 * This feature is only available with the `--experimental-vm-modules` command950 * flag enabled.951 *952 * The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as953 * defined in the WebIDL specification. The purpose of synthetic modules is to954 * provide a generic interface for exposing non-JavaScript sources to ECMAScript955 * module graphs.956 *957 * ```js958 * import vm from 'node:vm';959 *960 * const source = '{ "a": 1 }';961 * const module = new vm.SyntheticModule(['default'], function() {962 * const obj = JSON.parse(source);963 * this.setExport('default', obj);964 * });965 *966 * // Use `module` in linking...967 * ```968 * @since v13.0.0, v12.16.0969 * @experimental970 */971 class SyntheticModule extends Module {972 /**973 * Creates a new `SyntheticModule` instance.974 * @param exportNames Array of names that will be exported from the module.975 * @param evaluateCallback Called when the module is evaluated.976 */977 constructor(978 exportNames: string[],979 evaluateCallback: (this: SyntheticModule) => void,980 options?: SyntheticModuleOptions,981 );982 /**983 * This method is used after the module is linked to set the values of exports. If984 * it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error985 * will be thrown.986 *987 * ```js988 * import vm from 'node:vm';989 *990 * const m = new vm.SyntheticModule(['x'], () => {991 * m.setExport('x', 1);992 * });993 *994 * await m.link(() => {});995 * await m.evaluate();996 *997 * assert.strictEqual(m.namespace.x, 1);998 * ```999 * @since v13.0.0, v12.16.01000 * @param name Name of the export to set.1001 * @param value The value to set the export to.1002 */1003 setExport(name: string, value: any): void;1004 }1005 /**1006 * Returns an object containing commonly used constants for VM operations.1007 * @since v21.7.0, v20.12.01008 */1009 namespace constants {1010 /**1011 * A constant that can be used as the `importModuleDynamically` option to `vm.Script`1012 * and `vm.compileFunction()` so that Node.js uses the default ESM loader from the main1013 * context to load the requested module.1014 *1015 * For detailed information, see [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).1016 * @since v21.7.0, v20.12.01017 */1018 const USE_MAIN_CONTEXT_DEFAULT_LOADER: number;1019 /**1020 * This constant, when used as the `contextObject` argument in vm APIs, instructs Node.js to create1021 * a context without wrapping its global object with another object in a Node.js-specific manner.1022 * As a result, the `globalThis` value inside the new context would behave more closely to an ordinary1023 * one.1024 *1025 * When `vm.constants.DONT_CONTEXTIFY` is used as the `contextObject` argument to {@link createContext},1026 * the returned object is a proxy-like object to the global object in the newly created context with1027 * fewer Node.js-specific quirks. It is reference equal to the `globalThis` value in the new context,1028 * can be modified from outside the context, and can be used to access built-ins in the new context directly.1029 * @since v22.8.01030 */1031 const DONT_CONTEXTIFY: number;1032 }1033}1034declare module "node:vm" {1035 export * from "vm";1036}1037 