@yuebai008/cli
Version:
Command line interface for rapid qg-minigame development
1 lines • 11.6 kB
JavaScript
import*as Common from"../common/common.js";import*as Host from"../host/host.js";import{DebuggerModel}from"./DebuggerModel.js";import{HeapProfilerModel}from"./HeapProfilerModel.js";import{RemoteFunction,RemoteObject,RemoteObjectImpl,RemoteObjectProperty,ScopeRemoteObject}from"./RemoteObject.js";import{Capability,Type}from"./Target.js";import{SDKModel}from"./SDKModel.js";export class RuntimeModel extends SDKModel{agent;#e;#t;#n;constructor(e){super(e),this.agent=e.runtimeAgent(),this.target().registerRuntimeDispatcher(new RuntimeDispatcher(this)),this.agent.invoke_enable(),this.#e=new Map,this.#t=ExecutionContext.comparator,this.#n=null,Common.Settings.Settings.instance().moduleSetting("customFormatters").get()&&this.agent.invoke_setCustomObjectFormatterEnabled({enabled:!0}),Common.Settings.Settings.instance().moduleSetting("customFormatters").addChangeListener(this.customFormattersStateChanged.bind(this))}static isSideEffectFailure(e){const t="exceptionDetails"in e&&e.exceptionDetails;return Boolean(t&&t.exception&&t.exception.description&&t.exception.description.startsWith("EvalError: Possible side-effect in debug-evaluate"))}debuggerModel(){return this.target().model(DebuggerModel)}heapProfilerModel(){return this.target().model(HeapProfilerModel)}executionContexts(){return[...this.#e.values()].sort(this.executionContextComparator())}setExecutionContextComparator(e){this.#t=e}executionContextComparator(){return this.#t}defaultExecutionContext(){for(const e of this.executionContexts())if(e.isDefault)return e;return null}executionContext(e){return this.#e.get(e)||null}executionContextCreated(e){const t=e.auxData||{isDefault:!0},n=new ExecutionContext(this,e.id,e.uniqueId,e.name,e.origin,t.isDefault,t.frameId);this.#e.set(n.id,n),this.dispatchEventToListeners(Events.ExecutionContextCreated,n)}executionContextDestroyed(e){const t=this.#e.get(e);t&&(this.debuggerModel().executionContextDestroyed(t),this.#e.delete(e),this.dispatchEventToListeners(Events.ExecutionContextDestroyed,t))}fireExecutionContextOrderChanged(){this.dispatchEventToListeners(Events.ExecutionContextOrderChanged,this)}executionContextsCleared(){this.debuggerModel().globalObjectCleared();const e=this.executionContexts();this.#e.clear();for(let t=0;t<e.length;++t)this.dispatchEventToListeners(Events.ExecutionContextDestroyed,e[t])}createRemoteObject(e){return console.assert("object"==typeof e,"Remote object payload should only be an object"),new RemoteObjectImpl(this,e.objectId,e.type,e.subtype,e.value,e.unserializableValue,e.description,e.preview,e.customPreview,e.className)}createScopeRemoteObject(e,t){return new ScopeRemoteObject(this,e.objectId,t,e.type,e.subtype,e.value,e.unserializableValue,e.description,e.preview)}createRemoteObjectFromPrimitiveValue(e){const t=typeof e;let n;const o=RemoteObject.unserializableDescription(e);return null!==o&&(n=o),void 0!==n&&(e=void 0),new RemoteObjectImpl(this,void 0,t,void 0,e,n)}createRemotePropertyFromPrimitiveValue(e,t){return new RemoteObjectProperty(e,this.createRemoteObjectFromPrimitiveValue(t))}discardConsoleEntries(){this.agent.invoke_discardConsoleEntries()}releaseObjectGroup(e){this.agent.invoke_releaseObjectGroup({objectGroup:e})}releaseEvaluationResult(e){if("object"in e&&e.object&&e.object.release(),"exceptionDetails"in e&&e.exceptionDetails&&e.exceptionDetails.exception){const t=e.exceptionDetails.exception;this.createRemoteObject({type:t.type,objectId:t.objectId}).release()}}runIfWaitingForDebugger(){this.agent.invoke_runIfWaitingForDebugger()}customFormattersStateChanged({data:e}){this.agent.invoke_setCustomObjectFormatterEnabled({enabled:e})}async compileScript(e,t,n,o){const i=await this.agent.invoke_compileScript({expression:e,sourceURL:t,persistScript:n,executionContextId:o});return i.getError()?(console.error(i.getError()),null):{scriptId:i.scriptId,exceptionDetails:i.exceptionDetails}}async runScript(e,t,n,o,i,r,s,a){const c=await this.agent.invoke_runScript({scriptId:e,executionContextId:t,objectGroup:n,silent:o,includeCommandLineAPI:i,returnByValue:r,generatePreview:s,awaitPromise:a}),l=c.getError();return l?(console.error(l),{error:l}):{object:this.createRemoteObject(c.result),exceptionDetails:c.exceptionDetails}}async queryObjects(e){if(!e.objectId)return{error:"Prototype should be an Object."};const t=await this.agent.invoke_queryObjects({prototypeObjectId:e.objectId,objectGroup:"console"}),n=t.getError();return n?(console.error(n),{error:n}):{objects:this.createRemoteObject(t.objects)}}async isolateId(){const e=await this.agent.invoke_getIsolateId();return e.getError()||!e.id?this.target().id():e.id}async heapUsage(){const e=await this.agent.invoke_getHeapUsage();return e.getError()?null:e}inspectRequested(e,t,n){const o=this.createRemoteObject(e);t&&"copyToClipboard"in t&&Boolean(t.copyToClipboard)?this.copyRequested(o):t&&"queryObjects"in t&&t.queryObjects?this.queryObjectsRequested(o,n):o.isNode()?Common.Revealer.reveal(o).then(o.release.bind(o)):"function"!==o.type?o.release():RemoteFunction.objectAsFunction(o).targetFunctionDetails().then((function(e){if(o.release(),!e||!e.location)return;Common.Revealer.reveal(e.location)}))}async addBinding(e){return await this.agent.invoke_addBinding(e)}bindingCalled(e){this.dispatchEventToListeners(Events.BindingCalled,e)}copyRequested(e){if(!e.objectId)return void Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText(e.unserializableValue()||e.value);const t=Common.Settings.Settings.instance().moduleSetting("textEditorIndent").get();e.callFunctionJSON((function(e){const t=e.subtype,n=e.indent;if("node"===t)return this instanceof Element?this.outerHTML:void 0;if(t&&void 0===this)return String(t);try{return JSON.stringify(this,null,n)}catch(e){return String(this)}}),[{value:{subtype:e.subtype,indent:t}}]).then(Host.InspectorFrontendHost.InspectorFrontendHostInstance.copyText.bind(Host.InspectorFrontendHost.InspectorFrontendHostInstance))}async queryObjectsRequested(e,t){const n=await this.queryObjects(e);e.release(),"error"in n?Common.Console.Console.instance().error(n.error):this.dispatchEventToListeners(Events.QueryObjectRequested,{objects:n.objects,executionContextId:t})}static simpleTextFromException(e){let t=e.text;if(e.exception&&e.exception.description){let n=e.exception.description;-1!==n.indexOf("\n")&&(n=n.substring(0,n.indexOf("\n"))),t+=" "+n}return t}exceptionThrown(e,t){const n={timestamp:e,details:t};this.dispatchEventToListeners(Events.ExceptionThrown,n)}exceptionRevoked(e){this.dispatchEventToListeners(Events.ExceptionRevoked,e)}consoleAPICalled(e,t,n,o,i,r){const s={type:e,args:t,executionContextId:n,timestamp:o,stackTrace:i,context:r};this.dispatchEventToListeners(Events.ConsoleAPICalled,s)}executionContextIdForScriptId(e){const t=this.debuggerModel().scriptForId(e);return t?t.executionContextId:0}executionContextForStackTrace(e){let t=e;for(;t&&!t.callFrames.length;)t=t.parent||null;return t&&t.callFrames.length?this.executionContextIdForScriptId(t.callFrames[0].scriptId):0}hasSideEffectSupport(){return this.#n}async checkSideEffectSupport(){const e=this.executionContexts(),t=e[e.length-1];if(!t)return!1;const n=await this.agent.invoke_evaluate({expression:_sideEffectTestExpression,contextId:t.id,throwOnSideEffect:!0});return this.#n=!n.getError()&&RuntimeModel.isSideEffectFailure(n),this.#n}terminateExecution(){return this.agent.invoke_terminateExecution()}async getExceptionDetails(e){const t=await this.agent.invoke_getExceptionDetails({errorObjectId:e});if(!t.getError())return t.exceptionDetails}}const _sideEffectTestExpression="(async function(){ await 1; })()";export var Events;!function(e){e.BindingCalled="BindingCalled",e.ExecutionContextCreated="ExecutionContextCreated",e.ExecutionContextDestroyed="ExecutionContextDestroyed",e.ExecutionContextChanged="ExecutionContextChanged",e.ExecutionContextOrderChanged="ExecutionContextOrderChanged",e.ExceptionThrown="ExceptionThrown",e.ExceptionRevoked="ExceptionRevoked",e.ConsoleAPICalled="ConsoleAPICalled",e.QueryObjectRequested="QueryObjectRequested"}(Events||(Events={}));class RuntimeDispatcher{#o;constructor(e){this.#o=e}executionContextCreated({context:e}){this.#o.executionContextCreated(e)}executionContextDestroyed({executionContextId:e}){this.#o.executionContextDestroyed(e)}executionContextsCleared(){this.#o.executionContextsCleared()}exceptionThrown({timestamp:e,exceptionDetails:t}){this.#o.exceptionThrown(e,t)}exceptionRevoked({exceptionId:e}){this.#o.exceptionRevoked(e)}consoleAPICalled({type:e,args:t,executionContextId:n,timestamp:o,stackTrace:i,context:r}){this.#o.consoleAPICalled(e,t,n,o,i,r)}inspectRequested({object:e,hints:t,executionContextId:n}){this.#o.inspectRequested(e,t,n)}bindingCalled(e){this.#o.bindingCalled(e)}}export class ExecutionContext{id;uniqueId;name;#i;origin;isDefault;runtimeModel;debuggerModel;frameId;constructor(e,t,n,o,i,r,s){this.id=t,this.uniqueId=n,this.name=o,this.#i=null,this.origin=i,this.isDefault=r,this.runtimeModel=e,this.debuggerModel=e.debuggerModel(),this.frameId=s,this.setLabelInternal("")}target(){return this.runtimeModel.target()}static comparator(e,t){function n(e){return e.parentTarget()?.type()!==Type.Frame?5:e.type()===Type.Frame?4:e.type()===Type.ServiceWorker?3:e.type()===Type.Worker||e.type()===Type.SharedWorker?2:1}function o(e){let t=e;const n=[];for(;t;)n.push(t),t=t.parentTarget();return n.reverse()}const i=o(e.target()),r=o(t.target());let s,a;for(let e=0;;e++)if(!i[e]||!r[e]||i[e]!==r[e]){s=i[e],a=r[e];break}if(!s&&a)return-1;if(!a&&s)return 1;if(s&&a){const e=n(s)-n(a);return e?-e:s.id().localeCompare(a.id())}return e.isDefault?-1:t.isDefault?1:e.name.localeCompare(t.name)}async evaluate(e,t,n){if(this.debuggerModel.selectedCallFrame())return this.debuggerModel.evaluateOnSelectedCallFrame(e);return!(Boolean(e.throwOnSideEffect)||void 0!==e.timeout)||this.runtimeModel.hasSideEffectSupport()||!1!==this.runtimeModel.hasSideEffectSupport()&&(await this.runtimeModel.checkSideEffectSupport(),this.runtimeModel.hasSideEffectSupport())?this.evaluateGlobal(e,t,n):{error:"Side-effect checks not supported by backend."}}globalObject(e,t){const n={expression:"this",objectGroup:e,includeCommandLineAPI:!1,silent:!0,returnByValue:!1,generatePreview:t};return this.evaluateGlobal(n,!1,!1)}async evaluateGlobal(e,t,n){e.expression||(e.expression="this");const o=await this.runtimeModel.agent.invoke_evaluate({expression:e.expression,objectGroup:e.objectGroup,includeCommandLineAPI:e.includeCommandLineAPI,silent:e.silent,returnByValue:e.returnByValue,generatePreview:e.generatePreview,userGesture:t,awaitPromise:n,throwOnSideEffect:e.throwOnSideEffect,timeout:e.timeout,disableBreaks:e.disableBreaks,replMode:e.replMode,allowUnsafeEvalBlockedByCSP:e.allowUnsafeEvalBlockedByCSP,...this.uniqueId?{uniqueContextId:this.uniqueId}:{contextId:this.id}}),i=o.getError();return i?(console.error(i),{error:i}):{object:this.runtimeModel.createRemoteObject(o.result),exceptionDetails:o.exceptionDetails}}async globalLexicalScopeNames(){const e=await this.runtimeModel.agent.invoke_globalLexicalScopeNames({executionContextId:this.id});return e.getError()?[]:e.names}label(){return this.#i}setLabel(e){this.setLabelInternal(e),this.runtimeModel.dispatchEventToListeners(Events.ExecutionContextChanged,this)}setLabelInternal(e){if(e)return void(this.#i=e);if(this.name)return void(this.#i=this.name);const t=Common.ParsedURL.ParsedURL.fromString(this.origin);this.#i=t?t.lastPathComponentWithFragment():""}}SDKModel.register(RuntimeModel,{capabilities:Capability.JS,autostart:!0});