import { PeerMap } from "./map.js";
class TrackedPeerMap extends PeerMap {
    metric;
    constructor(init) {
        super();
        const { name, metrics } = init;
        this.metric = metrics.registerMetric(name);
        this.updateComponentMetric();
    }
    set(key, value) {
        super.set(key, value);
        this.updateComponentMetric();
        return this;
    }
    delete(key) {
        const deleted = super.delete(key);
        this.updateComponentMetric();
        return deleted;
    }
    clear() {
        super.clear();
        this.updateComponentMetric();
    }
    updateComponentMetric() {
        this.metric.update(this.size);
    }
}
/**
 * Creates a PeerMap that reports it's size to the libp2p Metrics service
 *
 * @example
 *
 * ```Typescript
 * import { trackedPeerMap } from '@libp2p/peer-collections'
 * import { createLibp2p } from 'libp2p'
 *
 * const libp2p = await createLibp2p()
 *
 * const list = trackedPeerMap({ name: 'my_metric_name', metrics: libp2p.metrics })
 * map.set(peerId, 'value')
 * ```
 */
export function trackedPeerMap(config) {
    const { name, metrics } = config;
    let map;
    if (metrics != null) {
        map = new TrackedPeerMap({ name, metrics });
    }
    else {
        map = new PeerMap();
    }
    return map;
}
//# sourceMappingURL=tracked-map.js.map