11cb0ef41Sopenharmony_ci// Flags: --experimental-vm-modules
21cb0ef41Sopenharmony_ci'use strict';
31cb0ef41Sopenharmony_ci
41cb0ef41Sopenharmony_ci// https://github.com/nodejs/node/issues/3020
51cb0ef41Sopenharmony_ci// Promises used to allow code to escape the timeout
61cb0ef41Sopenharmony_ci// set for runInContext, runInNewContext, and runInThisContext.
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciconst common = require('../common');
91cb0ef41Sopenharmony_ciconst assert = require('assert');
101cb0ef41Sopenharmony_ciconst vm = require('vm');
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ciconst NS_PER_MS = 1000000n;
131cb0ef41Sopenharmony_ci
141cb0ef41Sopenharmony_ciconst hrtime = process.hrtime.bigint;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_cifunction loop() {
171cb0ef41Sopenharmony_ci  const start = hrtime();
181cb0ef41Sopenharmony_ci  while (1) {
191cb0ef41Sopenharmony_ci    const current = hrtime();
201cb0ef41Sopenharmony_ci    const span = (current - start) / NS_PER_MS;
211cb0ef41Sopenharmony_ci    if (span >= 100n) {
221cb0ef41Sopenharmony_ci      throw new Error(
231cb0ef41Sopenharmony_ci        `escaped timeout at ${span} milliseconds!`);
241cb0ef41Sopenharmony_ci    }
251cb0ef41Sopenharmony_ci  }
261cb0ef41Sopenharmony_ci}
271cb0ef41Sopenharmony_ci
281cb0ef41Sopenharmony_ciassert.rejects(async () => {
291cb0ef41Sopenharmony_ci  const module = new vm.SourceTextModule(
301cb0ef41Sopenharmony_ci    'Promise.resolve().then(() => loop());',
311cb0ef41Sopenharmony_ci    {
321cb0ef41Sopenharmony_ci      context: vm.createContext({
331cb0ef41Sopenharmony_ci        hrtime,
341cb0ef41Sopenharmony_ci        loop
351cb0ef41Sopenharmony_ci      }, { microtaskMode: 'afterEvaluate' })
361cb0ef41Sopenharmony_ci    });
371cb0ef41Sopenharmony_ci  await module.link(common.mustNotCall());
381cb0ef41Sopenharmony_ci  await module.evaluate({ timeout: 10 });
391cb0ef41Sopenharmony_ci}, {
401cb0ef41Sopenharmony_ci  code: 'ERR_SCRIPT_EXECUTION_TIMEOUT',
411cb0ef41Sopenharmony_ci  message: 'Script execution timed out after 10ms'
421cb0ef41Sopenharmony_ci});
43