4bb797b2abb1f5e4e08d2704dc934f65bbaf0b67c495583d051b4b4df57d2df1ef8dbb2834f85046d477571e886326922a5805c41f9e633ffa8a64a650e651 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. /**
  2. * The `node:vm` module enables compiling and running code within V8 Virtual
  3. * 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 or
  9. * compiled, saved, and run later.
  10. *
  11. * A common use case is to run the code in a different V8 Context. This means
  12. * invoked code has a different global object than the invoking code.
  13. *
  14. * One can provide the context by `contextifying` an
  15. * object. The invoked code treats any property in the context like a
  16. * global variable. Any changes to global variables caused by the invoked
  17. * code are reflected in the context object.
  18. *
  19. * ```js
  20. * 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); // 42
  33. * console.log(context.y); // 17
  34. *
  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. */
  39. declare module "vm" {
  40. import { ImportAttributes, ImportPhase } 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 0
  51. */
  52. lineOffset?: number | undefined;
  53. /**
  54. * Specifies the column number offset that is displayed in stack traces produced by this script.
  55. * @default 0
  56. */
  57. columnOffset?: number | undefined;
  58. }
  59. type DynamicModuleLoader<T> = (
  60. specifier: string,
  61. referrer: T,
  62. importAttributes: ImportAttributes,
  63. phase: ImportPhase,
  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 is
  74. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  75. * [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. * @experimental
  77. */
  78. importModuleDynamically?:
  79. | DynamicModuleLoader<Script>
  80. | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
  81. | 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 true
  87. */
  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 false
  99. */
  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 is
  126. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  127. * [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. * @experimental
  129. */
  130. importModuleDynamically?:
  131. | DynamicModuleLoader<Script>
  132. | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
  133. | 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 is
  142. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  143. * [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. * @experimental
  145. */
  146. importModuleDynamically?:
  147. | DynamicModuleLoader<Script>
  148. | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
  149. | 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 false
  159. */
  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 compiling
  167. */
  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 is
  171. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  172. * [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. * @experimental
  174. */
  175. importModuleDynamically?:
  176. | DynamicModuleLoader<ReturnType<typeof compileFunction>>
  177. | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
  178. | 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 true
  200. */
  201. strings?: boolean | undefined;
  202. /**
  203. * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError.
  204. * @default true
  205. */
  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 is
  215. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  216. * [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. * @experimental
  218. */
  219. importModuleDynamically?:
  220. | DynamicModuleLoader<Context>
  221. | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
  222. | 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 be
  243. * executed in specific contexts.
  244. * @since v0.3.1
  245. */
  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 access
  250. * to local scope.
  251. *
  252. * The following example compiles code that increments a global variable, sets
  253. * the value of another global variable, then execute the code multiple times.
  254. * The globals are contained in the `context` object.
  255. *
  256. * ```js
  257. * 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 loops
  276. * and corresponding threads being started, which have a non-zero performance
  277. * overhead.
  278. * @since v0.3.1
  279. * @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 code
  292. * 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 executes
  296. * the code multiple times in different contexts. The globals are set on and
  297. * contained within each individual `context`.
  298. *
  299. * ```js
  300. * 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 ordinary
  314. * // 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.1
  319. * @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 the
  329. * 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 then
  332. * executes that code multiple times:
  333. *
  334. * ```js
  335. * 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. * // 1000
  348. * ```
  349. * @since v0.3.1
  350. * @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 any
  355. * time and any number of times.
  356. *
  357. * The code cache of the `Script` doesn't contain any JavaScript observable
  358. * states. The code cache is safe to be saved along side the script source and
  359. * used to construct new `Script` instances multiple times.
  360. *
  361. * Functions in the `Script` source can be marked as lazily compiled and they are
  362. * not compiled at construction of the `Script`. These functions are going to be
  363. * compiled when they are invoked the first time. The code cache serializes the
  364. * metadata that V8 currently knows about the `Script` that it can use to speed up
  365. * future compilations.
  366. *
  367. * ```js
  368. * 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 compilation
  378. * // upon invocation.
  379. *
  380. * script.runInThisContext();
  381. *
  382. * const cacheWithAdd = script.createCachedData();
  383. * // `cacheWithAdd` contains fully compiled function `add()`.
  384. * ```
  385. * @since v10.6.0
  386. */
  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 set
  392. * to either `true` or `false` depending on acceptance of the data by V8.
  393. * Otherwise the value is `undefined`.
  394. * @since v5.7.0
  395. */
  396. cachedDataRejected?: boolean | undefined;
  397. cachedData?: Buffer | undefined;
  398. /**
  399. * When the script is compiled from a source that contains a source map magic
  400. * comment, this property will be set to the URL of the source map.
  401. *
  402. * ```js
  403. * import vm from 'node:vm';
  404. *
  405. * const script = new vm.Script(`
  406. * function myFunc() {}
  407. * //# sourceMappingURL=sourcemap.json
  408. * `);
  409. *
  410. * console.log(script.sourceMapURL);
  411. * // Prints: sourcemap.json
  412. * ```
  413. * @since v19.1.0, v18.13.0
  414. */
  415. sourceMapURL?: string | undefined;
  416. }
  417. /**
  418. * If the given `contextObject` is an object, the `vm.createContext()` method will
  419. * [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} or
  421. * [`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 its
  423. * existing properties but also having the built-in objects and functions any standard
  424. * [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global
  425. * variables will remain unchanged.
  426. *
  427. * ```js
  428. * 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: 3
  442. * ```
  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 quirks
  448. * compared to ordinary global objects. For example, it cannot be frozen. To create a context
  449. * 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 single
  453. * context that can be used to run multiple scripts. For instance, if emulating a
  454. * web browser, the method can be used to create a single context representing a
  455. * window's global object, then run all `<script>` tags together within that
  456. * context.
  457. *
  458. * The provided `name` and `origin` of the context are made visible through the
  459. * Inspector API.
  460. * @since v0.3.1
  461. * @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.7
  473. */
  474. function isContext(sandbox: Context): boolean;
  475. /**
  476. * The `vm.runInContext()` method compiles `code`, runs it within the context of
  477. * the `contextifiedObject`, then returns the result. Running code does not have
  478. * access to the local scope. The `contextifiedObject` object _must_ have been
  479. * 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. * ```js
  486. * 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.1
  498. * @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 to
  505. * `(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 in
  516. * which this method is called.
  517. * 5. Returns the result.
  518. *
  519. * The following example compiles and executes code that increments a global
  520. * variable and sets a new one. These globals are contained in the `contextObject`.
  521. *
  522. * ```js
  523. * 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 that
  536. * // can be frozen.
  537. * const frozenContext = vm.runInNewContext('Object.freeze(globalThis); globalThis;', vm.constants.DONT_CONTEXTIFY);
  538. * ```
  539. * @since v0.3.1
  540. * @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 the
  552. * current `global` and returns the result. Running code does not have access to
  553. * 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()` and
  558. * the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code:
  559. *
  560. * ```js
  561. * 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 the
  575. * 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 VM
  578. *
  579. * When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global
  580. * 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 passed
  583. * to the context must either import `node:http` on its own, or have a
  584. * reference to the `node:http` module passed to it. For instance:
  585. *
  586. * ```js
  587. * '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 is
  606. * 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.1
  609. * @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 is
  615. * supplied, the current context is used), and returns it wrapped inside a
  616. * function with the given `params`.
  617. * @since v10.10.0
  618. * @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 the
  632. * current V8 isolate, or the main context.
  633. *
  634. * The format of the object that the returned Promise may resolve with is
  635. * 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 the
  638. * memory reachable by each V8 specific contexts in the current instance of
  639. * the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure
  640. * the memory occupied by each heap space in the current V8 instance.
  641. *
  642. * ```js
  643. * 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'ed
  661. * // 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.0
  683. * @experimental
  684. */
  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` command
  700. * flag enabled.
  701. *
  702. * The `vm.Module` class provides a low-level interface for using
  703. * 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 as
  704. * defined in the ECMAScript
  705. * specification.
  706. *
  707. * Unlike `vm.Script` however, every `vm.Module` object is bound to a context from
  708. * its creation. Operations on `vm.Module` objects are intrinsically asynchronous,
  709. * in contrast with the synchronous nature of `vm.Script` objects. The use of
  710. * '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 following
  714. * example.
  715. *
  716. * This implementation lies at a lower level than the `ECMAScript Module
  717. * loader`. There is also no way to interact with the Loader yet, though
  718. * support is planned.
  719. *
  720. * ```js
  721. * import vm from 'node:vm';
  722. *
  723. * const contextifiedObject = vm.createContext({
  724. * secret: 42,
  725. * print: console.log,
  726. * });
  727. *
  728. * // Step 1
  729. * //
  730. * // Create a Module by constructing a new `vm.SourceTextModule` object. This
  731. * // parses the provided source text, throwing a `SyntaxError` if anything goes
  732. * // wrong. By default, a Module is created in the top context. But here, we
  733. * // specify `contextifiedObject` as the context this Module belongs to.
  734. * //
  735. * // Here, we attempt to obtain the default export from the module "foo", and
  736. * // 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 2
  745. * //
  746. * // "Link" the imported dependencies of this Module to it.
  747. * //
  748. * // The provided linking callback (the "linker") accepts two arguments: the
  749. * // parent module (`bar` in this case) and the string that is the specifier of
  750. * // the imported module. The callback is expected to return a Module that
  751. * // corresponds to the provided specifier, with certain requirements documented
  752. * // in `module.link()`.
  753. * //
  754. * // If linking has not started for the returned Module, the same linker
  755. * // callback will be called on the returned Module.
  756. * //
  757. * // Even top-level Modules without dependencies must be explicitly linked. The
  758. * // callback provided would never be called, however.
  759. * //
  760. * // The link() method returns a Promise that will be resolved when all the
  761. * // Promises returned by the linker resolve.
  762. * //
  763. * // Note: This is a contrived example in that the linker function creates a new
  764. * // "foo" module every time it is called. In a full-fledged module system, a
  765. * // 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 to
  771. * // "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 3
  783. * //
  784. * // Evaluate the Module. The evaluate() method returns a promise which will
  785. * // resolve after the module has finished evaluating.
  786. *
  787. * // Prints 42.
  788. * await bar.evaluate();
  789. * ```
  790. * @since v13.0.0, v12.16.0
  791. * @experimental
  792. */
  793. class Module {
  794. /**
  795. * If the `module.status` is `'errored'`, this property contains the exception
  796. * thrown by the module during evaluation. If the status is anything else,
  797. * accessing this property will result in a thrown exception.
  798. *
  799. * The value `undefined` cannot be used for cases where there is not a thrown
  800. * exception due to possible ambiguity with `throw undefined;`.
  801. *
  802. * Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s
  803. * in the ECMAScript specification.
  804. */
  805. error: any;
  806. /**
  807. * The identifier of the current module, as set in the constructor.
  808. */
  809. identifier: string;
  810. context: Context;
  811. /**
  812. * The namespace object of the module. This is only available after linking
  813. * (`module.link()`) has completed.
  814. *
  815. * Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript
  816. * specification.
  817. */
  818. namespace: Object;
  819. /**
  820. * The current status of the module. Will be one of:
  821. *
  822. * * `'unlinked'`: `module.link()` has not yet been called.
  823. * * `'linking'`: `module.link()` has been called, but not all Promises returned
  824. * by the linker function have been resolved yet.
  825. * * `'linked'`: The module has been linked successfully, and all of its
  826. * dependencies are linked, but `module.evaluate()` has not yet been called.
  827. * * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on
  828. * itself or a parent module.
  829. * * `'evaluated'`: The module has been successfully evaluated.
  830. * * `'errored'`: The module has been evaluated, but an exception was thrown.
  831. *
  832. * 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'`
  833. * corresponds to `'evaluated'` in the specification, but with `[[EvaluationError]]` set to a
  834. * value that is not `undefined`.
  835. */
  836. status: ModuleStatus;
  837. /**
  838. * Evaluate the module.
  839. *
  840. * This must be called after the module has been linked; otherwise it will reject.
  841. * It could be called also when the module has already been evaluated, in which
  842. * case it will either do nothing if the initial evaluation ended in success
  843. * (`module.status` is `'evaluated'`) or it will re-throw the exception that the
  844. * initial evaluation resulted in (`module.status` is `'errored'`).
  845. *
  846. * This method cannot be called while the module is being evaluated
  847. * (`module.status` is `'evaluating'`).
  848. *
  849. * 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 the
  850. * ECMAScript specification.
  851. * @return Fulfills with `undefined` upon success.
  852. */
  853. evaluate(options?: ModuleEvaluateOptions): Promise<void>;
  854. /**
  855. * Link module dependencies. This method must be called before evaluation, and
  856. * can only be called once per module.
  857. *
  858. * The function is expected to return a `Module` object or a `Promise` that
  859. * eventually resolves to a `Module` object. The returned `Module` must satisfy the
  860. * following two invariants:
  861. *
  862. * * It must belong to the same context as the parent `Module`.
  863. * * Its `status` must not be `'errored'`.
  864. *
  865. * If the returned `Module`'s `status` is `'unlinked'`, this method will be
  866. * recursively called on the returned `Module` with the same provided `linker` function.
  867. *
  868. * `link()` returns a `Promise` that will either get resolved when all linking
  869. * instances resolve to a valid `Module`, or rejected if the linker function either
  870. * throws an exception or returns an invalid `Module`.
  871. *
  872. * The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the
  873. * ECMAScript
  874. * specification, with a few key differences:
  875. *
  876. * * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous.
  877. *
  878. * The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module
  879. * linking is one that returns the modules linked during linking. Since at
  880. * that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per
  881. * specification.
  882. *
  883. * 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 in
  884. * the ECMAScript specification.
  885. */
  886. link(linker: ModuleLinker): Promise<void>;
  887. }
  888. interface SourceTextModuleOptions {
  889. /**
  890. * String used in stack traces.
  891. * @default 'vm:module(i)' where i is a context-specific ascending index.
  892. */
  893. identifier?: string | undefined;
  894. /**
  895. * Provides an optional data with V8's code cache data for the supplied source.
  896. */
  897. cachedData?: ScriptOptions["cachedData"] | undefined;
  898. context?: Context | undefined;
  899. lineOffset?: BaseOptions["lineOffset"] | undefined;
  900. columnOffset?: BaseOptions["columnOffset"] | undefined;
  901. /**
  902. * Called during evaluation of this module to initialize the `import.meta`.
  903. */
  904. initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined;
  905. /**
  906. * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
  907. * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
  908. * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
  909. * @experimental
  910. */
  911. importModuleDynamically?: DynamicModuleLoader<SourceTextModule> | undefined;
  912. }
  913. /**
  914. * A `ModuleRequest` represents the request to import a module with given import attributes and phase.
  915. * @since 24.4.0
  916. */
  917. interface ModuleRequest {
  918. /**
  919. * The specifier of the requested module.
  920. */
  921. specifier: string;
  922. /**
  923. * The `"with"` value passed to the `WithClause` in a `ImportDeclaration`, or an empty object if no value was
  924. * provided.
  925. */
  926. attributes: ImportAttributes;
  927. /**
  928. * The phase of the requested module (`"source"` or `"evaluation"`).
  929. */
  930. phase: ImportPhase;
  931. }
  932. /**
  933. * This feature is only available with the `--experimental-vm-modules` command
  934. * flag enabled.
  935. *
  936. * The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as
  937. * defined in the ECMAScript specification.
  938. * @since v9.6.0
  939. * @experimental
  940. */
  941. class SourceTextModule extends Module {
  942. /**
  943. * Creates a new `SourceTextModule` instance.
  944. * @param code JavaScript Module code to parse
  945. */
  946. constructor(code: string, options?: SourceTextModuleOptions);
  947. /**
  948. * @deprecated Use `sourceTextModule.moduleRequests` instead.
  949. */
  950. readonly dependencySpecifiers: readonly string[];
  951. /**
  952. * The requested import dependencies of this module. The returned array is frozen
  953. * to disallow any changes to it.
  954. *
  955. * For example, given a source text:
  956. *
  957. * ```js
  958. * import foo from 'foo';
  959. * import fooAlias from 'foo';
  960. * import bar from './bar.js';
  961. * import withAttrs from '../with-attrs.ts' with { arbitraryAttr: 'attr-val' };
  962. * import source Module from 'wasm-mod.wasm';
  963. * ```
  964. *
  965. * The value of the `sourceTextModule.moduleRequests` will be:
  966. *
  967. * ```js
  968. * [
  969. * {
  970. * specifier: 'foo',
  971. * attributes: {},
  972. * phase: 'evaluation',
  973. * },
  974. * {
  975. * specifier: 'foo',
  976. * attributes: {},
  977. * phase: 'evaluation',
  978. * },
  979. * {
  980. * specifier: './bar.js',
  981. * attributes: {},
  982. * phase: 'evaluation',
  983. * },
  984. * {
  985. * specifier: '../with-attrs.ts',
  986. * attributes: { arbitraryAttr: 'attr-val' },
  987. * phase: 'evaluation',
  988. * },
  989. * {
  990. * specifier: 'wasm-mod.wasm',
  991. * attributes: {},
  992. * phase: 'source',
  993. * },
  994. * ];
  995. * ```
  996. * @since v24.4.0
  997. */
  998. readonly moduleRequests: readonly ModuleRequest[];
  999. }
  1000. interface SyntheticModuleOptions {
  1001. /**
  1002. * String used in stack traces.
  1003. * @default 'vm:module(i)' where i is a context-specific ascending index.
  1004. */
  1005. identifier?: string | undefined;
  1006. /**
  1007. * The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in.
  1008. */
  1009. context?: Context | undefined;
  1010. }
  1011. /**
  1012. * This feature is only available with the `--experimental-vm-modules` command
  1013. * flag enabled.
  1014. *
  1015. * The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as
  1016. * defined in the WebIDL specification. The purpose of synthetic modules is to
  1017. * provide a generic interface for exposing non-JavaScript sources to ECMAScript
  1018. * module graphs.
  1019. *
  1020. * ```js
  1021. * import vm from 'node:vm';
  1022. *
  1023. * const source = '{ "a": 1 }';
  1024. * const module = new vm.SyntheticModule(['default'], function() {
  1025. * const obj = JSON.parse(source);
  1026. * this.setExport('default', obj);
  1027. * });
  1028. *
  1029. * // Use `module` in linking...
  1030. * ```
  1031. * @since v13.0.0, v12.16.0
  1032. * @experimental
  1033. */
  1034. class SyntheticModule extends Module {
  1035. /**
  1036. * Creates a new `SyntheticModule` instance.
  1037. * @param exportNames Array of names that will be exported from the module.
  1038. * @param evaluateCallback Called when the module is evaluated.
  1039. */
  1040. constructor(
  1041. exportNames: string[],
  1042. evaluateCallback: (this: SyntheticModule) => void,
  1043. options?: SyntheticModuleOptions,
  1044. );
  1045. /**
  1046. * This method is used after the module is linked to set the values of exports. If
  1047. * it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error
  1048. * will be thrown.
  1049. *
  1050. * ```js
  1051. * import vm from 'node:vm';
  1052. *
  1053. * const m = new vm.SyntheticModule(['x'], () => {
  1054. * m.setExport('x', 1);
  1055. * });
  1056. *
  1057. * await m.link(() => {});
  1058. * await m.evaluate();
  1059. *
  1060. * assert.strictEqual(m.namespace.x, 1);
  1061. * ```
  1062. * @since v13.0.0, v12.16.0
  1063. * @param name Name of the export to set.
  1064. * @param value The value to set the export to.
  1065. */
  1066. setExport(name: string, value: any): void;
  1067. }
  1068. /**
  1069. * Returns an object containing commonly used constants for VM operations.
  1070. * @since v21.7.0, v20.12.0
  1071. */
  1072. namespace constants {
  1073. /**
  1074. * A constant that can be used as the `importModuleDynamically` option to `vm.Script`
  1075. * and `vm.compileFunction()` so that Node.js uses the default ESM loader from the main
  1076. * context to load the requested module.
  1077. *
  1078. * 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).
  1079. * @since v21.7.0, v20.12.0
  1080. */
  1081. const USE_MAIN_CONTEXT_DEFAULT_LOADER: number;
  1082. /**
  1083. * This constant, when used as the `contextObject` argument in vm APIs, instructs Node.js to create
  1084. * a context without wrapping its global object with another object in a Node.js-specific manner.
  1085. * As a result, the `globalThis` value inside the new context would behave more closely to an ordinary
  1086. * one.
  1087. *
  1088. * When `vm.constants.DONT_CONTEXTIFY` is used as the `contextObject` argument to {@link createContext},
  1089. * the returned object is a proxy-like object to the global object in the newly created context with
  1090. * fewer Node.js-specific quirks. It is reference equal to the `globalThis` value in the new context,
  1091. * can be modified from outside the context, and can be used to access built-ins in the new context directly.
  1092. * @since v22.8.0
  1093. */
  1094. const DONT_CONTEXTIFY: number;
  1095. }
  1096. }
  1097. declare module "node:vm" {
  1098. export * from "vm";
  1099. }