{"version":3,"file":"cleanup-queue.cjs","names":["codedMessage","CleanupQueue","instance","microtaskScheduled","updateTimeout"],"sources":["../../../src/collection/cleanup-queue.ts"],"sourcesContent":["import { codedMessage, devBuild } from '../error-message'\n\n// Share one elapsed clock for appointments and startup handoff deadlines.\n// Some runtimes lack `performance` although the DOM types declare it.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nexport const cleanupNow = () => globalThis.performance?.now() ?? Date.now()\n\ntype CleanupTask = {\n  executeAt: number\n  callback: () => void\n}\n\n/**\n * Batches many GC registrations behind a single shared timeout.\n */\nexport class CleanupQueue {\n  private static instance: CleanupQueue | null = null\n\n  private tasks: Map<unknown, CleanupTask> = new Map()\n\n  private timeoutId: ReturnType<typeof setTimeout> | null = null\n  private microtaskScheduled = false\n\n  private constructor() {}\n\n  public static getInstance(): CleanupQueue {\n    return (CleanupQueue.instance ??= new CleanupQueue())\n  }\n\n  /**\n   * Queues a cleanup task and defers timeout selection to a microtask so\n   * multiple synchronous registrations can share one root timer.\n   */\n  public schedule(key: unknown, gcTime: number, callback: () => void): void {\n    const executeAt = cleanupNow() + gcTime\n    this.tasks.set(key, { executeAt, callback })\n\n    if (!this.microtaskScheduled) {\n      this.microtaskScheduled = true\n      Promise.resolve().then(() => {\n        this.microtaskScheduled = false\n        this.updateTimeout()\n      })\n    }\n  }\n\n  public cancel(key: unknown): void {\n    this.tasks.delete(key)\n\n    // Retire the root timer with the last task. A non-empty queue keeps its\n    // timer even when the cancelled task was the earliest: it wakes early,\n    // finds nothing due and reschedules, which costs less than rescanning\n    // every task on each cancellation.\n    if (this.tasks.size === 0 && this.timeoutId !== null) {\n      clearTimeout(this.timeoutId)\n      this.timeoutId = null\n    }\n  }\n\n  /**\n   * Keeps only one active timeout: whichever task is due next.\n   */\n  private updateTimeout(): void {\n    if (this.timeoutId !== null) {\n      clearTimeout(this.timeoutId)\n      this.timeoutId = null\n    }\n\n    if (this.tasks.size === 0) {\n      return\n    }\n\n    let earliestTime = Infinity\n    for (const task of this.tasks.values()) {\n      if (task.executeAt < earliestTime) {\n        earliestTime = task.executeAt\n      }\n    }\n\n    const delay = Math.max(0, earliestTime - cleanupNow())\n    // Run every due task, then select the next shared wakeup.\n    this.timeoutId = setTimeout(() => {\n      this.timeoutId = null\n      const now = cleanupNow()\n      for (const [key, task] of this.tasks.entries()) {\n        if (now >= task.executeAt) {\n          this.tasks.delete(key)\n          try {\n            task.callback()\n          } catch (error) {\n            console.error(\n              devBuild() && process.env.NODE_ENV !== `production`\n                ? 'Error in CleanupQueue task:'\n                : codedMessage(214),\n              error,\n            )\n          }\n        }\n      }\n\n      this.updateTimeout()\n    }, delay)\n    // Background collection GC must not keep an otherwise finished Node\n    // process alive. Browsers return a numeric timer handle.\n    if (typeof this.timeoutId === `object`) this.timeoutId.unref()\n  }\n}\n"],"mappings":";AAKA,IAAa,mBAAmB,WAAW,aAAa,IAAI,KAAK,KAAK,IAAI;AAU1E,IAAa,eAAb,MAAaC,cAAa;;EACuB,KAAAC,KAAA;;CAO/C,cAAsB;EALqB,KAAA,wBAAA,IAAI,IAAI;EAEO,KAAA,YAAA;EAC7B,KAAAC,KAAA;CAEN;CAEvB,OAAc,cAA4B;EACxC,OAAQF,cAAaC,OAAa,IAAID,cAAa;CACrD;;;;;CAMA,SAAgB,KAAc,QAAgB,UAA4B;EACxE,MAAM,YAAY,WAAW,IAAI;EACjC,KAAK,MAAM,IAAI,KAAK;GAAE;GAAW;EAAS,CAAC;EAE3C,IAAI,CAAC,KAAKE,IAAoB;GAC5B,KAAKA,KAAqB;GAC1B,QAAQ,QAAQ,CAAA,CAAE,WAAW;IAC3B,KAAKA,KAAqB;IAC1B,KAAKC,GAAc;GACrB,CAAC;EACH;CACF;CAEA,OAAc,KAAoB;EAChC,KAAK,MAAM,OAAO,GAAG;EAMrB,IAAI,KAAK,MAAM,SAAS,KAAK,KAAK,cAAc,MAAM;GACpD,aAAa,KAAK,SAAS;GAC3B,KAAK,YAAY;EACnB;CACF;;;;CAK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