ten to all
    // newly attached contexts and update the cache behavior for them.
    if (this.#defaultCacheBehavior === CacheBehavior.Bypass) {
      this.#contextListener.startListening();
    } else {
      this.#contextListener.stopListening();
    }
  }

  #setLoadFlagsForBrowsingContext(browsingContext, loadFlags) {
    if (browsingContext.defaultLoadFlags !== loadFlags) {
      browsingContext.defaultLoadFlags = loadFlags;
    }
  }

  /**
   * Reset network cache behavior to the default.
   */
  cleanup() {
    this.#setDefaultCacheBehavior(CacheBehavior.Default);

    if (this.#getWeakMapSize(this.#navigableCacheBehaviorMap) === 0) {
      return;
    }

    const loadFlags = this.#getLoadFlags(CacheBehavior.Default);

    for (const browser of lazy.TabManager.getBrowsers()) {
      if (this.#navigableCacheBehaviorMap.has(browser.browsingContext)) {
        this.#setLoadFlagsForBrowsingContext(
          browser.browsingContext,
          loadFlags
        );
      }
    }

    this.#navigableCacheBehaviorMap = new WeakMap();
  }

  /**
   * Update network cache behavior to a provided value
   * and optionally specified contexts.
   *
   * @param {CacheBehavior} behavior
   *     An enum value to set the network cache behavior.
   * @param {Array<BrowsingContext>=} contexts
   *     The list of browsing contexts where the network cache
   *     behaviour should be updated.
   */
  updateCacheBehavior(behavior, contexts = null) {
    if (contexts === null) {
      this.#setDefaultCacheBehavior(behavior);
      return;
    }

    const loadFlags = this.#getLoadFlags(behavior);

    for (const context of contexts) {
      if (this.#navigableCacheBehaviorMap.get(context) === behavior) {
        continue;
      }

      this.#setLoadFlagsForBrowsingContext(context, loadFlags);

      if (behavior === CacheBehavior.Default) {
        this.#navigableCacheBehaviorMap.delete(context);
      } else {
        this.#navigableCacheBehaviorMap.set(context, behavior);
      }
    }
  }
}

// Create a private NetworkCacheManager singleton.
const networkCacheManager = new NetworkCacheManager();

export function updateCacheBehavior(behavior, contexts) {
  return networkCacheManager.updateCacheBehavior(behavior, contexts);
}

export function cleanupCacheBypassState() {
  return networkCacheManager.cleanup();
}
PK