@yuebai008/cli
Version:
Command line interface for rapid qg-minigame development
1 lines • 19.3 kB
JavaScript
import*as Common from"../common/common.js";import*as i18n from"../i18n/i18n.js";import*as Platform from"../platform/platform.js";import{DOMModel}from"./DOMModel.js";import{Events as NetworkManagerEvents,NetworkManager}from"./NetworkManager.js";import{Resource}from"./Resource.js";import{ExecutionContext,RuntimeModel}from"./RuntimeModel.js";import{Capability,Type}from"./Target.js";import{SDKModel}from"./SDKModel.js";import{TargetManager}from"./TargetManager.js";import{SecurityOriginManager}from"./SecurityOriginManager.js";import{StorageKeyManager}from"./StorageKeyManager.js";import{FrameManager}from"./FrameManager.js";export class ResourceTreeModel extends SDKModel{agent;storageAgent;#e;#r;framesInternal;#t;#a;#s;isInterstitialShowing;mainFrame;#n;#i;constructor(e){super(e);const r=e.model(NetworkManager);r&&(r.addEventListener(NetworkManagerEvents.RequestFinished,this.onRequestFinished,this),r.addEventListener(NetworkManagerEvents.RequestUpdateDropped,this.onRequestUpdateDropped,this)),this.agent=e.pageAgent(),this.storageAgent=e.storageAgent(),this.agent.invoke_enable(),this.#e=e.model(SecurityOriginManager),this.#r=e.model(StorageKeyManager),this.#n=new Set,this.#i=new Set,e.registerPageDispatcher(new PageDispatcher(this)),e.registerPreloadDispatcher(new PreloadDispatcher(this)),this.framesInternal=new Map,this.#t=!1,this.#a=null,this.#s=0,this.isInterstitialShowing=!1,this.mainFrame=null,this.#o()}async#o(){return this.agent.invoke_getResourceTree().then((e=>{this.processCachedResources(e.getError()?null:e.frameTree),this.mainFrame&&this.processPendingEvents(this.mainFrame)}))}static frameForRequest(e){const r=NetworkManager.forRequest(e),t=r?r.target().model(ResourceTreeModel):null;return t&&e.frameId?t.frameForId(e.frameId):null}static frames(){const e=[];for(const r of TargetManager.instance().models(ResourceTreeModel))e.push(...r.frames());return e}static resourceForURL(e){for(const r of TargetManager.instance().models(ResourceTreeModel)){const t=r.mainFrame,a=t?t.resourceForURL(e):null;if(a)return a}return null}static reloadAllPages(e,r){for(const t of TargetManager.instance().models(ResourceTreeModel))t.target().parentTarget()?.type()!==Type.Frame&&t.reloadPage(e,r)}async storageKeyForFrame(e){if(!this.framesInternal.has(e))return null;const r=await this.storageAgent.invoke_getStorageKeyForFrame({frameId:e});return"Frame tree node for given frame not found"===r.getError()?null:r.storageKey}domModel(){return this.target().model(DOMModel)}processCachedResources(e){e&&":"!==e.frame.url&&(this.dispatchEventToListeners(Events.WillLoadCachedResources),this.addFramesRecursively(null,e),this.target().setInspectedURL(e.frame.url)),this.#t=!0;const r=this.target().model(RuntimeModel);r&&(r.setExecutionContextComparator(this.executionContextComparator.bind(this)),r.fireExecutionContextOrderChanged()),this.dispatchEventToListeners(Events.CachedResourcesLoaded,this)}cachedResourcesLoaded(){return this.#t}addFrame(e,r){this.framesInternal.set(e.id,e),e.isMainFrame()&&(this.mainFrame=e),this.dispatchEventToListeners(Events.FrameAdded,e),this.updateSecurityOrigins(),this.updateStorageKeys()}frameAttached(e,r,t){const a=r&&this.framesInternal.get(r)||null;if(!this.#t&&a)return null;if(this.framesInternal.has(e))return null;const s=new ResourceTreeFrame(this,a,e,null,t||null);return r&&!a&&(s.crossTargetParentFrameId=r),s.isMainFrame()&&this.mainFrame&&this.frameDetached(this.mainFrame.id,!1),this.addFrame(s,!0),s}frameNavigated(e,r){const t=e.parentId&&this.framesInternal.get(e.parentId)||null;if(!this.#t&&t)return;let a=this.framesInternal.get(e.id)||null;if(!a&&(a=this.frameAttached(e.id,e.parentId||null),console.assert(Boolean(a)),!a))return;this.dispatchEventToListeners(Events.FrameWillNavigate,a),a.navigate(e),r&&(a.backForwardCacheDetails.restoredFromCache="BackForwardCacheRestore"===r),this.dispatchEventToListeners(Events.FrameNavigated,a),a.isPrimaryFrame()&&this.primaryPageChanged(a,"Navigation");const s=a.resources();for(let e=0;e<s.length;++e)this.dispatchEventToListeners(Events.ResourceAdded,s[e]);a.isMainFrame()&&this.target().setInspectedURL(a.url),this.updateSecurityOrigins(),this.updateStorageKeys(),a.backForwardCacheDetails.restoredFromCache&&(FrameManager.instance().modelRemoved(this),FrameManager.instance().modelAdded(this),this.#o())}primaryPageChanged(e,r){this.processPendingEvents(e),this.dispatchEventToListeners(Events.PrimaryPageChanged,{frame:e,type:r});const t=this.target().model(NetworkManager);t&&e.isOutermostFrame()&&t.clearRequests()}documentOpened(e){this.frameNavigated(e,void 0);const r=this.framesInternal.get(e.id);if(r&&!r.getResourcesMap().get(e.url)){const t=this.createResourceFromFramePayload(e,e.url,Common.ResourceType.resourceTypes.Document,e.mimeType,null,null);t.isGenerated=!0,r.addResource(t)}}frameDetached(e,r){if(!this.#t)return;const t=this.framesInternal.get(e);if(!t)return;const a=t.sameTargetParentFrame();a?a.removeChildFrame(t,r):t.remove(r),this.updateSecurityOrigins(),this.updateStorageKeys()}onRequestFinished(e){if(!this.#t)return;const r=e.data;if(r.failed)return;const t=r.frameId?this.framesInternal.get(r.frameId):null;t&&t.addRequest(r)}onRequestUpdateDropped(e){if(!this.#t)return;const r=e.data,t=r.frameId;if(!t)return;const a=this.framesInternal.get(t);if(!a)return;const s=r.url;if(a.getResourcesMap().get(s))return;const n=new Resource(this,null,s,a.url,t,r.loaderId,Common.ResourceType.resourceTypes[r.resourceType],r.mimeType,r.lastModified,null);a.addResource(n)}frameForId(e){return this.framesInternal.get(e)||null}forAllResources(e){return!!this.mainFrame&&this.mainFrame.callForFrameResources(e)}frames(){return[...this.framesInternal.values()]}resourceForURL(e){return this.mainFrame?this.mainFrame.resourceForURL(e):null}addFramesRecursively(e,r){const t=r.frame;let a=this.framesInternal.get(t.id);a||(a=new ResourceTreeFrame(this,e,t.id,t,null)),!e&&t.parentId&&(a.crossTargetParentFrameId=t.parentId),this.addFrame(a);for(const e of r.childFrames||[])this.addFramesRecursively(a,e);for(let e=0;e<r.resources.length;++e){const s=r.resources[e],n=this.createResourceFromFramePayload(t,s.url,Common.ResourceType.resourceTypes[s.type],s.mimeType,s.lastModified||null,s.contentSize||null);a.addResource(n)}if(!a.getResourcesMap().get(t.url)){const e=this.createResourceFromFramePayload(t,t.url,Common.ResourceType.resourceTypes.Document,t.mimeType,null,null);a.addResource(e)}}createResourceFromFramePayload(e,r,t,a,s,n){const i="number"==typeof s?new Date(1e3*s):null;return new Resource(this,null,r,e.url,e.id,e.loaderId,t,a,i,n)}suspendReload(){this.#s++}resumeReload(){if(this.#s--,console.assert(this.#s>=0,"Unbalanced call to ResourceTreeModel.resumeReload()"),!this.#s&&this.#a){const{ignoreCache:e,scriptToEvaluateOnLoad:r}=this.#a;this.reloadPage(e,r)}}reloadPage(e,r){if(this.#a||this.dispatchEventToListeners(Events.PageReloadRequested,this),this.#s)return void(this.#a={ignoreCache:e,scriptToEvaluateOnLoad:r});this.#a=null;const t=this.target().model(NetworkManager);t&&t.clearRequests(),this.dispatchEventToListeners(Events.WillReloadPage),this.agent.invoke_reload({ignoreCache:e,scriptToEvaluateOnLoad:r})}navigate(e){return this.agent.invoke_navigate({url:e})}async navigationHistory(){const e=await this.agent.invoke_getNavigationHistory();return e.getError()?null:{currentIndex:e.currentIndex,entries:e.entries}}navigateToHistoryEntry(e){this.agent.invoke_navigateToHistoryEntry({entryId:e.id})}setLifecycleEventsEnabled(e){return this.agent.invoke_setLifecycleEventsEnabled({enabled:e})}async fetchAppManifest(){const e=await this.agent.invoke_getAppManifest();return e.getError()?{url:e.url,data:null,errors:[]}:{url:e.url,data:e.data||null,errors:e.errors}}async getInstallabilityErrors(){return(await this.agent.invoke_getInstallabilityErrors()).installabilityErrors||[]}async getAppId(){return this.agent.invoke_getAppId()}executionContextComparator(e,r){function t(e){let r=e;const t=[];for(;r;)t.push(r),r=r.sameTargetParentFrame();return t.reverse()}if(e.target()!==r.target())return ExecutionContext.comparator(e,r);const a=e.frameId?t(this.frameForId(e.frameId)):[],s=r.frameId?t(this.frameForId(r.frameId)):[];let n,i;for(let e=0;;e++)if(!a[e]||!s[e]||a[e]!==s[e]){n=a[e],i=s[e];break}return!n&&i?-1:!i&&n?1:n&&i?n.id.localeCompare(i.id):ExecutionContext.comparator(e,r)}getSecurityOriginData(){const e=new Set;let r=null,t=null;for(const a of this.framesInternal.values()){const s=a.securityOrigin;if(s&&(e.add(s),a.isMainFrame()&&(r=s,a.unreachableUrl()))){t=new Common.ParsedURL.ParsedURL(a.unreachableUrl()).securityOrigin()}}return{securityOrigins:e,mainSecurityOrigin:r,unreachableMainSecurityOrigin:t}}async getStorageKeyData(){const e=new Set;let r=null;for(const{isMainFrame:t,storageKey:a}of await Promise.all([...this.framesInternal.values()].map((e=>e.getStorageKey(!1).then((r=>({isMainFrame:e.isMainFrame(),storageKey:r})))))))t&&(r=a),a&&e.add(a);return{storageKeys:e,mainStorageKey:r}}updateSecurityOrigins(){const e=this.getSecurityOriginData();this.#e.setMainSecurityOrigin(e.mainSecurityOrigin||"",e.unreachableMainSecurityOrigin||""),this.#e.updateSecurityOrigins(e.securityOrigins)}async updateStorageKeys(){const e=await this.getStorageKeyData();this.#r.setMainStorageKey(e.mainStorageKey||""),this.#r.updateStorageKeys(e.storageKeys)}async getMainStorageKey(){return this.mainFrame?this.mainFrame.getStorageKey(!1):null}getMainSecurityOrigin(){const e=this.getSecurityOriginData();return e.mainSecurityOrigin||e.unreachableMainSecurityOrigin}onBackForwardCacheNotUsed(e){this.mainFrame&&this.mainFrame.id===e.frameId&&this.mainFrame.loaderId===e.loaderId?(this.mainFrame.setBackForwardCacheDetails(e),this.dispatchEventToListeners(Events.BackForwardCacheDetailsUpdated,this.mainFrame)):this.#n.add(e)}onPrerenderAttemptCompleted(e){this.mainFrame&&this.mainFrame.id===e.initiatingFrameId?(this.mainFrame.setPrerenderFinalStatus(e.finalStatus),this.dispatchEventToListeners(Events.PrerenderingStatusUpdated,this.mainFrame),e.disallowedApiMethod&&this.mainFrame.setPrerenderDisallowedApiMethod(e.disallowedApiMethod)):this.#i.add(e),this.dispatchEventToListeners(Events.PrerenderAttemptCompleted,e)}processPendingEvents(e){if(e.isMainFrame()){for(const r of this.#n)if(e.id===r.frameId&&e.loaderId===r.loaderId){e.setBackForwardCacheDetails(r),this.#n.delete(r);break}for(const r of this.#i)if(e.id===r.initiatingFrameId){e.setPrerenderFinalStatus(r.finalStatus),r.disallowedApiMethod&&e.setPrerenderDisallowedApiMethod(r.disallowedApiMethod),this.#i.delete(r);break}}}}export var Events;!function(e){e.FrameAdded="FrameAdded",e.FrameNavigated="FrameNavigated",e.FrameDetached="FrameDetached",e.FrameResized="FrameResized",e.FrameWillNavigate="FrameWillNavigate",e.PrimaryPageChanged="PrimaryPageChanged",e.ResourceAdded="ResourceAdded",e.WillLoadCachedResources="WillLoadCachedResources",e.CachedResourcesLoaded="CachedResourcesLoaded",e.DOMContentLoaded="DOMContentLoaded",e.LifecycleEvent="LifecycleEvent",e.Load="Load",e.PageReloadRequested="PageReloadRequested",e.WillReloadPage="WillReloadPage",e.InterstitialShown="InterstitialShown",e.InterstitialHidden="InterstitialHidden",e.BackForwardCacheDetailsUpdated="BackForwardCacheDetailsUpdated",e.PrerenderingStatusUpdated="PrerenderingStatusUpdated",e.PrerenderAttemptCompleted="PrerenderAttemptCompleted",e.JavaScriptDialogOpening="JavaScriptDialogOpening"}(Events||(Events={}));export class ResourceTreeFrame{#d;#l;#c;crossTargetParentFrameId;#u;#h;#m;#g;#p;#F;#y;#f;#I;#T;#v;#M;#R;#S;resourcesMap;backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};prerenderFinalStatus;prerenderDisallowedApiMethod;constructor(e,r,t,a,s){this.#d=e,this.#l=r,this.#c=t,this.crossTargetParentFrameId=null,this.#u=a&&a.loaderId||"",this.#h=a&&a.name,this.#m=a&&a.url||Platform.DevToolsPath.EmptyUrlString,this.#g=a&&a.domainAndRegistry||"",this.#p=a&&a.securityOrigin,this.#y=a&&a.unreachableUrl||Platform.DevToolsPath.EmptyUrlString,this.#f=a?.adFrameStatus,this.#I=a&&a.secureContextType,this.#T=a&&a.crossOriginIsolatedContextType,this.#v=a&&a.gatedAPIFeatures,this.#M=s,this.#R=null,this.#S=new Set,this.resourcesMap=new Map,this.prerenderFinalStatus=null,this.prerenderDisallowedApiMethod=null,this.#l&&this.#l.#S.add(this)}isSecureContext(){return null!==this.#I&&this.#I.startsWith("Secure")}getSecureContextType(){return this.#I}isCrossOriginIsolated(){return null!==this.#T&&this.#T.startsWith("Isolated")}getCrossOriginIsolatedContextType(){return this.#T}getGatedAPIFeatures(){return this.#v}getCreationStackTraceData(){return{creationStackTrace:this.#M,creationStackTraceTarget:this.#R||this.resourceTreeModel().target()}}navigate(e){this.#u=e.loaderId,this.#h=e.name,this.#m=e.url,this.#g=e.domainAndRegistry,this.#p=e.securityOrigin,this.getStorageKey(!0),this.#y=e.unreachableUrl||Platform.DevToolsPath.EmptyUrlString,this.#f=e?.adFrameStatus,this.#I=e.secureContextType,this.#T=e.crossOriginIsolatedContextType,this.#v=e.gatedAPIFeatures,this.backForwardCacheDetails={restoredFromCache:void 0,explanations:[],explanationsTree:void 0};const r=this.resourcesMap.get(this.#m);this.resourcesMap.clear(),this.removeChildFrames(),r&&r.loaderId===this.#u&&this.addResource(r)}resourceTreeModel(){return this.#d}get id(){return this.#c}get name(){return this.#h||""}get url(){return this.#m}domainAndRegistry(){return this.#g}async getAdScriptId(e){return(await this.#d.agent.invoke_getAdScriptId({frameId:e})).adScriptId||null}get securityOrigin(){return this.#p}getStorageKey(e){return this.#F&&!e||(this.#F=this.#d.storageKeyForFrame(this.#c)),this.#F}unreachableUrl(){return this.#y}get loaderId(){return this.#u}adFrameType(){return this.#f?.adFrameType||"none"}adFrameStatus(){return this.#f}get childFrames(){return[...this.#S]}sameTargetParentFrame(){return this.#l}crossTargetParentFrame(){if(!this.crossTargetParentFrameId)return null;const e=this.#d.target().parentTarget();if(e?.type()!==Type.Frame)return null;const r=e.model(ResourceTreeModel);return r&&r.framesInternal.get(this.crossTargetParentFrameId)||null}parentFrame(){return this.sameTargetParentFrame()||this.crossTargetParentFrame()}isMainFrame(){return!this.#l}isOutermostFrame(){return this.#d.target().parentTarget()?.type()!==Type.Frame&&!this.#l&&!this.crossTargetParentFrameId}isPrimaryFrame(){return!this.#l&&this.#d.target()===TargetManager.instance().primaryPageTarget()}removeChildFrame(e,r){this.#S.delete(e),e.remove(r)}removeChildFrames(){const e=this.#S;this.#S=new Set;for(const r of e)r.remove(!1)}remove(e){this.removeChildFrames(),this.#d.framesInternal.delete(this.id),this.#d.dispatchEventToListeners(Events.FrameDetached,{frame:this,isSwap:e})}addResource(e){this.resourcesMap.get(e.url)!==e&&(this.resourcesMap.set(e.url,e),this.#d.dispatchEventToListeners(Events.ResourceAdded,e))}addRequest(e){let r=this.resourcesMap.get(e.url());r&&r.request===e||(r=new Resource(this.#d,e,e.url(),e.documentURL,e.frameId,e.loaderId,e.resourceType(),e.mimeType,null,null),this.resourcesMap.set(r.url,r),this.#d.dispatchEventToListeners(Events.ResourceAdded,r))}resources(){return Array.from(this.resourcesMap.values())}resourceForURL(e){const r=this.resourcesMap.get(e);if(r)return r;for(const r of this.#S){const t=r.resourceForURL(e);if(t)return t}return null}callForFrameResources(e){for(const r of this.resourcesMap.values())if(e(r))return!0;for(const r of this.#S)if(r.callForFrameResources(e))return!0;return!1}displayName(){if(this.isOutermostFrame())return i18n.i18n.lockedString("top");const e=new Common.ParsedURL.ParsedURL(this.#m).displayName;return e?this.#h?this.#h+" ("+e+")":e:i18n.i18n.lockedString("iframe")}async getOwnerDeferredDOMNode(){const e=this.parentFrame();return e?e.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#c):null}async getOwnerDOMNodeOrDocument(){const e=await this.getOwnerDeferredDOMNode();return e?e.resolvePromise():this.isOutermostFrame()?this.resourceTreeModel().domModel().requestDocument():null}async highlight(){const e=this.parentFrame(),r=this.resourceTreeModel().target().parentTarget(),t=async e=>{const r=await e.getOwnerNodeForFrame(this.#c);r&&e.overlayModel().highlightInOverlay({deferredNode:r,selectorList:""},"all",!0)};if(e)return t(e.resourceTreeModel().domModel());if(r?.type()===Type.Frame){const e=r.model(DOMModel);if(e)return t(e)}const a=await this.resourceTreeModel().domModel().requestDocument();a&&this.resourceTreeModel().domModel().overlayModel().highlightInOverlay({node:a,selectorList:""},"all",!0)}async getPermissionsPolicyState(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getPermissionsPolicyState({frameId:this.#c});return e.getError()?null:e.states}async getOriginTrials(){const e=await this.resourceTreeModel().target().pageAgent().invoke_getOriginTrials({frameId:this.#c});return e.getError()?[]:e.originTrials}setCreationStackTrace(e){this.#M=e.creationStackTrace,this.#R=e.creationStackTraceTarget}setBackForwardCacheDetails(e){this.backForwardCacheDetails.restoredFromCache=!1,this.backForwardCacheDetails.explanations=e.notRestoredExplanations,this.backForwardCacheDetails.explanationsTree=e.notRestoredExplanationsTree}getResourcesMap(){return this.resourcesMap}setPrerenderFinalStatus(e){this.prerenderFinalStatus=e}setPrerenderDisallowedApiMethod(e){this.prerenderDisallowedApiMethod=e}}export class PageDispatcher{#C;constructor(e){this.#C=e}backForwardCacheNotUsed(e){this.#C.onBackForwardCacheNotUsed(e)}domContentEventFired({timestamp:e}){this.#C.dispatchEventToListeners(Events.DOMContentLoaded,e)}loadEventFired({timestamp:e}){this.#C.dispatchEventToListeners(Events.Load,{resourceTreeModel:this.#C,loadTime:e})}lifecycleEvent({frameId:e,name:r}){this.#C.dispatchEventToListeners(Events.LifecycleEvent,{frameId:e,name:r})}frameAttached({frameId:e,parentFrameId:r,stack:t}){this.#C.frameAttached(e,r,t)}frameNavigated({frame:e,type:r}){this.#C.frameNavigated(e,r)}documentOpened({frame:e}){this.#C.documentOpened(e)}frameDetached({frameId:e,reason:r}){this.#C.frameDetached(e,"swap"===r)}frameStartedLoading({}){}frameStoppedLoading({}){}frameRequestedNavigation({}){}frameScheduledNavigation({}){}frameClearedScheduledNavigation({}){}navigatedWithinDocument({}){}frameResized(){this.#C.dispatchEventToListeners(Events.FrameResized)}javascriptDialogOpening(e){this.#C.dispatchEventToListeners(Events.JavaScriptDialogOpening,e),e.hasBrowserHandler||this.#C.agent.invoke_handleJavaScriptDialog({accept:!1})}javascriptDialogClosed({}){}screencastFrame({}){}screencastVisibilityChanged({}){}interstitialShown(){this.#C.isInterstitialShowing=!0,this.#C.dispatchEventToListeners(Events.InterstitialShown)}interstitialHidden(){this.#C.isInterstitialShowing=!1,this.#C.dispatchEventToListeners(Events.InterstitialHidden)}windowOpen({}){}compilationCacheProduced({}){}fileChooserOpened({}){}downloadWillBegin({}){}downloadProgress(){}}class PreloadDispatcher{#C;constructor(e){this.#C=e}ruleSetUpdated(e){}ruleSetRemoved(e){}prerenderAttemptCompleted(e){this.#C.onPrerenderAttemptCompleted(e)}prefetchStatusUpdated(e){}prerenderStatusUpdated(e){}preloadEnabledStateUpdated(e){}preloadingAttemptSourcesUpdated(){}}SDKModel.register(ResourceTreeModel,{capabilities:Capability.DOM,autostart:!0,early:!0});