| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {MeasureMemoryOptions} from 'node:vm'; |
| b69ab31 | | | 9 | import type {Json} from './typeUtils'; |
| b69ab31 | | | 10 | |
| b69ab31 | | | 11 | import {measureMemory} from 'node:vm'; |
| b69ab31 | | | 12 | import {Logger} from '../isl-server/src/logger'; |
| b69ab31 | | | 13 | |
| b69ab31 | | | 14 | export class MockLogger extends Logger { |
| b69ab31 | | | 15 | write() { |
| b69ab31 | | | 16 | // noop |
| b69ab31 | | | 17 | } |
| b69ab31 | | | 18 | } |
| b69ab31 | | | 19 | export const mockLogger = new MockLogger(); |
| b69ab31 | | | 20 | |
| b69ab31 | | | 21 | export function clone<T extends Json>(o: T): T { |
| b69ab31 | | | 22 | return JSON.parse(JSON.stringify(o)); |
| b69ab31 | | | 23 | } |
| b69ab31 | | | 24 | |
| b69ab31 | | | 25 | /** |
| b69ab31 | | | 26 | * Returns a Promise which resolves after the current async tick is finished. |
| b69ab31 | | | 27 | * Useful for testing code which `await`s. |
| b69ab31 | | | 28 | */ |
| b69ab31 | | | 29 | export function nextTick(): Promise<void> { |
| b69ab31 | | | 30 | return new Promise(res => setTimeout(res, 0)); |
| b69ab31 | | | 31 | } |
| b69ab31 | | | 32 | |
| b69ab31 | | | 33 | export async function gc() { |
| b69ab31 | | | 34 | // 'node --expose-gc' defines 'global.gc'. |
| b69ab31 | | | 35 | // To run with yarn: yarn node --expose-gc ./node_modules/.bin/jest ... |
| b69ab31 | | | 36 | const globalGc = global.gc; |
| b69ab31 | | | 37 | if (globalGc != null) { |
| b69ab31 | | | 38 | await new Promise<void>(r => |
| b69ab31 | | | 39 | setTimeout(() => { |
| b69ab31 | | | 40 | globalGc(); |
| b69ab31 | | | 41 | r(); |
| b69ab31 | | | 42 | }, 0), |
| b69ab31 | | | 43 | ); |
| b69ab31 | | | 44 | } else { |
| b69ab31 | | | 45 | // measureMemory with 'eager' has a side effect of running the GC. |
| b69ab31 | | | 46 | // This exists since node 14. |
| b69ab31 | | | 47 | // 'as' used since `MeasureMemoryOptions` is outdated (node 13?). |
| b69ab31 | | | 48 | await measureMemory({execution: 'eager'} as MeasureMemoryOptions); |
| b69ab31 | | | 49 | } |
| b69ab31 | | | 50 | } |