@@ -24,6 +24,7 @@ import { Reference, ReferenceWithData, ReferenceWithFinalizer, type ReferenceOwn
2424import { type IDeferrdValue , Deferred } from './Deferred'
2525import { Store } from './Store'
2626import { TrackedFinalizer } from './TrackedFinalizer'
27+ import { ExternalMemory } from './ExternalMemory'
2728
2829export type CleanupHookCallbackFunction = number | ( ( arg : number ) => void )
2930
@@ -110,6 +111,10 @@ class NodejsWaitingRequestCounter {
110111 }
111112}
112113
114+ export interface ContextOptions {
115+ onExternalMemoryChange ?: ( current : bigint , old : bigint , delta : bigint ) => any
116+ }
117+
113118export class Context {
114119 private _isStopping = false
115120 private _canCallIntoJs = true
@@ -122,6 +127,7 @@ export class Context {
122127 public handleStore = new HandleStore ( )
123128 private readonly refCounter ?: NodejsWaitingRequestCounter
124129 private readonly cleanupQueue : CleanupQueue
130+ private readonly _externalMemory : ExternalMemory
125131
126132 public feature = {
127133 supportReflect,
@@ -135,8 +141,9 @@ export class Context {
135141 MessageChannel : _MessageChannel
136142 }
137143
138- public constructor ( ) {
144+ public constructor ( options ?: ContextOptions ) {
139145 this . cleanupQueue = new CleanupQueue ( )
146+ this . _externalMemory = new ExternalMemory ( options ?. onExternalMemoryChange )
140147 if ( typeof process === 'object' && process !== null && typeof process . once === 'function' ) {
141148 this . refCounter = new NodejsWaitingRequestCounter ( )
142149 process . once ( 'beforeExit' , ( ) => {
@@ -231,7 +238,11 @@ export class Context {
231238 return Deferred . create ( this , value )
232239 }
233240
234- createEnv (
241+ public adjustAmountOfExternalAllocatedMemory ( changeInBytes : number | bigint ) : bigint {
242+ return this . _externalMemory . adjust ( changeInBytes )
243+ }
244+
245+ public createEnv (
235246 filename : string ,
236247 moduleApiVersion : number ,
237248 makeDynCall_vppp : ( cb : Ptr ) => ( a : Ptr , b : Ptr , c : Ptr ) => void ,
@@ -331,8 +342,8 @@ export class Context {
331342
332343let defaultContext : Context
333344
334- export function createContext ( ) : Context {
335- return new Context ( )
345+ export function createContext ( options ?: ContextOptions ) : Context {
346+ return new Context ( options )
336347}
337348
338349export function getDefaultContext ( ) : Context {
0 commit comments