import*as Common from"../common/common.js";import*as SDK from"../sdk/sdk.js";const uiSourceCodeToAttributionMap=new WeakMap,projectToTargetMap=new WeakMap;let networkProjectManagerInstance;export class NetworkProjectManager extends Common.ObjectWrapper.ObjectWrapper{constructor(){super()}static instance({forceNew:e}={forceNew:!1}){return networkProjectManagerInstance&&!e||(networkProjectManagerInstance=new NetworkProjectManager),networkProjectManagerInstance}}export const Events={FrameAttributionAdded:Symbol("FrameAttributionAdded"),FrameAttributionRemoved:Symbol("FrameAttributionRemoved")};export class NetworkProject{static _resolveFrame(e,t){const r=NetworkProject.targetForUISourceCode(e),o=r&&r.model(SDK.ResourceTreeModel.ResourceTreeModel);return o?o.frameForId(t):null}static setInitialFrameAttribution(e,t){const r=NetworkProject._resolveFrame(e,t);if(!r)return;const o=new Map;o.set(t,{frame:r,count:1}),uiSourceCodeToAttributionMap.set(e,o)}static cloneInitialFrameAttribution(e,t){const r=uiSourceCodeToAttributionMap.get(e);if(!r)return;const o=new Map;for(const n of r.keys()){const e=r.get(n);"undefined"!==typeof e&&o.set(n,{frame:e.frame,count:e.count})}uiSourceCodeToAttributionMap.set(t,o)}static addFrameAttribution(e,t){const r=NetworkProject._resolveFrame(e,t);if(!r)return;const o=uiSourceCodeToAttributionMap.get(e);if(!o)return;const n=o.get(t)||{frame:r,count:0};if(n.count+=1,o.set(t,n),1!==n.count)return;const a={uiSourceCode:e,frame:r};NetworkProjectManager.instance().dispatchEventToListeners(Events.FrameAttributionAdded,a)}static removeFrameAttribution(e,t){const r=uiSourceCodeToAttributionMap.get(e);if(!r)return;const o=r.get(t);if(console.assert(Boolean(o),"Failed to remove frame attribution for url: "+e.url()),!o)return;if(o.count-=1,o.count>0)return;r.delete(t);const n={uiSourceCode:e,frame:o.frame};NetworkProjectManager.instance().dispatchEventToListeners(Events.FrameAttributionRemoved,n)}static targetForUISourceCode(e){return projectToTargetMap.get(e.project())||null}static setTargetForProject(e,t){projectToTargetMap.set(e,t)}static getTargetForProject(e){return projectToTargetMap.get(e)||null}static framesForUISourceCode(e){const t=NetworkProject.targetForUISourceCode(e),r=t&&t.model(SDK.ResourceTreeModel.ResourceTreeModel),o=uiSourceCodeToAttributionMap.get(e);if(!r||!o)return[];return Array.from(o.keys()).map((e=>r.frameForId(e))).filter((e=>Boolean(e)))}}