diff --git a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp index dcccc4155c..eaa23364d9 100644 --- a/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp +++ b/native/cocos/scripting/js-bindings/manual/ScriptingCore.cpp @@ -2035,6 +2035,7 @@ bool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, JS::Value* vp) uint32_t nestLevel = ++s_nestedLoopLevel; while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) { + drainJobQueue(); if (!NS_ProcessNextEvent()) rv = NS_ERROR_UNEXPECTED; } @@ -2195,7 +2196,8 @@ bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, JS::Value* vp) { if (argc == 1) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - JSStringWrapper strWrapper(args.get(0)); + JS::RootedString jsstr(cx, args.get(0).toString()); + JSStringWrapper strWrapper(jsstr); // this is safe because we're already inside a lock (from clearBuffers) outData.append(strWrapper.get()); _clientSocketWriteAndClearString(outData); diff --git a/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js b/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js index 2ed34b40af..d69f27187d 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js +++ b/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js @@ -112,7 +112,7 @@ DevToolsUtils.safeErrorString = function safeErrorString(aError) { * Report that |aWho| threw an exception, |aException|. */ DevToolsUtils.reportException = function reportException(aWho, aException) { - let msg = aWho + " threw an exception: " + DevToolsUtils.safeErrorString(aException); + let msg = "" + aWho + " threw an exception: " + DevToolsUtils.safeErrorString(aException); log(msg + "\n"); @@ -245,7 +245,7 @@ DevToolsUtils.executeSoon = function executeSoon(aFn) { * A promise that is resolved after the next tick in the event loop. */ DevToolsUtils.waitForTick = function waitForTick() { - let deferred = promise.defer(); + let deferred = Promise.defer(); DevToolsUtils.executeSoon(deferred.resolve); return deferred.promise; }; @@ -259,7 +259,7 @@ DevToolsUtils.waitForTick = function waitForTick() { * A promise that is resolved after the specified amount of time passes. */ DevToolsUtils.waitForTime = function waitForTime(aDelay) { - let deferred = promise.defer(); + let deferred = Promise.defer(); require("Timer").setTimeout(deferred.resolve, aDelay); return deferred.promise; }; @@ -280,7 +280,7 @@ DevToolsUtils.waitForTime = function waitForTime(aDelay) { * over, and all promises returned by the aFn callback are resolved. */ DevToolsUtils.yieldingEach = function yieldingEach(aArray, aFn) { - const deferred = promise.defer(); + const deferred = Promise.defer(); let i = 0; let len = aArray.length; @@ -310,7 +310,7 @@ DevToolsUtils.yieldingEach = function yieldingEach(aArray, aFn) { deferred.resolve(); }()); - return promise.all(outstanding); + return Promise.all(outstanding); } /** @@ -452,7 +452,7 @@ DevToolsUtils.dumpv = function(msg) { // loader, so define it on dumpn instead. DevToolsUtils.dumpv.wantVerbose = false; -DevToolsUtils.dbg_assert = function dbg_assert(cond, e) { +DevToolsUtils.assert = function assert(cond, e) { if (!cond) { return e; } @@ -598,7 +598,7 @@ function mainThreadFetch(aURL, aOptions = { loadFromCache: true, try { channel = newChannelForURL(url, aOptions); } catch (ex) { - return promise.reject(ex); + return Promise.reject(ex); } // Set the channel options. @@ -614,12 +614,12 @@ function mainThreadFetch(aURL, aOptions = { loadFromCache: true, .loadGroup; } - let deferred = promise.defer(); + let deferred = Promise.defer(); let onResponse = (stream, status, request) => { - if (!components.isSuccessCode(status)) { - deferred.reject(new Error('Failed to fetch ${url}. Code ${status}.')); - return; - } +// if (!components.isSuccessCode(status)) { +// deferred.reject(new Error('Failed to fetch ${url}. Code ${status}.')); +// return; +// } try { // We cannot use NetUtil to do the charset conversion as if charset @@ -677,7 +677,7 @@ function mainThreadFetch(aURL, aOptions = { loadFromCache: true, try { NetUtil.asyncFetch(channel, onResponse); } catch (ex) { - return promise.reject(ex); + return Promise.reject(ex); } return deferred.promise; @@ -745,7 +745,7 @@ DevToolsUtils.settleAll = values => { throw new Error("settleAll() expects an iterable."); } - let deferred = promise.defer(); + let deferred = Promise.defer(); values = Array.isArray(values) ? values : [...values]; let countdown = values.length; @@ -822,12 +822,12 @@ DevToolsUtils.openFileStream = function (filePath) { NetUtil.asyncFetch( { uri, loadUsingSystemPrincipal: true }, (stream, result) => { - if (!components.isSuccessCode(result)) { - reject(new Error('Could not open "${filePath}": result = ${result}')); - return; - } +// if (!components.isSuccessCode(result)) { +// reject(new Error('Could not open "${filePath}": result = ${result}')); +// return; +// } - resolve(stream); + Promise.resolve(stream); } ); }); diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js new file mode 100644 index 0000000000..758d06d506 --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js @@ -0,0 +1,200 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +// const { ActorClassWithSpec } = require("devtools/shared/protocol"); +// const { breakpointSpec } = require("devtools/shared/specs/breakpoint"); + +// from "devtools/shared/specs/breakpoint" +const breakpointSpec = generateActorSpec({ + typeName: "breakpoint", + + methods: { + delete: {} + }, +}); + +// --------------- + +/** + * Set breakpoints on all the given entry points with the given + * BreakpointActor as the handler. + * + * @param BreakpointActor actor + * The actor handling the breakpoint hits. + * @param Array entryPoints + * An array of objects of the form `{ script, offsets }`. + */ +function setBreakpointAtEntryPoints(actor, entryPoints) { + for (let { script, offsets } of entryPoints) { + actor.addScript(script); + for (let offset of offsets) { + script.setBreakpoint(offset, actor); + } + } +} + +// exports.setBreakpointAtEntryPoints = setBreakpointAtEntryPoints; + +/** + * BreakpointActors exist for the lifetime of their containing thread and are + * responsible for deleting breakpoints, handling breakpoint hits and + * associating breakpoints with scripts. + */ +let BreakpointActor = ActorClassWithSpec(breakpointSpec, { + /** + * Create a Breakpoint actor. + * + * @param ThreadActor threadActor + * The parent thread actor that contains this breakpoint. + * @param OriginalLocation originalLocation + * The original location of the breakpoint. + */ + initialize: function (threadActor, originalLocation) { + // The set of Debugger.Script instances that this breakpoint has been set + // upon. + this.scripts = new Set(); + + this.threadActor = threadActor; + this.originalLocation = originalLocation; + this.condition = null; + this.isPending = true; + }, + + disconnect: function () { + this.removeScripts(); + }, + + hasScript: function (script) { + return this.scripts.has(script); + }, + + /** + * Called when this same breakpoint is added to another Debugger.Script + * instance. + * + * @param script Debugger.Script + * The new source script on which the breakpoint has been set. + */ + addScript: function (script) { + this.scripts.add(script); + this.isPending = false; + }, + + /** + * Remove the breakpoints from associated scripts and clear the script cache. + */ + removeScripts: function () { + for (let script of this.scripts) { + script.clearBreakpoint(this); + } + this.scripts.clear(); + }, + + /** + * Check if this breakpoint has a condition that doesn't error and + * evaluates to true in frame. + * + * @param frame Debugger.Frame + * The frame to evaluate the condition in + * @returns Object + * - result: boolean|undefined + * True when the conditional breakpoint should trigger a pause, + * false otherwise. If the condition evaluation failed/killed, + * `result` will be `undefined`. + * - message: string + * If the condition throws, this is the thrown message. + */ + checkCondition: function (frame) { + let completion = frame.eval(this.condition); + if (completion) { + if (completion.throw) { + // The evaluation failed and threw + let message = "Unknown exception"; + try { + if (completion.throw.getOwnPropertyDescriptor) { + message = completion.throw.getOwnPropertyDescriptor("message") + .value; + } else if (completion.toString) { + message = completion.toString(); + } + } catch (ex) {} + return { + result: true, + message: message + }; + } else if (completion.yield) { + assert(false, "Shouldn't ever get yield completions from an eval"); + } else { + return { result: completion.return ? true : false }; + } + } else { + // The evaluation was killed (possibly by the slow script dialog) + return { result: undefined }; + } + }, + + /** + * A function that the engine calls when a breakpoint has been hit. + * + * @param frame Debugger.Frame + * The stack frame that contained the breakpoint. + */ + hit: function (frame) { + // Don't pause if we are currently stepping (in or over) or the frame is + // black-boxed. + let generatedLocation = this.threadActor.sources.getFrameLocation(frame); + let { originalSourceActor } = this.threadActor.unsafeSynchronize( + this.threadActor.sources.getOriginalLocation(generatedLocation)); + let url = originalSourceActor.url; + + if (this.threadActor.sources.isBlackBoxed(url) + || frame.onStep) { + return undefined; + } + + let reason = {}; + + if (this.threadActor._hiddenBreakpoints.has(this.actorID)) { + reason.type = "pauseOnDOMEvents"; + } else if (!this.condition) { + reason.type = "breakpoint"; + // TODO: add the rest of the breakpoints on that line (bug 676602). + reason.actors = [ this.actorID ]; + } else { + let { result, message } = this.checkCondition(frame); + + if (result) { + if (!message) { + reason.type = "breakpoint"; + } else { + reason.type = "breakpointConditionThrown"; + reason.message = message; + } + reason.actors = [ this.actorID ]; + } else { + return undefined; + } + } + return this.threadActor._pauseAndRespond(frame, reason); + }, + + /** + * Handle a protocol request to remove this breakpoint. + */ + delete: function () { + // Remove from the breakpoint store. + if (this.originalLocation) { + this.threadActor.breakpointActorMap.deleteActor(this.originalLocation); + } + this.threadActor.threadLifetimePool.removeActor(this); + // Remove the actual breakpoint from the associated scripts. + this.removeScripts(); + } +}); + +// exports.BreakpointActor = BreakpointActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/common.js b/native/cocos/scripting/js-bindings/script/debugger/actors/common.js index fb5a52fb00..b5312bbd8d 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/common.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/common.js @@ -478,7 +478,7 @@ function expectState(expectedState, method, activity) { const msg = `Wrong state while ${activity}:` + `Expected '${expectedState}', ` + `but current state is '${this.state}'.`; - return promise.reject(new Error(msg)); + return Promise.reject(new Error(msg)); } return method.apply(this, args); diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/object.js b/native/cocos/scripting/js-bindings/script/debugger/actors/object.js index f3b77628a5..a7085082d1 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/object.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/object.js @@ -75,7 +75,7 @@ ObjectActor.prototype = { /** * Returns a grip for this actor for returning in a protocol message. */ - grip: function() { + grip: function () { this.hooks.incrementGripDepth(); let g = { diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/script.js b/native/cocos/scripting/js-bindings/script/debugger/actors/script.js index 6acfd08b9a..c9fa8b6fff 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/script.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/script.js @@ -192,7 +192,7 @@ BreakpointActorMap.prototype = { } }; -exports.BreakpointActorMap = BreakpointActorMap; +// exports.BreakpointActorMap = BreakpointActorMap; /** * Keeps track of persistent sources across reloads and ties different @@ -241,7 +241,7 @@ SourceActorStore.prototype = { } }; -exports.SourceActorStore = SourceActorStore; +// exports.SourceActorStore = SourceActorStore; /** * Manages pushing event loops and automatically pops and exits them in the @@ -412,8 +412,7 @@ EventLoop.prototype = { * An optional (for content debugging only) reference to the content * window. */ -const ThreadActor = ActorClassWithSpec(threadSpec, { - initialize: function (aParent, aGlobal) { +function ThreadActor (aParent, aGlobal) { this._state = "detached"; this._frameActors = []; this._parent = aParent; @@ -449,12 +448,14 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { this.objectGrip = this.objectGrip.bind(this); this.pauseObjectGrip = this.pauseObjectGrip.bind(this); this._onWindowReady = this._onWindowReady.bind(this); - events.on(this._parent, "window-ready", this._onWindowReady); + // events.on(this._parent, "window-ready", this._onWindowReady); // Set a wrappedJSObject property so |this| can be sent via the observer svc // for the xpcshell harness. this.wrappedJSObject = this; - }, +}; +ThreadActor.prototype = { + constructor: ThreadActor, // Used by the ObjectActor to keep track of the depth of grip() calls. _gripDepth: null, @@ -497,6 +498,14 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { return this._threadLifetimePool; }, + get scripts() { + if (!this._scripts) { + this._scripts = new ScriptStore(); + this._scripts.addScripts(this.dbg.findScripts()); + } + return this._scripts; + }, + get sources() { return this._parent.sources; }, @@ -514,7 +523,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { this._prettyPrintWorker = new DevToolsWorker( "resource://devtools/server/actors/pretty-print-worker.js", { name: "pretty-print", - verbose: flags.wantLogging } + verbose: dumpn.wantLogging } ); } return this._prettyPrintWorker; @@ -681,7 +690,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { Object.assign(this._options, options); // Update the global source store - this.sources.setOptions(options); +// this.sources.setOptions(options); return {}; }, @@ -728,7 +737,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { line: originalLocation.originalLine, column: originalLocation.originalColumn }; - resolve(onPacket(packet)) + Promise.resolve(onPacket(packet)) .then(null, error => { reportError(error); return { @@ -1004,13 +1013,12 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { lastPausedUrl: this._nestedEventLoops.lastPausedUrl }; } - let resumeLimitHandled; if (aRequest && aRequest.resumeLimit) { resumeLimitHandled = this._handleResumeLimit(aRequest); } else { this._clearSteppingHooks(this.youngestFrame); - resumeLimitHandled = resolve(true); + resumeLimitHandled = Promise.resolve(true); } return resumeLimitHandled.then(() => { @@ -1280,7 +1288,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { promises.push(promise); } - return all(promises).then(function (frames) { + return Promise.all(promises).then(function (frames) { // Filter null values because sourcemapping may have failed. return { frames: frames.filter(x => !!x) }; }); @@ -1322,7 +1330,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { } } - return all([...sourcesToScripts.values()].map(script => { + return Promise.all([...sourcesToScripts.values()].map(script => { return this.sources.createSourceActors(script.source); })); }, @@ -1848,9 +1856,9 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { // NS_ERROR_NO_INTERFACE exceptions are a special case in browser code, // since they're almost always thrown by QueryInterface functions, and // handled cleanly by native code. - if (aValue == Cr.NS_ERROR_NO_INTERFACE) { - return undefined; - } +// if (aValue == Cr.NS_ERROR_NO_INTERFACE) { +// return undefined; +// } const generatedLocation = this.sources.getFrameLocation(aFrame); const { originalSourceActor } = this.unsafeSynchronize(this.sources.getOriginalLocation( @@ -1971,7 +1979,7 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { } if (promises.length > 0) { - this.unsafeSynchronize(promise.all(promises)); + this.unsafeSynchronize(Promise.all(promises)); } } else { // Bug 1225160: If addSource is called in response to a new script @@ -2028,9 +2036,9 @@ const ThreadActor = ActorClassWithSpec(threadSpec, { return { from: this.actorID, actors: result }; } -}); +}; -ThreadActor.prototype.requestTypes = object.merge(ThreadActor.prototype.requestTypes, { +ThreadActor.prototype.requestTypes = { "attach": ThreadActor.prototype.onAttach, "detach": ThreadActor.prototype.onDetach, "reconfigure": ThreadActor.prototype.onReconfigure, @@ -2043,9 +2051,9 @@ ThreadActor.prototype.requestTypes = object.merge(ThreadActor.prototype.requestT "sources": ThreadActor.prototype.onSources, "threadGrips": ThreadActor.prototype.onThreadGrips, "prototypesAndProperties": ThreadActor.prototype.onPrototypesAndProperties -}); +}; -exports.ThreadActor = ThreadActor; +// exports.ThreadActor = ThreadActor; /** * Creates a PauseActor. @@ -2262,7 +2270,7 @@ Object.assign(ChromeDebuggerActor.prototype, { actorPrefix: "chromeDebugger" }); -exports.ChromeDebuggerActor = ChromeDebuggerActor; +// exports.ChromeDebuggerActor = ChromeDebuggerActor; /** * Creates an actor for handling add-on debugging. AddonThreadActor is @@ -2290,7 +2298,7 @@ Object.assign(AddonThreadActor.prototype, { actorPrefix: "addonThread" }); -exports.AddonThreadActor = AddonThreadActor; +// exports.AddonThreadActor = AddonThreadActor; // Utility functions. @@ -2305,7 +2313,7 @@ exports.AddonThreadActor = AddonThreadActor; // var oldReportError = reportError; function reportError(aError, aPrefix="") { // assert(aError instanceof Error, "Must pass Error objects to reportError"); - let msg = aPrefix + aError.message + ":\n" + aError.stack; + let msg = "" + aPrefix + aError.message + ":\n" + aError.stack; // oldReportError(msg); log(msg); } @@ -2345,7 +2353,7 @@ function findEntryPointsForLine(scripts, line) { * Returns the unwrapped global object or |undefined| if unwrapping * failed. */ -exports.unwrapDebuggerObjectGlobal = wrappedGlobal => { +var unwrapDebuggerObjectGlobal = wrappedGlobal => { try { // Because of bug 991399 we sometimes get nuked window references here. We // just bail out in that case. diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/source.js b/native/cocos/scripting/js-bindings/script/debugger/actors/source.js new file mode 100644 index 0000000000..f2d2db1fed --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/source.js @@ -0,0 +1,937 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +// const { Cc, Ci } = require("chrome"); +// const Services = require("Services"); +// const { BreakpointActor, setBreakpointAtEntryPoints } = require("devtools/server/actors/breakpoint"); +// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common"); +// const { createValueGrip } = require("devtools/server/actors/object"); +// const { ActorClassWithSpec, Arg, RetVal, method } = require("devtools/shared/protocol"); +// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); +// const { assert, fetch } = DevToolsUtils; +// const { joinURI } = require("devtools/shared/path"); +// const promise = require("promise"); +// const { defer, resolve, reject, all } = promise; +// const { sourceSpec } = require("devtools/shared/specs/source"); + +// loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true); +// loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true); +// loader.lazyRequireGetter(this, "mapURIToAddonID", "devtools/server/actors/utils/map-uri-to-addon-id"); + +// from "devtools/shared/specs/source" +const sourceSpec = generateActorSpec({ + typeName: "source", + + methods: { + getExecutableLines: { response: { lines: RetVal("json") } }, + onSource: { + request: { type: "source" }, + response: RetVal("json") + }, + prettyPrint: { + request: { indent: Arg(0, "number") }, + response: RetVal("json") + }, + disablePrettyPrint: { + response: RetVal("json") + }, + blackbox: { response: { pausedInSource: RetVal("boolean") } }, + unblackbox: {}, + setBreakpoint: { + request: { + location: { + line: Arg(0, "number"), + column: Arg(1, "nullable:number") + }, + condition: Arg(2, "nullable:string"), + noSliding: Arg(3, "nullable:boolean") + }, + response: RetVal("json") + }, + }, +}); + +// --------------- + +function isEvalSource(source) { + let introType = source.introductionType; + // These are all the sources that are essentially eval-ed (either + // by calling eval or passing a string to one of these functions). + return (introType === "eval" || + introType === "Function" || + introType === "eventHandler" || + introType === "setTimeout" || + introType === "setInterval"); +} + +// exports.isEvalSource = isEvalSource; + +function getSourceURL(source, window) { + if (isEvalSource(source)) { + // Eval sources have no urls, but they might have a `displayURL` + // created with the sourceURL pragma. If the introduction script + // is a non-eval script, generate an full absolute URL relative to it. + + if (source.displayURL && source.introductionScript && + !isEvalSource(source.introductionScript.source)) { + + if (source.introductionScript.source.url === "debugger eval code") { + if (window) { + // If this is a named eval script created from the console, make it + // relative to the current page. window is only available + // when we care about this. + return joinURI(window.location.href, source.displayURL); + } + } + else { + return joinURI(source.introductionScript.source.url, source.displayURL); + } + } + + return source.displayURL; + } + else if (source.url === "debugger eval code") { + // Treat code evaluated by the console as unnamed eval scripts + return null; + } + return source.url; +} + +// exports.getSourceURL = getSourceURL; + +/** + * Resolve a URI back to physical file. + * + * Of course, this works only for URIs pointing to local resources. + * + * @param aURI + * URI to resolve + * @return + * resolved nsIURI + */ +function resolveURIToLocalPath(aURI) { + let resolved; + switch (aURI.scheme) { + case "jar": + case "file": + return aURI; + + case "chrome": + resolved = Cc["@mozilla.org/chrome/chrome-registry;1"]. + getService(Ci.nsIChromeRegistry).convertChromeURL(aURI); + return resolveURIToLocalPath(resolved); + + case "resource": + resolved = Cc["@mozilla.org/network/protocol;1?name=resource"]. + getService(Ci.nsIResProtocolHandler).resolveURI(aURI); + aURI = Services.io.newURI(resolved, null, null); + return resolveURIToLocalPath(aURI); + + default: + return null; + } +} + +/** + * A SourceActor provides information about the source of a script. There + * are two kinds of source actors: ones that represent real source objects, + * and ones that represent non-existant "original" sources when the real + * sources are sourcemapped. When a source is sourcemapped, actors are + * created for both the "generated" and "original" sources, and the client will + * only see the original sources. We separate these because there isn't + * a 1:1 mapping of generated to original sources; one generated source + * may represent N original sources, so we need to create N + 1 separate + * actors. + * + * There are 4 different scenarios for sources that you should + * understand: + * + * - A single non-sourcemapped source that is not inlined in HTML + * (separate JS file, eval'ed code, etc) + * - A single sourcemapped source which creates N original sources + * - An HTML page with multiple inline scripts, which are distinct + * sources, but should be represented as a single source + * - A pretty-printed source (which may or may not be an original + * sourcemapped source), which generates a sourcemap for itself + * + * The complexity of `SourceActor` and `ThreadSources` are to handle + * all of thise cases and hopefully internalize the complexities. + * + * @param Debugger.Source source + * The source object we are representing. + * @param ThreadActor thread + * The current thread actor. + * @param String originalUrl + * Optional. For sourcemapped urls, the original url this is representing. + * @param Debugger.Source generatedSource + * Optional, passed in when aSourceMap is also passed in. The generated + * source object that introduced this source. + * @param Boolean isInlineSource + * Optional. True if this is an inline source from a HTML or XUL page. + * @param String contentType + * Optional. The content type of this source, if immediately available. + */ +let SourceActor = ActorClassWithSpec(sourceSpec, { + typeName: "source", + + initialize: function ({ source, thread, originalUrl, generatedSource, + isInlineSource, contentType }) { + this._threadActor = thread; + this._originalUrl = originalUrl; + this._source = source; + this._generatedSource = generatedSource; + this._contentType = contentType; + this._isInlineSource = isInlineSource; + + this.onSource = this.onSource.bind(this); + this._invertSourceMap = this._invertSourceMap.bind(this); + this._encodeAndSetSourceMapURL = this._encodeAndSetSourceMapURL.bind(this); + this._getSourceText = this._getSourceText.bind(this); + + this._mapSourceToAddon(); + + if (this.threadActor.sources.isPrettyPrinted(this.url)) { + this._init = this.prettyPrint( + this.threadActor.sources.prettyPrintIndent(this.url) + ).then(null, error => { + DevToolsUtils.reportException("SourceActor", error); + }); + } else { + this._init = null; + } + }, + + get isSourceMapped() { + return !!(!this.isInlineSource && ( + this._originalURL || this._generatedSource || + this.threadActor.sources.isPrettyPrinted(this.url) + )); + }, + + get isInlineSource() { + return this._isInlineSource; + }, + + get threadActor() { return this._threadActor; }, + get sources() { return this._threadActor.sources; }, + get dbg() { return this.threadActor.dbg; }, + get source() { return this._source; }, + get generatedSource() { return this._generatedSource; }, + get breakpointActorMap() { return this.threadActor.breakpointActorMap; }, + get url() { + if (this.source) { + return getSourceURL(this.source, this.threadActor._parent.window); + } + return this._originalUrl; + }, + get addonID() { return this._addonID; }, + get addonPath() { return this._addonPath; }, + + get prettyPrintWorker() { + return this.threadActor.prettyPrintWorker; + }, + + form: function () { + let source = this.source || this.generatedSource; + // This might not have a source or a generatedSource because we + // treat HTML pages with inline scripts as a special SourceActor + // that doesn't have either + let introductionUrl = null; + if (source && source.introductionScript) { + introductionUrl = source.introductionScript.source.url; + } + + return { + actor: this.actorID, + generatedUrl: this.generatedSource ? this.generatedSource.url : null, + url: this.url ? this.url.split(" -> ").pop() : null, + addonID: this._addonID, + addonPath: this._addonPath, + isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url), + isPrettyPrinted: this.threadActor.sources.isPrettyPrinted(this.url), + isSourceMapped: this.isSourceMapped, + sourceMapURL: source ? source.sourceMapURL : null, + introductionUrl: introductionUrl ? introductionUrl.split(" -> ").pop() : null, + introductionType: source ? source.introductionType : null + }; + }, + + disconnect: function () { + if (this.registeredPool && this.registeredPool.sourceActors) { + delete this.registeredPool.sourceActors[this.actorID]; + } + }, + + _mapSourceToAddon: function () { + try { + var nsuri = Services.io.newURI(this.url.split(" -> ").pop(), null, null); + } + catch (e) { + // We can't do anything with an invalid URI + return; + } + + let localURI = resolveURIToLocalPath(nsuri); + if (!localURI) { + return; + } + + let id = mapURIToAddonID(localURI); + if (!id) { + return; + } + this._addonID = id; + + if (localURI instanceof Ci.nsIJARURI) { + // The path in the add-on is easy for jar: uris + this._addonPath = localURI.JAREntry; + } + else if (localURI instanceof Ci.nsIFileURL) { + // For file: uris walk up to find the last directory that is part of the + // add-on + let target = localURI.file; + let path = target.leafName; + + // We can assume that the directory containing the source file is part + // of the add-on + let root = target.parent; + let file = root.parent; + while (file && mapURIToAddonID(Services.io.newFileURI(file))) { + path = root.leafName + "/" + path; + root = file; + file = file.parent; + } + + if (!file) { + const error = new Error("Could not find the root of the add-on for " + this.url); + DevToolsUtils.reportException("SourceActor.prototype._mapSourceToAddon", error); + return; + } + + this._addonPath = path; + } + }, + + _reportLoadSourceError: function (error, map = null) { + try { + DevToolsUtils.reportException("SourceActor", error); + + JSON.stringify(this.form(), null, 4).split(/\n/g) + .forEach(line => console.error("\t", line)); + + if (!map) { + return; + } + + console.error("\t", "source map's sourceRoot =", map.sourceRoot); + + console.error("\t", "source map's sources ="); + map.sources.forEach(s => { + let hasSourceContent = map.sourceContentFor(s, true); + console.error("\t\t", s, "\t", + hasSourceContent ? "has source content" : "no source content"); + }); + + console.error("\t", "source map's sourcesContent ="); + map.sourcesContent.forEach(c => { + if (c.length > 80) { + c = c.slice(0, 77) + "..."; + } + c = c.replace(/\n/g, "\\n"); + console.error("\t\t", c); + }); + } catch (e) { } + }, + + _getSourceText: function () { + let toResolvedContent = t => ({ + content: t, + contentType: this._contentType + }); + + let genSource = this.generatedSource || this.source; + return this.threadActor.sources.fetchSourceMap(genSource).then(map => { + if (map) { + try { + let sourceContent = map.sourceContentFor(this.url); + if (sourceContent) { + return toResolvedContent(sourceContent); + } + } catch (error) { + this._reportLoadSourceError(error, map); + throw error; + } + } + + // Use `source.text` if it exists, is not the "no source" string, and + // the content type of the source is JavaScript or it is synthesized + // wasm. It will be "no source" if the Debugger API wasn't able to load + // the source because sources were discarded + // (javascript.options.discardSystemSource == true). Re-fetch non-JS + // sources to get the contentType from the headers. + if (this.source && + this.source.text !== "[no source]" && + this._contentType && + (this._contentType.indexOf("javascript") !== -1 || + this._contentType === "text/wasm")) { + return toResolvedContent(this.source.text); + } + else { + // Only load the HTML page source from cache (which exists when + // there are inline sources). Otherwise, we can't trust the + // cache because we are most likely here because we are + // fetching the original text for sourcemapped code, and the + // page hasn't requested it before (if it has, it was a + // previous debugging session). + let loadFromCache = this.isInlineSource; + + // Fetch the sources with the same principal as the original document + let win = this.threadActor._parent.window; + let principal, cacheKey; + // On xpcshell, we don't have a window but a Sandbox + if (!isWorker && win instanceof Ci.nsIDOMWindow) { + let webNav = win.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation); + let channel = webNav.currentDocumentChannel; + principal = channel.loadInfo.loadingPrincipal; + + // Retrieve the cacheKey in order to load POST requests from cache + // Note that chrome:// URLs don't support this interface. + if (loadFromCache && + webNav.currentDocumentChannel instanceof Ci.nsICacheInfoChannel) { + cacheKey = webNav.currentDocumentChannel.cacheKey; + assert( + cacheKey, + "Could not fetch the cacheKey from the related document." + ); + } + } + + let sourceFetched = fetch(this.url, { + principal, + cacheKey, + loadFromCache + }); + + // Record the contentType we just learned during fetching + return sourceFetched + .then(result => { + this._contentType = result.contentType; + return result; + }, error => { + this._reportLoadSourceError(error, map); + throw error; + }); + } + }); + }, + + /** + * Get all executable lines from the current source + * @return Array - Executable lines of the current script + **/ + getExecutableLines: function () { + function sortLines(lines) { + // Converting the Set into an array + lines = [...lines]; + lines.sort((a, b) => { + return a - b; + }); + return lines; + } + + if (this.generatedSource) { + return this.threadActor.sources.getSourceMap(this.generatedSource).then(sm => { + let lines = new Set(); + + // Position of executable lines in the generated source + let offsets = this.getExecutableOffsets(this.generatedSource, false); + for (let offset of offsets) { + let {line, source: sourceUrl} = sm.originalPositionFor({ + line: offset.lineNumber, + column: offset.columnNumber + }); + + if (sourceUrl === this.url) { + lines.add(line); + } + } + + return sortLines(lines); + }); + } + + let lines = this.getExecutableOffsets(this.source, true); + return sortLines(lines); + }, + + /** + * Extract all executable offsets from the given script + * @param String url - extract offsets of the script with this url + * @param Boolean onlyLine - will return only the line number + * @return Set - Executable offsets/lines of the script + **/ + getExecutableOffsets: function (source, onlyLine) { + let offsets = new Set(); + for (let s of this.dbg.findScripts({ source })) { + for (let offset of s.getAllColumnOffsets()) { + offsets.add(onlyLine ? offset.lineNumber : offset); + } + } + + return offsets; + }, + + /** + * Handler for the "source" packet. + */ + onSource: function () { + return Promise.resolve(this._init) + .then(this._getSourceText) + .then(({ content, contentType }) => { + return { + source: createValueGrip(content, this.threadActor.threadLifetimePool, + this.threadActor.objectGrip), + contentType: contentType + }; + }) + .then(null, aError => { + reportError(aError, "Got an exception during SA_onSource: "); + throw new Error("Could not load the source for " + this.url + ".\n" + + DevToolsUtils.safeErrorString(aError)); + }); + }, + + /** + * Handler for the "prettyPrint" packet. + */ + prettyPrint: function (indent) { + this.threadActor.sources.prettyPrint(this.url, indent); + return this._getSourceText() + .then(this._sendToPrettyPrintWorker(indent)) + .then(this._invertSourceMap) + .then(this._encodeAndSetSourceMapURL) + .then(() => { + // We need to reset `_init` now because we have already done the work of + // pretty printing, and don't want onSource to wait forever for + // initialization to complete. + this._init = null; + }) + .then(this.onSource) + .then(null, error => { + this.disablePrettyPrint(); + throw new Error(DevToolsUtils.safeErrorString(error)); + }); + }, + + /** + * Return a function that sends a request to the pretty print worker, waits on + * the worker's response, and then returns the pretty printed code. + * + * @param Number aIndent + * The number of spaces to indent by the code by, when we send the + * request to the pretty print worker. + * @returns Function + * Returns a function which takes an AST, and returns a promise that + * is resolved with `{ code, mappings }` where `code` is the pretty + * printed code, and `mappings` is an array of source mappings. + */ + _sendToPrettyPrintWorker: function (aIndent) { + return ({ content }) => { + return this.prettyPrintWorker.performTask("pretty-print", { + url: this.url, + indent: aIndent, + source: content + }); + }; + }, + + /** + * Invert a source map. So if a source map maps from a to b, return a new + * source map from b to a. We need to do this because the source map we get + * from _generatePrettyCodeAndMap goes the opposite way we want it to for + * debugging. + * + * Note that the source map is modified in place. + */ + _invertSourceMap: function ({ code, mappings }) { + const generator = new SourceMapGenerator({ file: this.url }); + return DevToolsUtils.yieldingEach(mappings._array, m => { + let mapping = { + generated: { + line: m.originalLine, + column: m.originalColumn + } + }; + if (m.source) { + mapping.source = m.source; + mapping.original = { + line: m.generatedLine, + column: m.generatedColumn + }; + mapping.name = m.name; + } + generator.addMapping(mapping); + }).then(() => { + generator.setSourceContent(this.url, code); + let consumer = SourceMapConsumer.fromSourceMap(generator); + + return { + code: code, + map: consumer + }; + }); + }, + + /** + * Save the source map back to our thread's ThreadSources object so that + * stepping, breakpoints, debugger statements, etc can use it. If we are + * pretty printing a source mapped source, we need to compose the existing + * source map with our new one. + */ + _encodeAndSetSourceMapURL: function ({ map: sm }) { + let source = this.generatedSource || this.source; + let sources = this.threadActor.sources; + + return sources.getSourceMap(source).then(prevMap => { + if (prevMap) { + // Compose the source maps + this._oldSourceMapping = { + url: source.sourceMapURL, + map: prevMap + }; + + prevMap = SourceMapGenerator.fromSourceMap(prevMap); + prevMap.applySourceMap(sm, this.url); + sm = SourceMapConsumer.fromSourceMap(prevMap); + } + + let sources = this.threadActor.sources; + sources.clearSourceMapCache(source.sourceMapURL); + sources.setSourceMapHard(source, null, sm); + }); + }, + + /** + * Handler for the "disablePrettyPrint" packet. + */ + disablePrettyPrint: function () { + let source = this.generatedSource || this.source; + let sources = this.threadActor.sources; + let sm = sources.getSourceMap(source); + + sources.clearSourceMapCache(source.sourceMapURL, { hard: true }); + + if (this._oldSourceMapping) { + sources.setSourceMapHard(source, + this._oldSourceMapping.url, + this._oldSourceMapping.map); + this._oldSourceMapping = null; + } + + this.threadActor.sources.disablePrettyPrint(this.url); + return this.onSource(); + }, + + /** + * Handler for the "blackbox" packet. + */ + blackbox: function () { + this.threadActor.sources.blackBox(this.url); + if (this.threadActor.state == "paused" + && this.threadActor.youngestFrame + && this.threadActor.youngestFrame.script.url == this.url) { + return true; + } + return false; + }, + + /** + * Handler for the "unblackbox" packet. + */ + unblackbox: function () { + this.threadActor.sources.unblackBox(this.url); + }, + + /** + * Handle a request to set a breakpoint. + * + * @param Number line + * Line to break on. + * @param Number column + * Column to break on. + * @param String condition + * A condition which must be true for breakpoint to be hit. + * @param Boolean noSliding + * If true, disables breakpoint sliding. + * + * @returns Promise + * A promise that resolves to a JSON object representing the + * response. + */ + setBreakpoint: function (line, column, condition, noSliding) { + if (this.threadActor.state !== "paused") { + throw { + error: "wrongState", + message: "Cannot set breakpoint while debuggee is running." + }; + } + + let location = new OriginalLocation(this, line, column); + return this._getOrCreateBreakpointActor( + location, + condition, + noSliding + ).then((actor) => { + let response = { + actor: actor.actorID, + isPending: actor.isPending + }; + + let actualLocation = actor.originalLocation; + if (!actualLocation.equals(location)) { + response.actualLocation = actualLocation.toJSON(); + } + + return response; + }); + }, + + /** + * Get or create a BreakpointActor for the given location in the original + * source, and ensure it is set as a breakpoint handler on all scripts that + * match the given location. + * + * @param OriginalLocation originalLocation + * An OriginalLocation representing the location of the breakpoint in + * the original source. + * @param String condition + * A string that is evaluated whenever the breakpoint is hit. If the + * string evaluates to false, the breakpoint is ignored. + * @param Boolean noSliding + * If true, disables breakpoint sliding. + * + * @returns BreakpointActor + * A BreakpointActor representing the breakpoint. + */ + _getOrCreateBreakpointActor: function (originalLocation, condition, noSliding) { + let actor = this.breakpointActorMap.getActor(originalLocation); + if (!actor) { + actor = new BreakpointActor(this.threadActor, originalLocation); + this.threadActor.threadLifetimePool.addActor(actor); + this.breakpointActorMap.setActor(originalLocation, actor); + } + + actor.condition = condition; + + return this._setBreakpoint(actor, noSliding); + }, + + /* + * Ensure the given BreakpointActor is set as a breakpoint handler on all + * scripts that match its location in the original source. + * + * If there are no scripts that match the location of the BreakpointActor, + * we slide its location to the next closest line (for line breakpoints) or + * column (for column breakpoint) that does. + * + * If breakpoint sliding fails, then either there are no scripts that contain + * any code for the given location, or they were all garbage collected before + * the debugger started running. We cannot distinguish between these two + * cases, so we insert the BreakpointActor in the BreakpointActorMap as + * a pending breakpoint. Whenever a new script is introduced, this method is + * called again for each pending breakpoint. + * + * @param BreakpointActor actor + * The BreakpointActor to be set as a breakpoint handler. + * @param Boolean noSliding + * If true, disables breakpoint sliding. + * + * @returns A Promise that resolves to the given BreakpointActor. + */ + _setBreakpoint: function (actor, noSliding) { + const { originalLocation } = actor; + const { originalLine, originalSourceActor } = originalLocation; + + if (!this.isSourceMapped) { + const generatedLocation = GeneratedLocation.fromOriginalLocation(originalLocation); + if (!this._setBreakpointAtGeneratedLocation(actor, generatedLocation) && + !noSliding) { + const query = { line: originalLine }; + // For most cases, we have a real source to query for. The + // only time we don't is for HTML pages. In that case we want + // to query for scripts in an HTML page based on its URL, as + // there could be several sources within an HTML page. + if (this.source) { + query.source = this.source; + } else { + query.url = this.url; + } + const scripts = this.dbg.findScripts(query); + + // Never do breakpoint sliding for column breakpoints. + // Additionally, never do breakpoint sliding if no scripts + // exist on this line. + // + // Sliding can go horribly wrong if we always try to find the + // next line with valid entry points in the entire file. + // Scripts may be completely GCed and we never knew they + // existed, so we end up sliding through whole functions to + // the user's bewilderment. + // + // We can slide reliably if any scripts exist, however, due + // to how scripts are kept alive. A parent Debugger.Script + // keeps all of its children alive, so as long as we have a + // valid script, we can slide through it and know we won't + // slide through any of its child scripts. Additionally, if a + // script gets GCed, that means that all parents scripts are + // GCed as well, and no scripts will exist on those lines + // anymore. We will never slide through a GCed script. + if (originalLocation.originalColumn || scripts.length === 0) { + return Promise.resolve(actor); + } + + // Find the script that spans the largest amount of code to + // determine the bounds for sliding. + const largestScript = scripts.reduce((largestScript, script) => { + if (script.lineCount > largestScript.lineCount) { + return script; + } + return largestScript; + }); + const maxLine = largestScript.startLine + largestScript.lineCount - 1; + + let actualLine = originalLine; + for (; actualLine <= maxLine; actualLine++) { + const loc = new GeneratedLocation(this, actualLine); + if (this._setBreakpointAtGeneratedLocation(actor, loc)) { + break; + } + } + + // The above loop should never complete. We only did breakpoint sliding + // because we found scripts on the line we started from, + // which means there must be valid entry points somewhere + // within those scripts. + assert( + actualLine <= maxLine, + "Could not find any entry points to set a breakpoint on, " + + "even though I was told a script existed on the line I started " + + "the search with." + ); + + // Update the actor to use the new location (reusing a + // previous breakpoint if it already exists on that line). + const actualLocation = new OriginalLocation(originalSourceActor, actualLine); + const existingActor = this.breakpointActorMap.getActor(actualLocation); + this.breakpointActorMap.deleteActor(originalLocation); + if (existingActor) { + actor.delete(); + actor = existingActor; + } else { + actor.originalLocation = actualLocation; + this.breakpointActorMap.setActor(actualLocation, actor); + } + } + + return Promise.resolve(actor); + } else { + return this.sources.getAllGeneratedLocations(originalLocation).then((generatedLocations) => { + this._setBreakpointAtAllGeneratedLocations( + actor, + generatedLocations + ); + + return actor; + }); + } + }, + + _setBreakpointAtAllGeneratedLocations: function (actor, generatedLocations) { + let success = false; + for (let generatedLocation of generatedLocations) { + if (this._setBreakpointAtGeneratedLocation( + actor, + generatedLocation + )) { + success = true; + } + } + return success; + }, + + /* + * Ensure the given BreakpointActor is set as breakpoint handler on all + * scripts that match the given location in the generated source. + * + * @param BreakpointActor actor + * The BreakpointActor to be set as a breakpoint handler. + * @param GeneratedLocation generatedLocation + * A GeneratedLocation representing the location in the generated + * source for which the given BreakpointActor is to be set as a + * breakpoint handler. + * + * @returns A Boolean that is true if the BreakpointActor was set as a + * breakpoint handler on at least one script, and false otherwise. + */ + _setBreakpointAtGeneratedLocation: function (actor, generatedLocation) { + let { + generatedSourceActor, + generatedLine, + generatedColumn, + generatedLastColumn + } = generatedLocation; + + // Find all scripts that match the given source actor and line + // number. + const query = { line: generatedLine }; + if (generatedSourceActor.source) { + query.source = generatedSourceActor.source; + } else { + query.url = generatedSourceActor.url; + } + let scripts = this.dbg.findScripts(query); + + scripts = scripts.filter((script) => !actor.hasScript(script)); + + // Find all entry points that correspond to the given location. + let entryPoints = []; + if (generatedColumn === undefined) { + // This is a line breakpoint, so we are interested in all offsets + // that correspond to the given line number. + for (let script of scripts) { + let offsets = script.getLineOffsets(generatedLine); + if (offsets.length > 0) { + entryPoints.push({ script, offsets }); + } + } + } else { + // This is a column breakpoint, so we are interested in all column + // offsets that correspond to the given line *and* column number. + for (let script of scripts) { + let columnToOffsetMap = script.getAllColumnOffsets() + .filter(({ lineNumber }) => { + return lineNumber === generatedLine; + }); + for (let { columnNumber: column, offset } of columnToOffsetMap) { + if (column >= generatedColumn && column <= generatedLastColumn) { + entryPoints.push({ script, offsets: [offset] }); + } + } + } + } + + if (entryPoints.length === 0) { + return false; + } + setBreakpointAtEntryPoints(actor, entryPoints); + return true; + } +}); + +// exports.SourceActor = SourceActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js index b2352fec98..3d865a6ccc 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js @@ -5,15 +5,15 @@ "use strict"; // const { Ci, Cu } = require("chrome"); -// const Services = require("Services"); -// const DevToolsUtils = require("devtools/toolkit/DevToolsUtils"); -// const { dbg_assert, fetch } = DevToolsUtils; -// const EventEmitter = require("devtools/toolkit/event-emitter"); -// const { OriginalLocation, GeneratedLocation, getOffsetColumn } = require("devtools/server/actors/common"); +// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); +// const { assert, fetch } = DevToolsUtils.; +// const EventEmitter = require("devtools/shared/event-emitter"); +// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common"); // const { resolve } = require("promise"); +// const { joinURI } = require("devtools/shared/path"); -// loader.lazyRequireGetter(this, "SourceActor", "devtools/server/actors/script", true); -// loader.lazyRequireGetter(this, "isEvalSource", "devtools/server/actors/script", true); +// loader.lazyRequireGetter(this, "SourceActor", "devtools/server/actors/source", true); +// loader.lazyRequireGetter(this, "isEvalSource", "devtools/server/actors/source", true); // loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true); // loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true); @@ -21,7 +21,7 @@ * Manages the sources for a thread. Handles source maps, locations in the * sources, etc for ThreadActors. */ -function TabSources(threadActor, allowSourceFn=() => true) { +function TabSources(threadActor, allowSourceFn = () => true) { EventEmitter.decorate(this); this._thread = threadActor; @@ -30,10 +30,11 @@ function TabSources(threadActor, allowSourceFn=() => true) { this._anonSourceMapId = 1; this.allowSource = source => { return !isHiddenSource(source) && allowSourceFn(source); - } + }; this.blackBoxedSources = new Set(); this.prettyPrintedSources = new Map(); + this.neverAutoBlackBoxSources = new Set(); // generated Debugger.Source -> promise of SourceMapConsumer this._sourceMaps = new Map(); @@ -67,6 +68,27 @@ TabSources.prototype = { this.reset(); }, + + /** + * Update preferences and clear out existing sources + */ + setOptions: function (options) { + let shouldReset = false; + + if ("useSourceMaps" in options) { + shouldReset = true; + this._useSourceMaps = options.useSourceMaps; + } + + if ("autoBlackBox" in options) { + shouldReset = true; + this._autoBlackBox = options.autoBlackBox; + } + + if (shouldReset) { + this.reset(); + } + }, /** * Clear existing sources so they are recreated on the next access. @@ -75,7 +97,7 @@ TabSources.prototype = { * Specify { sourceMaps: true } if you also want to clear * the source map cache (usually done on reload). */ - reset: function(opts={}) { + reset: function (opts = {}) { this._sourceActors = new Map(); this._sourceMaps = new Map(); this._sourceMappedSourceActors = Object.create(null); @@ -101,10 +123,10 @@ TabSources.prototype = { * The content type of the source, if immediately available. * @returns a SourceActor representing the source or null. */ - source: function ({ source, originalUrl, generatedSource, - isInlineSource, contentType }) { - dbg_assert(source || (originalUrl && generatedSource), - "TabSources.prototype.source needs an originalUrl or a source"); + source: function ({ source, originalUrl, generatedSource, + isInlineSource, contentType }) { + DevToolsUtils.assert(source || (originalUrl && generatedSource), + "TabSources.prototype.source needs an originalUrl or a source"); if (source) { // If a source is passed, we are creating an actor for a real @@ -163,14 +185,19 @@ TabSources.prototype = { let sourceActorStore = this._thread.sourceActorStore; var id = sourceActorStore.getReusableActorId(source, originalUrl); if (id) { + log("++++ source " + originalUrl + ": " + id); actor.actorID = id; } this._thread.threadLifetimePool.addActor(actor); sourceActorStore.setReusableActorId(source, originalUrl, actor.actorID); - if (this._autoBlackBox && this._isMinifiedURL(actor.url)) { + if (this._autoBlackBox && + !this.neverAutoBlackBoxSources.has(actor.url) && + this._isMinifiedURL(actor.url)) { + this.blackBox(actor.url); + this.neverAutoBlackBoxSources.add(actor.url); } if (source) { @@ -184,12 +211,12 @@ TabSources.prototype = { return actor; }, - _emitNewSource: function(actor) { + _emitNewSource: function (actor) { if (!actor.source) { // Always notify if we don't have a source because that means // it's something that has been sourcemapped, or it represents // the HTML file that contains inline sources. - this.emit('newSource', actor); + this.emit("newSource", actor); } else { // If sourcemapping is enabled and a source has sourcemaps, we @@ -202,13 +229,13 @@ TabSources.prototype = { // it's a generated source), don't send the notification. this.fetchSourceMap(actor.source).then(map => { if (!map) { - this.emit('newSource', actor); + this.emit("newSource", actor); } }); } }, - getSourceActor: function(source) { + getSourceActor: function (source) { if (source.url in this._sourceMappedSourceActors) { return this._sourceMappedSourceActors[source.url]; } @@ -217,11 +244,11 @@ TabSources.prototype = { return this._sourceActors.get(source); } - throw new Error('getSource: could not find source actor for ' + - (source.url || 'source')); + throw new Error("getSource: could not find source actor for " + + (source.url || "source")); }, - getSourceActorByURL: function(url) { + getSourceActorByURL: function (url) { if (url) { for (let [source, actor] of this._sourceActors) { if (source.url === url) { @@ -234,7 +261,8 @@ TabSources.prototype = { } } - throw new Error('getSourceByURL: could not find source for ' + url); + throw new Error("getSourceActorByURL: could not find source for " + url); + return null; }, /** @@ -246,10 +274,14 @@ TabSources.prototype = { * @returns Boolean */ _isMinifiedURL: function (aURL) { + if (!aURL) { + return false; + } + try { - let url = Services.io.newURI(aURL, null, null) - .QueryInterface(Ci.nsIURL); - return MINIFIED_SOURCE_REGEXP.test(url.fileName); + let url = new URL(aURL); + let pathname = url.pathname; + return MINIFIED_SOURCE_REGEXP.test(pathname.slice(pathname.lastIndexOf("/") + 1)); } catch (e) { // Not a valid URL so don't try to parse out the filename, just test the // whole thing with the minified source regexp. @@ -288,24 +320,41 @@ TabSources.prototype = { let element = aSource.element ? aSource.element.unsafeDereference() : null; if (element && (element.tagName !== "SCRIPT" || !element.hasAttribute("src"))) { spec.isInlineSource = true; + } else if (aSource.introductionType === "wasm") { + // Wasm sources are not JavaScript. Give them their own content-type. + spec.contentType = "text/wasm"; } else { if (url) { - try { - let urlInfo = Services.io.newURI(url, null, null).QueryInterface(Ci.nsIURL); - if (urlInfo.fileExtension === "xml") { - // XUL inline scripts may not correctly have the - // `source.element` property, so do a blunt check here if - // it's an xml page. - spec.isInlineSource = true; - } - else if (urlInfo.fileExtension === "js") { - spec.contentType = "text/javascript"; - } - } catch(ex) { - // There are a few special URLs that we know are JavaScript: - // inline `javascript:` and code coming from the console - if (url.indexOf("javascript:") === 0 || url === 'debugger eval code') { - spec.contentType = "text/javascript"; + // There are a few special URLs that we know are JavaScript: + // inline `javascript:` and code coming from the console + if (url.indexOf("Scratchpad/") === 0 || + url.indexOf("javascript:") === 0 || + url === "debugger eval code") { + spec.contentType = "text/javascript"; + } else { + try { + let pathname = new URL(url).pathname; + let filename = pathname.slice(pathname.lastIndexOf("/") + 1); + let index = filename.lastIndexOf("."); + let extension = index >= 0 ? filename.slice(index + 1) : ""; + if (extension === "xml") { + // XUL inline scripts may not correctly have the + // `source.element` property, so do a blunt check here if + // it's an xml page. + spec.isInlineSource = true; + } + else if (extension === "js") { + spec.contentType = "text/javascript"; + } + } catch (e) { + // This only needs to be here because URL is not yet exposed to + // workers. (BUG 1258892) + const filename = url; + const index = filename.lastIndexOf("."); + const extension = index >= 0 ? filename.slice(index + 1) : ""; + if (extension === "js") { + spec.contentType = "text/javascript"; + } } } } @@ -330,7 +379,7 @@ TabSources.prototype = { */ _createSourceMappedActors: function (aSource) { if (!this._useSourceMaps || !aSource.sourceMapURL) { - return resolve(null); + return Promise.resolve(null); } return this.fetchSourceMap(aSource) @@ -354,7 +403,7 @@ TabSources.prototype = { * The source instance to create actors for. * @param Promise of an array of source actors */ - createSourceActors: function(aSource) { + createSourceActors: function (aSource) { return this._createSourceMappedActors(aSource).then(actors => { let actor = this.createNonSourceMappedActor(aSource); return (actors || [actor]).filter(isNotNull); @@ -372,21 +421,25 @@ TabSources.prototype = { * @return Promise of a SourceMapConsumer */ fetchSourceMap: function (aSource) { - if (this._sourceMaps.has(aSource)) { + if (!this._useSourceMaps) { + return resolve(null); + } + else if (this._sourceMaps.has(aSource)) { return this._sourceMaps.get(aSource); } else if (!aSource || !aSource.sourceMapURL) { - return resolve(null); + return Promise.resolve(null); } let sourceMapURL = aSource.sourceMapURL; if (aSource.url) { - sourceMapURL = this._normalize(sourceMapURL, aSource.url); + sourceMapURL = joinURI(aSource.url, sourceMapURL); } let result = this._fetchSourceMap(sourceMapURL, aSource.url); // The promises in `_sourceMaps` must be the exact same instances - // as returned by `_fetchSourceMap` for `clearSourceMapCache` to work. + // as returned by `_fetchSourceMap` for `clearSourceMapCache` to + // work. this._sourceMaps.set(aSource, result); return result; }, @@ -396,16 +449,16 @@ TabSources.prototype = { * `aSource`. The resolved result may be null if the source does not * have a source map or source maps are disabled. */ - getSourceMap: function(aSource) { - return resolve(this._sourceMaps.get(aSource)); + getSourceMap: function (aSource) { + return Promise.resolve(this._sourceMaps.get(aSource)); }, /** * Set a SourceMapConsumer for the source map for * |aSource|. */ - setSourceMap: function(aSource, aMap) { - this._sourceMaps.set(aSource, resolve(aMap)); + setSourceMap: function (aSource, aMap) { + this._sourceMaps.set(aSource, Promise.resolve(aMap)); }, /** @@ -422,14 +475,14 @@ TabSources.prototype = { * them from aScriptURL. */ _fetchSourceMap: function (aAbsSourceMapURL, aSourceURL) { - if (!this._useSourceMaps) { - return resolve(null); - } - else if (this._sourceMapCache[aAbsSourceMapURL]) { + DevToolsUtils.assert(this._useSourceMaps, + "Cannot fetch sourcemaps if they are disabled"); + + if (this._sourceMapCache[aAbsSourceMapURL]) { return this._sourceMapCache[aAbsSourceMapURL]; } - let fetching = fetch(aAbsSourceMapURL, { loadFromCache: false }) + let fetching = DevToolsUtils.fetch(aAbsSourceMapURL, { loadFromCache: false }) .then(({ content }) => { let map = new SourceMapConsumer(content); this._setSourceMapRoot(map, aAbsSourceMapURL, aSourceURL); @@ -460,13 +513,14 @@ TabSources.prototype = { ? aScriptURL : aAbsSourceMapURL); aSourceMap.sourceRoot = aSourceMap.sourceRoot - ? this._normalize(aSourceMap.sourceRoot, base) + ? joinURI(base, aSourceMap.sourceRoot) : base; }, _dirname: function (aPath) { - return Services.io.newURI( - ".", null, Services.io.newURI(aPath, null, null)).spec; + let url = new URL(aPath); + let href = url.href; + return href.slice(0, href.lastIndexOf("/")); }, /** @@ -484,7 +538,7 @@ TabSources.prototype = { * - hard: Also remove the lower-level URL cache, which will * make us completely forget about the source map. */ - clearSourceMapCache: function(aSourceMapURL, opts = { hard: false }) { + clearSourceMapCache: function (aSourceMapURL, opts = { hard: false }) { let oldSm = this._sourceMapCache[aSourceMapURL]; if (opts.hard) { @@ -515,7 +569,7 @@ TabSources.prototype = { * @param aMap SourceMapConsumer * The source map instance */ - setSourceMapHard: function(aSource, aUrl, aMap) { + setSourceMapHard: function (aSource, aUrl, aMap) { let url = aUrl; if (!url) { // This is a littly hacky, but we want to forcefully set a @@ -525,13 +579,14 @@ TabSources.prototype = { // instances are per-debugger, so we can't key off that). To // avoid tons of work serializing the sourcemap into a data url, // just make a fake URL and stick the sourcemap there. - url = "internal://sourcemap" + (this._anonSourceMapId++) + '/'; + url = "internal://sourcemap" + (this._anonSourceMapId++) + "/"; } aSource.sourceMapURL = url; // Forcefully set the sourcemap cache. This will be used even if // sourcemaps are disabled. - this._sourceMapCache[url] = resolve(aMap); + this._sourceMapCache[url] = Promise.resolve(aMap); + this.emit("updatedSource", this.getSourceActor(aSource)); }, /** @@ -547,11 +602,12 @@ TabSources.prototype = { if (!aFrame || !aFrame.script) { return new GeneratedLocation(); } - + let {lineNumber, columnNumber} = + aFrame.script.getOffsetLocation(aFrame.offset); return new GeneratedLocation( this.createNonSourceMappedActor(aFrame.script.source), - aFrame.script.getOffsetLine(aFrame.offset), - getOffsetColumn(aFrame.offset, aFrame.script) + lineNumber, + columnNumber ); }, @@ -618,8 +674,8 @@ TabSources.prototype = { originalColumn } = originalLocation; - let source = originalSourceActor.source || - originalSourceActor.generatedSource; + let source = (originalSourceActor.source || + originalSourceActor.generatedSource); return this.fetchSourceMap(source).then((map) => { if (map) { @@ -759,19 +815,6 @@ TabSources.prototype = { this.prettyPrintedSources.delete(aURL); }, - /** - * Normalize multiple relative paths towards the base paths on the right. - */ - _normalize: function (...aURLs) { - dbg_assert(aURLs.length > 1, "Should have more than 1 URL"); - let base = Services.io.newURI(aURLs.pop(), null, null); - let url; - while ((url = aURLs.pop())) { - base = Services.io.newURI(url, null, base); - } - return base.spec; - }, - iter: function () { let actors = Object.keys(this._sourceMappedSourceActors).map(k => { return this._sourceMappedSourceActors[k]; @@ -791,7 +834,7 @@ TabSources.prototype = { */ function isHiddenSource(aSource) { // Ignore the internal Function.prototype script - return aSource.text === '() {\n}'; + return aSource.text === "() {\n}"; } /** @@ -801,5 +844,5 @@ function isNotNull(aThing) { return aThing !== null; } -exports.TabSources = TabSources; -exports.isHiddenSource = isHiddenSource; +//exports.TabSources = TabSources; +//exports.isHiddenSource = isHiddenSource; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/webconsole.js b/native/cocos/scripting/js-bindings/script/debugger/actors/webconsole.js index abab86e934..aeec811307 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/webconsole.js +++ b/native/cocos/scripting/js-bindings/script/debugger/actors/webconsole.js @@ -557,9 +557,9 @@ WebConsoleActor.prototype = onStartListeners: function WCA_onStartListeners(aRequest) { // XXXworkers: Not handling the Console API yet for workers (Bug 1209353). - if (isWorker) { - aRequest.listeners = []; - } +// if (isWorker) { +// aRequest.listeners = []; +// } let startedListeners = []; let window = !this.parentActor.isRootActor ? this.window : null; @@ -594,7 +594,7 @@ WebConsoleActor.prototype = startedListeners.push(listener); break; case "NetworkActivity": - if (!this.networkMonitor) { + // if (!this.networkMonitor) { // Create a StackTraceCollector that's going to be shared both by the // NetworkMonitorChild (getting messages about requests from parent) and // by the NetworkMonitor that directly watches service workers requests. @@ -771,8 +771,7 @@ WebConsoleActor.prototype = } // See `window` definition. It isn't always a DOM Window. - let requestStartTime = this.window && this.window.performance ? - this.window.performance.timing.requestStart : 0; + let requestStartTime = 0; let cache = this.consoleAPIListener .getCachedMessages(!this.parentActor.isRootActor); @@ -1819,7 +1818,7 @@ WebConsoleActor.prototype.requestTypes = sendHTTPRequest: WebConsoleActor.prototype.onSendHTTPRequest }; -exports.WebConsoleActor = WebConsoleActor; +//exports.WebConsoleActor = WebConsoleActor; /** * Creates an actor for a network event. diff --git a/native/cocos/scripting/js-bindings/script/debugger/event-emitter.js b/native/cocos/scripting/js-bindings/script/debugger/event-emitter.js index 84d1031195..a1e843bb8c 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/event-emitter.js +++ b/native/cocos/scripting/js-bindings/script/debugger/event-emitter.js @@ -85,7 +85,7 @@ EventEmitter.prototype = { * that this is needed) then use listener */ once(event, listener) { - let deferred = promise.defer(); + let deferred = Promise.defer(); let handler = (_, first, ...rest) => { this.off(event, handler); @@ -150,8 +150,8 @@ EventEmitter.prototype = { } catch (ex) { // Prevent a bad listener from interfering with the others. let msg = ex + ": " + ex.stack; - console.error(msg); - dump(msg + "\n"); + log(msg); + DevToolsUtils.dumpn(msg + "\n"); } } } @@ -163,15 +163,15 @@ EventEmitter.prototype = { } let caller, func, path; - if (!isWorker) { - caller = components.stack.caller.caller; - func = caller.name; - let file = caller.filename; - if (file.includes(" -> ")) { - file = caller.filename.split(/ -> /)[1]; - } - path = file + ":" + caller.lineNumber; - } +// if (!isWorker) { +// caller = components.stack.caller.caller; +// func = caller.name; +// let file = caller.filename; +// if (file.includes(" -> ")) { +// file = caller.filename.split(/ -> /)[1]; +// } +// path = file + ":" + caller.lineNumber; +// } let argOut = "("; if (args.length === 1) { @@ -211,7 +211,7 @@ EventEmitter.prototype = { argOut += ")"; out += "emit" + argOut + " from " + func + "() -> " + path + "\n"; - dump(out); + DevToolsUtils.dumpn(out); }, }; diff --git a/native/cocos/scripting/js-bindings/script/debugger/main.js b/native/cocos/scripting/js-bindings/script/debugger/main.js index bf8e81e7c3..412ed56c36 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/main.js +++ b/native/cocos/scripting/js-bindings/script/debugger/main.js @@ -53,6 +53,8 @@ // } // }); +var isWorker = false; + // if (isWorker) { // dumpn.wantLogging = true; // dumpv.wantVerbose = true; @@ -177,7 +179,7 @@ var DebuggerServer = { /** * Initialize the debugger server. */ - init: function DS_init() { + init() { if (this.initialized) { return; } @@ -189,7 +191,7 @@ var DebuggerServer = { }, // get protocol() { - // return require("devtools/server/protocol"); + // return require("devtools/shared/protocol"); // }, get initialized() { @@ -203,7 +205,7 @@ var DebuggerServer = { * memory leaks. After this method returns, the debugger server must be * initialized again before use. */ - destroy: function DS_destroy() { + destroy() { if (!this._initialized) { return; } @@ -228,26 +230,27 @@ var DebuggerServer = { /** * Raises an exception if the server has not been properly initialized. */ - _checkInit: function DS_checkInit() { + _checkInit() { if (!this._initialized) { - throw "DebuggerServer has not been initialized."; + throw new Error("DebuggerServer has not been initialized."); } if (!this.createRootActor) { - throw "Use DebuggerServer.addActors() to add a root actor implementation."; + throw new Error("Use DebuggerServer.addActors() to add a root actor " + + "implementation."); } }, /** * Load a subscript into the debugging global. * - * @param aURL string A url that will be loaded as a subscript into the + * @param url string A url that will be loaded as a subscript into the * debugging global. The user must load at least one script * that implements a createRootActor() function to create the * server's root actor. */ - // addActors: function DS_addActors(aURL) { - // loadSubScript.call(this, aURL); + // addActors(urkl) { + // loadSubScript.call(this, url); // }, /** @@ -285,7 +288,7 @@ var DebuggerServer = { * registers a tab actor instance, if true. * A new actor will be created for each tab and each app. */ - // registerModule: function(id, options) { + // registerModule(id, options) { // if (id in gRegisteredModules) { // throw new Error("Tried to register a module twice: " + id + "\n"); // } @@ -333,14 +336,14 @@ var DebuggerServer = { /** * Returns true if a module id has been registered. */ - // isModuleRegistered: function(id) { + // isModuleRegistered(id) { // return (id in gRegisteredModules); // }, /** * Unregister a previously-loaded CommonJS module from the debugger server. */ - // unregisterModule: function(id) { + // unregisterModule(id) { // let mod = gRegisteredModules[id]; // if (!mod) { // throw new Error("Tried to unregister a module that was not previously registered."); @@ -373,7 +376,7 @@ var DebuggerServer = { * restrictPrivileges=true, to prevent exposing them on b2g parent process's * root actor. */ - // addBrowserActors: function(aWindowType = "navigator:browser", restrictPrivileges = false) { + // addBrowserActors(aWindowType = "navigator:browser", restrictPrivileges = false) { // this.chromeWindowType = aWindowType; // this.registerModule("devtools/server/actors/webbrowser"); @@ -418,7 +421,7 @@ var DebuggerServer = { /** * Install tab actors in documents loaded in content childs */ - // addChildActors: function () { + // addChildActors() { // // In case of apps being loaded in parent process, DebuggerServer is already // // initialized and browser actors are already loaded, // // but childtab.js hasn't been loaded yet. @@ -437,7 +440,7 @@ var DebuggerServer = { /** * Install tab actors. */ - // addTabActors: function() { + // addTabActors() { // this.registerModule("devtools/server/actors/webconsole", { // prefix: "console", // constructor: "WebConsoleActor", @@ -560,30 +563,35 @@ var DebuggerServer = { // constructor: "PerformanceEntriesActor", // type: { tab: true } // }); + // this.registerModule("devtools/server/actors/emulation", { + // prefix: "emulation", + // constructor: "EmulationActor", + // type: { tab: true } + // }); // }, /** * Passes a set of options to the BrowserAddonActors for the given ID. * - * @param aId string + * @param id string * The ID of the add-on to pass the options to - * @param aOptions object + * @param options object * The options. * @return a promise that will be resolved when complete. */ - // setAddonOptions: function DS_setAddonOptions(aId, aOptions) { + // setAddonOptions(id, options) { // if (!this._initialized) { - // return; + // return Promise.resolve(); // } // let promises = []; // // Pass to all connections // for (let connID of Object.getOwnPropertyNames(this._connections)) { - // promises.push(this._connections[connID].setAddonOptions(aId, aOptions)); + // promises.push(this._connections[connID].setAddonOptions(id, options)); // } - // return all(promises); + // return SyncPromise.all(promises); // }, // get listeningSockets() { @@ -596,7 +604,7 @@ var DebuggerServer = { * After calling this, set some socket options, such as the port / path to * listen on, and then call |open| on the listener. * - * See SocketListener in toolkit/devtools/security/socket.js for available + * See SocketListener in devtools/shared/security/socket.js for available * options. * * @return SocketListener @@ -605,7 +613,7 @@ var DebuggerServer = { * later time by calling |close| on the SocketListener. If remote * connections are disabled, an error is thrown. */ - // createListener: function() { + // createListener() { // if (!Services.prefs.getBoolPref("devtools.debugger.remote-enabled")) { // throw new Error("Can't create listener, remote debugging disabled"); // } @@ -617,7 +625,7 @@ var DebuggerServer = { * Add a SocketListener instance to the server's set of active * SocketListeners. This is called by a SocketListener after it is opened. */ - // _addListener: function(listener) { + // _addListener(listener) { // this._listeners.push(listener); // }, @@ -625,7 +633,7 @@ var DebuggerServer = { * Remove a SocketListener instance from the server's set of active * SocketListeners. This is called by a SocketListener after it is closed. */ - // _removeListener: function(listener) { + // _removeListener(listener) { // this._listeners = this._listeners.filter(l => l !== listener); // }, @@ -635,7 +643,7 @@ var DebuggerServer = { * @return boolean * Whether any listeners were actually closed. */ - // closeAllListeners: function() { + // closeAllListeners() { // if (!this.listeningSockets) { // return false; // } @@ -652,19 +660,19 @@ var DebuggerServer = { * transport. This connection results in straightforward calls to the onPacket * handlers of each side. * - * @param aPrefix string [optional] + * @param prefix string [optional] * If given, all actors in this connection will have names starting - * with |aPrefix + '/'|. + * with |prefix + '/'|. * @returns a client-side DebuggerTransport for communicating with * the newly-created connection. */ - // connectPipe: function DS_connectPipe(aPrefix) { + // connectPipe(prefix) { // this._checkInit(); - // let serverTransport = new LocalDebuggerTransport; + // let serverTransport = new LocalDebuggerTransport(); // let clientTransport = new LocalDebuggerTransport(serverTransport); // serverTransport.other = clientTransport; - // let connection = this._onConnection(serverTransport, aPrefix); + // let connection = this._onConnection(serverTransport, prefix); // // I'm putting this here because I trust you. // // @@ -1088,7 +1096,7 @@ var DebuggerServer = { * that all our actors have names beginning with |aForwardingPrefix + '/'|. * In particular, the root actor's name will be |aForwardingPrefix + '/root'|. */ - _onConnection: function DS_onConnection(aTransport, aForwardingPrefix, aNoRootActor) { + _onConnection(aTransport, aForwardingPrefix, aNoRootActor) { let connID; if (aForwardingPrefix) { connID = aForwardingPrefix + "/"; @@ -1117,21 +1125,22 @@ var DebuggerServer = { aTransport.ready(); // this.emit("connectionchange", "opened", conn); + return conn; }, /** * Remove the connection from the debugging server. */ - _connectionClosed: function DS_connectionClosed(aConnection) { - delete this._connections[aConnection.prefix]; - this.emit("connectionchange", "closed", aConnection); + _connectionClosed(connection) { + delete this._connections[connection.prefix]; + this.emit("connectionchange", "closed", connection); }, // DebuggerServer extension API. - setRootActor: function DS_setRootActor(aFunction) { - this.createRootActor = aFunction; + setRootActor(actorFactory) { + this.createRootActor = actorFactory; }, /** @@ -1295,24 +1304,23 @@ var DebuggerServer = { * @param aTransport transport * Packet transport for the debugging protocol. */ -function DebuggerServerConnection(aPrefix, aTransport) -{ - this._prefix = aPrefix; - this._transport = aTransport; +function DebuggerServerConnection(prefix, transport) { + this._prefix = prefix; + this._transport = transport; this._transport.hooks = this; this._nextID = 1; this._actorPool = new ActorPool(this); this._extraPools = [this._actorPool]; - // Responses to a given actor must be returned the client + // Responses to a given actor must be returned the the client // in the same order as the requests that they're replying to, but // Implementations might finish serving requests in a different // order. To keep things in order we generate a promise for each // request, chained to the promise for the request before it. // This map stores the latest request promise in the chain, keyed // by an actor ID string. - this._actorResponses = new Map; + this._actorResponses = new Map(); /* * We can forward packets to other servers, if the actors on that server @@ -1320,15 +1328,19 @@ function DebuggerServerConnection(aPrefix, aTransport) * to transports: it maps a prefix P to a transport T if T conveys * packets to the server whose actors' names all begin with P + "/". */ - this._forwardingPrefixes = new Map; + this._forwardingPrefixes = new Map(); } DebuggerServerConnection.prototype = { _prefix: null, - get prefix() { return this._prefix }, + get prefix() { + return this._prefix; + }, _transport: null, - get transport() { return this._transport }, + get transport() { + return this._transport; + }, /** * Message manager used to communicate with the parent process, @@ -1337,48 +1349,70 @@ DebuggerServerConnection.prototype = { */ parentMessageManager: null, - close: function() { - this._transport.close(); + close() { + if (this._transport) { + this._transport.close(); + } }, - send: function DSC_send(aPacket) { - this.transport.send(aPacket); + send(packet) { + this.transport.send(packet); }, /** * Used when sending a bulk reply from an actor. * @see DebuggerTransport.prototype.startBulkSend */ - startBulkSend: function(header) { + startBulkSend(header) { return this.transport.startBulkSend(header); }, - allocID: function DSC_allocID(aPrefix) { - return this.prefix + (aPrefix || '') + this._nextID++; + allocID(prefix) { + return this.prefix + (prefix || "") + this._nextID++; }, /** * Add a map of actor IDs to the connection. */ - addActorPool: function DSC_addActorPool(aActorPool) { - this._extraPools.push(aActorPool); + addActorPool(actorPool) { + this._extraPools.push(actorPool); }, /** * Remove a previously-added pool of actors to the connection. * - * @param ActorPool aActorPool + * @param ActorPool actorPool * The ActorPool instance you want to remove. - * @param boolean aNoCleanup [optional] + * @param boolean noCleanup [optional] * True if you don't want to disconnect each actor from the pool, false * otherwise. */ - removeActorPool: function DSC_removeActorPool(aActorPool, aNoCleanup) { - let index = this._extraPools.lastIndexOf(aActorPool); + removeActorPool(actorPool, noCleanup) { + // When a connection is closed, it removes each of its actor pools. When an + // actor pool is removed, it calls the disconnect method on each of its + // actors. Some actors, such as ThreadActor, manage their own actor pools. + // When the disconnect method is called on these actors, they manually + // remove their actor pools. Consequently, this method is reentrant. + // + // In addition, some actors, such as ThreadActor, perform asynchronous work + // (in the case of ThreadActor, because they need to resume), before they + // remove each of their actor pools. Since we don't wait for this work to + // be completed, we can end up in this function recursively after the + // connection already set this._extraPools to null. + // + // This is a bug: if the disconnect method can perform asynchronous work, + // then we should wait for that work to be completed before setting this. + // _extraPools to null. As a temporary solution, it should be acceptable + // to just return early (if this._extraPools has been set to null, all + // actors pools for this connection should already have been removed). + if (this._extraPools === null) { + return; + } + let index = this._extraPools.lastIndexOf(actorPool); if (index > -1) { let pool = this._extraPools.splice(index, 1); - if (!aNoCleanup) { - pool.map(function(p) { p.cleanup(); }); + if (!noCleanup) { + pool.forEach(p => p.destroy()); } } }, @@ -1386,51 +1420,51 @@ DebuggerServerConnection.prototype = { /** * Add an actor to the default actor pool for this connection. */ - addActor: function DSC_addActor(aActor) { - this._actorPool.addActor(aActor); + addActor(actor) { + this._actorPool.addActor(actor); }, /** * Remove an actor to the default actor pool for this connection. */ - removeActor: function DSC_removeActor(aActor) { - this._actorPool.removeActor(aActor); + removeActor(actor) { + this._actorPool.removeActor(actor); }, /** * Match the api expected by the protocol library. */ - unmanage: function(aActor) { - return this.removeActor(aActor); + unmanage(actor) { + return this.removeActor(actor); }, /** * Look up an actor implementation for an actorID. Will search * all the actor pools registered with the connection. * - * @param aActorID string + * @param actorID string * Actor ID to look up. */ - getActor: function DSC_getActor(aActorID) { - let pool = this.poolFor(aActorID); + getActor(actorID) { + let pool = this.poolFor(actorID); if (pool) { - return pool.get(aActorID); + return pool.get(actorID); } - if (aActorID === "root") { + if (actorID === "root") { return this.rootActor; } return null; }, - _getOrCreateActor: function(actorID) { + _getOrCreateActor(actorID) { let actor = this.getActor(actorID); if (!actor) { this.transport.send({ from: actorID ? actorID : "root", error: "noSuchActor", message: "No such actor for ID: " + actorID }); - return; + return null; } // Dynamically-loaded actors have to be created lazily. @@ -1452,16 +1486,16 @@ DebuggerServerConnection.prototype = { return actor; }, - poolFor: function DSC_actorPool(aActorID) { + poolFor(actorID) { for (let pool of this._extraPools) { - if (pool.has(aActorID)) { + if (pool.has(actorID)) { return pool; } } return null; }, - _unknownError: function DSC__unknownError(aPrefix, aError) { + _unknownError(aPrefix, aError) { // let errorString = aPrefix + ": " + DevToolsUtils.safeErrorString(aError); // reportError(errorString); // dumpn(errorString); @@ -1472,21 +1506,21 @@ DebuggerServerConnection.prototype = { }; }, - _queueResponse: function(from, type, response) { - let pendingResponse = this._actorResponses.get(from) || resolve(null); + _queueResponse: function (from, type, responseOrPromise) { + let pendingResponse = this._actorResponses.get(from) || Promise.resolve(null); let responsePromise = pendingResponse.then(() => { - return response; - }).then(aResponse => { - if (!aResponse.from) { - aResponse.from = from; + return responseOrPromise; + }).then(response => { + if (!response.from) { + response.from = from; } - this.transport.send(aResponse); + this.transport.send(response); }).then(null, (e) => { let errorPacket = this._unknownError( - "error occurred while processing '" + type, - e); + "error occurred while processing '" + type, e); errorPacket.from = from; this.transport.send(errorPacket); + log("Stack: " + e.stack); }); this._actorResponses.set(from, responsePromise); @@ -1495,9 +1529,9 @@ DebuggerServerConnection.prototype = { /** * Passes a set of options to the BrowserAddonActors for the given ID. * - * @param aId string + * @param id string * The ID of the add-on to pass the options to - * @param aOptions object + * @param options object * The options. * @return a promise that will be resolved when complete. */ @@ -1523,30 +1557,37 @@ DebuggerServerConnection.prototype = { * Arrange to forward packets to another server. This is how we * forward debugging connections to child processes. * - * If we receive a packet for an actor whose name begins with |aPrefix| - * followed by '/', then we will forward that packet to |aTransport|. + * If we receive a packet for an actor whose name begins with |prefix| + * followed by '/', then we will forward that packet to |transport|. * - * This overrides any prior forwarding for |aPrefix|. + * This overrides any prior forwarding for |prefix|. * - * @param aPrefix string + * @param prefix string * The actor name prefix, not including the '/'. - * @param aTransport object + * @param transport object * A packet transport to which we should forward packets to actors - * whose names begin with |(aPrefix + '/').| + * whose names begin with |(prefix + '/').| */ - setForwarding: function(aPrefix, aTransport) { - this._forwardingPrefixes.set(aPrefix, aTransport); + setForwarding(prefix, transport) { + this._forwardingPrefixes.set(prefix, transport); }, /* * Stop forwarding messages to actors whose names begin with - * |aPrefix+'/'|. Such messages will now elicit 'noSuchActor' errors. + * |prefix+'/'|. Such messages will now elicit 'noSuchActor' errors. */ - cancelForwarding: function(aPrefix) { - this._forwardingPrefixes.delete(aPrefix); + cancelForwarding(prefix) { + this._forwardingPrefixes.delete(prefix); + + // Notify the client that forwarding in now cancelled for this prefix. + // There could be requests in progress that the client should abort rather leaving + // handing indefinitely. + if (this.rootActor) { + this.send(this.rootActor.forwardingCancelled(prefix)); + } }, - sendActorEvent: function (actorID, eventName, event = {}) { + sendActorEvent(actorID, eventName, event = {}) { event.from = actorID; event.type = eventName; this.send(event); @@ -1557,10 +1598,10 @@ DebuggerServerConnection.prototype = { /** * Called by DebuggerTransport to dispatch incoming packets as appropriate. * - * @param aPacket object + * @param packet object * The incoming packet. */ - onPacket: function DSC_onPacket(aPacket) { + onPacket(packet) { // If the actor's name begins with a prefix we've been asked to // forward, do so. // @@ -1568,52 +1609,52 @@ DebuggerServerConnection.prototype = { // forwarding is needed: in DebuggerServerConnection instances in child // processes, every actor has a prefixed name. if (this._forwardingPrefixes.size > 0) { - let to = aPacket.to; - let separator = to.lastIndexOf('/'); + let to = packet.to; + let separator = to.lastIndexOf("/"); while (separator >= 0) { to = to.substring(0, separator); - let forwardTo = this._forwardingPrefixes.get(aPacket.to.substring(0, separator)); + let forwardTo = this._forwardingPrefixes.get(packet.to.substring(0, separator)); if (forwardTo) { - forwardTo.send(aPacket); + forwardTo.send(packet); return; } - separator = to.lastIndexOf('/'); + separator = to.lastIndexOf("/"); } } - let actor = this._getOrCreateActor(aPacket.to); + let actor = this._getOrCreateActor(packet.to); if (!actor) { return; } - - var ret = null; + let ret = null; // handle "requestTypes" RDP request. - if (aPacket.type == "requestTypes") { + if (packet.type == "requestTypes") { ret = { from: actor.actorID, requestTypes: Object.keys(actor.requestTypes) }; - } else if (actor.requestTypes && actor.requestTypes[aPacket.type]) { + } else if (actor.requestTypes && actor.requestTypes[packet.type]) { // Dispatch the request to the actor. try { - this.currentPacket = aPacket; - ret = actor.requestTypes[aPacket.type].bind(actor)(aPacket, this); - } catch(e) { + this.currentPacket = packet; + ret = actor.requestTypes[packet.type].bind(actor)(packet, this); + } catch (e) { + log("Devtool onPacket failed: " + e + "\nstack: " + e.stack); this.transport.send(this._unknownError( - "error occurred while processing '" + aPacket.type, + "error occurred while processing '" + packet.type, e)); - // log(e.stack); } finally { this.currentPacket = undefined; } } else { + log("...." + actor._originalUrl + ", " + actor.requestTypes); ret = { error: "unrecognizedPacketType", message: ("Actor " + actor.actorID + " does not recognize the packet type " + - aPacket.type) }; + packet.type) }; } // There will not be a return value if a bulk reply is sent. if (ret) { - this._queueResponse(aPacket.to, aPacket.type, ret); + this._queueResponse(packet.to, packet.type, ret); } }, @@ -1647,8 +1688,8 @@ DebuggerServerConnection.prototype = { * This object also emits "progress" events for each chunk * that is copied. See stream-utils.js. */ - onBulkPacket: function(packet) { - let { actor: actorKey, type, length } = packet; + onBulkPacket(packet) { + let { actor: actorKey, type } = packet; let actor = this._getOrCreateActor(actorKey); if (!actor) { @@ -1660,7 +1701,7 @@ DebuggerServerConnection.prototype = { if (actor.requestTypes && actor.requestTypes[type]) { try { ret = actor.requestTypes[type].call(actor, packet); - } catch(e) { + } catch (e) { this.transport.send(this._unknownError( "error occurred while processing bulk packet '" + type, e)); packet.done.reject(e); @@ -1682,20 +1723,21 @@ DebuggerServerConnection.prototype = { /** * Called by DebuggerTransport when the underlying stream is closed. * - * @param aStatus nsresult + * @param status nsresult * The status code that corresponds to the reason for closing * the stream. */ - onClosed: function DSC_onClosed(aStatus) { + onClosed(status) { dumpn("Cleaning up connection."); if (!this._actorPool) { // Ignore this call if the connection is already closed. return; } - events.emit(this, "closed", aStatus); - this._actorPool = null; - this._extraPools.map(function(p) { p.cleanup(); }); + + events.emit(this, "closed", status); + + this._extraPools.forEach(p => p.destroy()); this._extraPools = null; this.rootActor = null; @@ -1706,7 +1748,7 @@ DebuggerServerConnection.prototype = { /* * Debugging helper for inspecting the state of the actor pools. */ - _dumpPools: function DSC_dumpPools() { + _dumpPools() { // dumpn("/-------------------- dumping pools:"); // if (this._actorPool) { // dumpn("--------------------- actorPool actors: " + @@ -1723,10 +1765,10 @@ DebuggerServerConnection.prototype = { /* * Debugging helper for inspecting the state of an actor pool. */ - _dumpPool: function DSC_dumpPools(aPool) { + _dumpPool(pool) { // dumpn("/-------------------- dumping pool:"); // dumpn("--------------------- actorPool actors: " + - // uneval(Object.keys(aPool._actors))); + // uneval(Object.keys(pool._actors))); }, /** diff --git a/native/cocos/scripting/js-bindings/script/debugger/protocol.js b/native/cocos/scripting/js-bindings/script/debugger/protocol.js new file mode 100644 index 0000000000..ae19e99465 --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/protocol.js @@ -0,0 +1,1517 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +// var promise = require("promise"); +// var defer = require("devtools/shared/defer"); +// var {Class} = require("sdk/core/heritage"); +// var {EventTarget} = require("sdk/event/target"); +// var events = require("sdk/event/core"); +// var object = require("sdk/util/object"); +// var {getStack, callFunctionWithAsyncStack} = require("devtools/shared/platform/stack"); + +// exports.emit = events.emit; + +/** + * Types: named marshallers/demarshallers. + * + * Types provide a 'write' function that takes a js representation and + * returns a protocol representation, and a "read" function that + * takes a protocol representation and returns a js representation. + * + * The read and write methods are also passed a context object that + * represent the actor or front requesting the translation. + * + * Types are referred to with a typestring. Basic types are + * registered by name using addType, and more complex types can + * be generated by adding detail to the type name. + */ + +var types = Object.create(null); +// exports.types = types; + +var registeredTypes = types.registeredTypes = new Map(); +var registeredLifetimes = types.registeredLifetimes = new Map(); + +/** + * Return the type object associated with a given typestring. + * If passed a type object, it will be returned unchanged. + * + * Types can be registered with addType, or can be created on + * the fly with typestrings. Examples: + * + * boolean + * threadActor + * threadActor#detail + * array:threadActor + * array:array:threadActor#detail + * + * @param [typestring|type] type + * Either a typestring naming a type or a type object. + * + * @returns a type object. + */ +types.getType = function (type) { + if (!type) { + return types.Primitive; + } + + if (typeof (type) !== "string") { + return type; + } + + // If already registered, we're done here. + let reg = registeredTypes.get(type); + if (reg) return reg; + + // New type, see if it's a collection/lifetime type: + let sep = type.indexOf(":"); + if (sep >= 0) { + let collection = type.substring(0, sep); + let subtype = types.getType(type.substring(sep + 1)); + + if (collection === "array") { + return types.addArrayType(subtype); + } else if (collection === "nullable") { + return types.addNullableType(subtype); + } + + if (registeredLifetimes.has(collection)) { + return types.addLifetimeType(collection, subtype); + } + + throw Error("Unknown collection type: " + collection); + } + + // Not a collection, might be actor detail + let pieces = type.split("#", 2); + if (pieces.length > 1) { + return types.addActorDetail(type, pieces[0], pieces[1]); + } + + // Might be a lazily-loaded type + if (type === "longstring") { + require("devtools/shared/specs/string"); + return registeredTypes.get("longstring"); + } + + throw Error("Unknown type: " + type); +}; + +/** + * Don't allow undefined when writing primitive types to packets. If + * you want to allow undefined, use a nullable type. + */ +function identityWrite(v) { + if (v === undefined) { + throw Error("undefined passed where a value is required"); + } + // This has to handle iterator->array conversion because arrays of + // primitive types pass through here. + if (v && typeof (v) === "object" && Symbol.iterator in v) { + return [...v]; + } + return v; +} + +/** + * Add a type to the type system. + * + * When registering a type, you can provide `read` and `write` methods. + * + * The `read` method will be passed a JS object value from the JSON + * packet and must return a native representation. The `write` method will + * be passed a native representation and should provide a JSONable value. + * + * These methods will both be passed a context. The context is the object + * performing or servicing the request - on the server side it will be + * an Actor, on the client side it will be a Front. + * + * @param typestring name + * Name to register + * @param object typeObject + * An object whose properties will be stored in the type, including + * the `read` and `write` methods. + * @param object options + * Can specify `thawed` to prevent the type from being frozen. + * + * @returns a type object that can be used in protocol definitions. + */ +types.addType = function (name, typeObject = {}, options = {}) { + if (registeredTypes.has(name)) { + throw Error("Type '" + name + "' already exists."); + } + + let type = merge({ + toString() { return "[protocol type:" + name + "]";}, + name: name, + primitive: !(typeObject.read || typeObject.write), + read: identityWrite, + write: identityWrite + }, typeObject); + + registeredTypes.set(name, type); + + return type; +}; + +/** + * Remove a type previously registered with the system. + * Primarily useful for types registered by addons. + */ +types.removeType = function (name) { + // This type may still be referenced by other types, make sure + // those references don't work. + let type = registeredTypes.get(name); + + type.name = "DEFUNCT:" + name; + type.category = "defunct"; + type.primitive = false; + type.read = type.write = function () { throw new Error("Using defunct type: " + name); }; + + registeredTypes.delete(name); +}; + +/** + * Add an array type to the type system. + * + * getType() will call this function if provided an "array:" + * typestring. + * + * @param type subtype + * The subtype to be held by the array. + */ +types.addArrayType = function (subtype) { + subtype = types.getType(subtype); + + let name = "array:" + subtype.name; + + // Arrays of primitive types are primitive types themselves. + if (subtype.primitive) { + return types.addType(name); + } + return types.addType(name, { + category: "array", + read: (v, ctx) => [...v].map(i => subtype.read(i, ctx)), + write: (v, ctx) => [...v].map(i => subtype.write(i, ctx)) + }); +}; + +/** + * Add a dict type to the type system. This allows you to serialize + * a JS object that contains non-primitive subtypes. + * + * Properties of the value that aren't included in the specializations + * will be serialized as primitive values. + * + * @param object specializations + * A dict of property names => type + */ +types.addDictType = function (name, specializations) { + return types.addType(name, { + category: "dict", + specializations: specializations, + read: (v, ctx) => { + let ret = {}; + for (let prop in v) { + if (prop in specializations) { + ret[prop] = types.getType(specializations[prop]).read(v[prop], ctx); + } else { + ret[prop] = v[prop]; + } + } + return ret; + }, + + write: (v, ctx) => { + let ret = {}; + for (let prop in v) { + if (prop in specializations) { + ret[prop] = types.getType(specializations[prop]).write(v[prop], ctx); + } else { + ret[prop] = v[prop]; + } + } + return ret; + } + }); +}; + +/** + * Register an actor type with the type system. + * + * Types are marshalled differently when communicating server->client + * than they are when communicating client->server. The server needs + * to provide useful information to the client, so uses the actor's + * `form` method to get a json representation of the actor. When + * making a request from the client we only need the actor ID string. + * + * This function can be called before the associated actor has been + * constructed, but the read and write methods won't work until + * the associated addActorImpl or addActorFront methods have been + * called during actor/front construction. + * + * @param string name + * The typestring to register. + */ +types.addActorType = function (name) { + let type = types.addType(name, { + _actor: true, + category: "actor", + read: (v, ctx, detail) => { + // If we're reading a request on the server side, just + // find the actor registered with this actorID. + if (ctx instanceof Actor) { + return ctx.conn.getActor(v); + } + + // Reading a response on the client side, check for an + // existing front on the connection, and create the front + // if it isn't found. + let actorID = typeof (v) === "string" ? v : v.actor; + let front = ctx.conn.getActor(actorID); + if (!front) { + front = new type.frontClass(ctx.conn); + front.actorID = actorID; + ctx.marshallPool().manage(front); + } + + v = type.formType(detail).read(v, front, detail); + front.form(v, detail, ctx); + + return front; + }, + write: (v, ctx, detail) => { + // If returning a response from the server side, make sure + // the actor is added to a parent object and return its form. + if (v instanceof Actor) { + if (!v.actorID) { + ctx.marshallPool().manage(v); + } + return type.formType(detail).write(v.form(detail), ctx, detail); + } + + // Writing a request from the client side, just send the actor id. + return v.actorID; + }, + formType: (detail) => { + if (!("formType" in type.actorSpec)) { + return types.Primitive; + } + + let formAttr = "formType"; + if (detail) { + formAttr += "#" + detail; + } + + if (!(formAttr in type.actorSpec)) { + throw new Error("No type defined for " + formAttr); + } + + return type.actorSpec[formAttr]; + } + }); + return type; +}; + +types.addNullableType = function (subtype) { + subtype = types.getType(subtype); + return types.addType("nullable:" + subtype.name, { + category: "nullable", + read: (value, ctx) => { + if (value == null) { + return value; + } + return subtype.read(value, ctx); + }, + write: (value, ctx) => { + if (value == null) { + return value; + } + return subtype.write(value, ctx); + } + }); +}; + +/** + * Register an actor detail type. This is just like an actor type, but + * will pass a detail hint to the actor's form method during serialization/ + * deserialization. + * + * This is called by getType() when passed an 'actorType#detail' string. + * + * @param string name + * The typestring to register this type as. + * @param type actorType + * The actor type you'll be detailing. + * @param string detail + * The detail to pass. + */ +types.addActorDetail = function (name, actorType, detail) { + actorType = types.getType(actorType); + if (!actorType._actor) { + throw Error("Details only apply to actor types, tried to add detail '" + detail + "'' to " + actorType.name + "\n"); + } + return types.addType(name, { + _actor: true, + category: "detail", + read: (v, ctx) => actorType.read(v, ctx, detail), + write: (v, ctx) => actorType.write(v, ctx, detail) + }); +}; + +/** + * Register an actor lifetime. This lets the type system find a parent + * actor that differs from the actor fulfilling the request. + * + * @param string name + * The lifetime name to use in typestrings. + * @param string prop + * The property of the actor that holds the parent that should be used. + */ +types.addLifetime = function (name, prop) { + if (registeredLifetimes.has(name)) { + throw Error("Lifetime '" + name + "' already registered."); + } + registeredLifetimes.set(name, prop); +}; + +/** + * Remove a previously-registered lifetime. Useful for lifetimes registered + * in addons. + */ +types.removeLifetime = function (name) { + registeredLifetimes.delete(name); +}; + +/** + * Register a lifetime type. This creates an actor type tied to the given + * lifetime. + * + * This is called by getType() when passed a ':' + * typestring. + * + * @param string lifetime + * A lifetime string previously regisered with addLifetime() + * @param type subtype + * An actor type + */ +types.addLifetimeType = function (lifetime, subtype) { + subtype = types.getType(subtype); + if (!subtype._actor) { + throw Error("Lifetimes only apply to actor types, tried to apply lifetime '" + lifetime + "'' to " + subtype.name); + } + let prop = registeredLifetimes.get(lifetime); + return types.addType(lifetime + ":" + subtype.name, { + category: "lifetime", + read: (value, ctx) => subtype.read(value, ctx[prop]), + write: (value, ctx) => subtype.write(value, ctx[prop]) + }); +}; + +// Add a few named primitive types. +types.Primitive = types.addType("primitive"); +types.String = types.addType("string"); +types.Number = types.addType("number"); +types.Boolean = types.addType("boolean"); +types.JSON = types.addType("json"); + +/** + * Request/Response templates and generation + * + * Request packets are specified as json templates with + * Arg and Option placeholders where arguments should be + * placed. + * + * Reponse packets are also specified as json templates, + * with a RetVal placeholder where the return value should be + * placed. + */ + +/** + * Placeholder for simple arguments. + * + * @param number index + * The argument index to place at this position. + * @param type type + * The argument should be marshalled as this type. + * @constructor + */ +var Arg = Class({ + initialize: function (index, type) { + this.index = index; + this.type = types.getType(type); + }, + + write: function (arg, ctx) { + return this.type.write(arg, ctx); + }, + + read: function (v, ctx, outArgs) { + outArgs[this.index] = this.type.read(v, ctx); + }, + + describe: function () { + return { + _arg: this.index, + type: this.type.name, + }; + } +}); +// exports.Arg = Arg; + +/** + * Placeholder for an options argument value that should be hoisted + * into the packet. + * + * If provided in a method specification: + * + * { optionArg: Option(1)} + * + * Then arguments[1].optionArg will be placed in the packet in this + * value's place. + * + * @param number index + * The argument index of the options value. + * @param type type + * The argument should be marshalled as this type. + * @constructor + */ +var Option = Class({ + extends: Arg, + initialize: function (index, type) { + Arg.prototype.initialize.call(this, index, type); + }, + + write: function (arg, ctx, name) { + // Ignore if arg is undefined or null; allow other falsy values + if (arg == undefined || arg[name] == undefined) { + return undefined; + } + let v = arg[name]; + return this.type.write(v, ctx); + }, + read: function (v, ctx, outArgs, name) { + if (outArgs[this.index] === undefined) { + outArgs[this.index] = {}; + } + if (v === undefined) { + return; + } + outArgs[this.index][name] = this.type.read(v, ctx); + }, + + describe: function () { + return { + _option: this.index, + type: this.type.name, + }; + } +}); + +// exports.Option = Option; + +/** + * Placeholder for return values in a response template. + * + * @param type type + * The return value should be marshalled as this type. + */ +var RetVal = Class({ + initialize: function (type) { + this.type = types.getType(type); + }, + + write: function (v, ctx) { + return this.type.write(v, ctx); + }, + + read: function (v, ctx) { + return this.type.read(v, ctx); + }, + + describe: function () { + return { + _retval: this.type.name + }; + } +}); + +// exports.RetVal = RetVal; + +/* Template handling functions */ + +/** + * Get the value at a given path, or undefined if not found. + */ +function getPath(obj, path) { + for (let name of path) { + if (!(name in obj)) { + return undefined; + } + obj = obj[name]; + } + return obj; +} + +/** + * Find Placeholders in the template and save them along with their + * paths. + */ +function findPlaceholders(template, constructor, path = [], placeholders = []) { + if (!template || typeof (template) != "object") { + return placeholders; + } + + if (template instanceof constructor) { + placeholders.push({ placeholder: template, path: [...path] }); + return placeholders; + } + + for (let name in template) { + path.push(name); + findPlaceholders(template[name], constructor, path, placeholders); + path.pop(); + } + + return placeholders; +} + + +function describeTemplate(template) { + return JSON.parse(JSON.stringify(template, (key, value) => { + if (value.describe) { + return value.describe(); + } + return value; + })); +} + +/** + * Manages a request template. + * + * @param object template + * The request template. + * @construcor + */ +var Request = Class({ + initialize: function (template = {}) { + this.type = template.type; + this.template = template; + this.args = findPlaceholders(template, Arg); + }, + + /** + * Write a request. + * + * @param array fnArgs + * The function arguments to place in the request. + * @param object ctx + * The object making the request. + * @returns a request packet. + */ + write: function (fnArgs, ctx) { + let str = JSON.stringify(this.template, (key, value) => { + if (value instanceof Arg) { + return value.write(value.index in fnArgs ? fnArgs[value.index] : undefined, + ctx, key); + } + return value; + }); + return JSON.parse(str); + }, + + /** + * Read a request. + * + * @param object packet + * The request packet. + * @param object ctx + * The object making the request. + * @returns an arguments array + */ + read: function (packet, ctx) { + let fnArgs = []; + for (let templateArg of this.args) { + let arg = templateArg.placeholder; + let path = templateArg.path; + let name = path[path.length - 1]; + arg.read(getPath(packet, path), ctx, fnArgs, name); + } + return fnArgs; + }, + + describe: function () { return describeTemplate(this.template); } +}); + +/** + * Manages a response template. + * + * @param object template + * The response template. + * @construcor + */ +var Response = Class({ + initialize: function (template = {}) { + this.template = template; + let placeholders = findPlaceholders(template, RetVal); + if (placeholders.length > 1) { + throw Error("More than one RetVal specified in response"); + } + let placeholder = placeholders.shift(); + if (placeholder) { + this.retVal = placeholder.placeholder; + this.path = placeholder.path; + } + }, + + /** + * Write a response for the given return value. + * + * @param val ret + * The return value. + * @param object ctx + * The object writing the response. + */ + write: function (ret, ctx) { + return JSON.parse(JSON.stringify(this.template, function (key, value) { + if (value instanceof RetVal) { + return value.write(ret, ctx); + } + return value; + })); + }, + + /** + * Read a return value from the given response. + * + * @param object packet + * The response packet. + * @param object ctx + * The object reading the response. + */ + read: function (packet, ctx) { + if (!this.retVal) { + return undefined; + } + let v = getPath(packet, this.path); + return this.retVal.read(v, ctx); + }, + + describe: function () { return describeTemplate(this.template); } +}); + +/** + * Actor and Front implementations + */ + +/** + * A protocol object that can manage the lifetime of other protocol + * objects. + */ +var Pool = Class({ + extends: EventTarget, + + /** + * Pools are used on both sides of the connection to help coordinate + * lifetimes. + * + * @param optional conn + * Either a DebuggerServerConnection or a DebuggerClient. Must have + * addActorPool, removeActorPool, and poolFor. + * conn can be null if the subclass provides a conn property. + * @constructor + */ + initialize: function (conn) { + if (conn) { + this.conn = conn; + } + }, + + /** + * Return the parent pool for this client. + */ + parent: function () { return this.conn.poolFor(this.actorID); }, + + /** + * Override this if you want actors returned by this actor + * to belong to a different actor by default. + */ + marshallPool: function () { return this; }, + + /** + * Pool is the base class for all actors, even leaf nodes. + * If the child map is actually referenced, go ahead and create + * the stuff needed by the pool. + */ + __poolMap: null, + get _poolMap() { + if (this.__poolMap) return this.__poolMap; + this.__poolMap = new Map(); + this.conn.addActorPool(this); + return this.__poolMap; + }, + + /** + * Add an actor as a child of this pool. + */ + manage: function (actor) { + if (!actor.actorID) { + actor.actorID = this.conn.allocID(actor.actorPrefix || actor.typeName); + } + + this._poolMap.set(actor.actorID, actor); + return actor; + }, + + /** + * Remove an actor as a child of this pool. + */ + unmanage: function (actor) { + this.__poolMap && this.__poolMap.delete(actor.actorID); + }, + + // true if the given actor ID exists in the pool. + has: function (actorID) { + return this.__poolMap && this._poolMap.has(actorID); + }, + + // The actor for a given actor id stored in this pool + actor: function (actorID) { + return this.__poolMap ? this._poolMap.get(actorID) : null; + }, + + // Same as actor, should update debugger connection to use 'actor' + // and then remove this. + get: function (actorID) { + return this.__poolMap ? this._poolMap.get(actorID) : null; + }, + + // True if this pool has no children. + isEmpty: function () { + return !this.__poolMap || this._poolMap.size == 0; + }, + + /** + * Destroy this item, removing it from a parent if it has one, + * and destroying all children if necessary. + */ + destroy: function () { + let parent = this.parent(); + if (parent) { + parent.unmanage(this); + } + if (!this.__poolMap) { + return; + } + for (let actor of this.__poolMap.values()) { + // Self-owned actors are ok, but don't need destroying twice. + if (actor === this) { + continue; + } + let destroy = actor.destroy; + if (destroy) { + // Disconnect destroy while we're destroying in case of (misbehaving) + // circular ownership. + actor.destroy = null; + destroy.call(actor); + actor.destroy = destroy; + } + } + this.conn.removeActorPool(this, true); + this.__poolMap.clear(); + this.__poolMap = null; + }, + + /** + * For getting along with the debugger server pools, should be removable + * eventually. + */ + cleanup: function () { + this.destroy(); + } +}); +// exports.Pool = Pool; + +/** + * An actor in the actor tree. + */ +var Actor = Class({ + extends: Pool, + + // Will contain the actor's ID + actorID: null, + + /** + * Initialize an actor. + * + * @param optional conn + * Either a DebuggerServerConnection or a DebuggerClient. Must have + * addActorPool, removeActorPool, and poolFor. + * conn can be null if the subclass provides a conn property. + * @constructor + */ + initialize: function (conn) { + Pool.prototype.initialize.call(this, conn); + + // Forward events to the connection. + if (this._actorSpec && this._actorSpec.events) { + for (let key of this._actorSpec.events.keys()) { + let name = key; + let sendEvent = this._sendEvent.bind(this, name); + this.on(name, (...args) => { + sendEvent.apply(null, args); + }); + } + } + }, + + toString: function () { return "[Actor " + this.typeName + "/" + this.actorID + "]"; }, + + _sendEvent: function (name, ...args) { + if (!this._actorSpec.events.has(name)) { + // It's ok to emit events that don't go over the wire. + return; + } + let request = this._actorSpec.events.get(name); + let packet; + try { + packet = request.write(args, this); + } catch (ex) { + console.error("Error sending event: " + name); + throw ex; + } + packet.from = packet.from || this.actorID; + this.conn.send(packet); + }, + + destroy: function () { + Pool.prototype.destroy.call(this); + this.actorID = null; + }, + + /** + * Override this method in subclasses to serialize the actor. + * @param [optional] string hint + * Optional string to customize the form. + * @returns A jsonable object. + */ + form: function (hint) { + return { actor: this.actorID }; + }, + + writeError: function (error) { + console.error(error); + if (error.stack) { + dump(error.stack); + } + this.conn.send({ + from: this.actorID, + error: error.error || "unknownError", + message: error.message + }); + }, + + _queueResponse: function (create) { + let pending = this._pendingResponse || Promise.resolve(null); + let response = create(pending); + this._pendingResponse = response; + } +}); +// exports.Actor = Actor; + +/** + * Tags a prtotype method as an actor method implementation. + * + * @param function fn + * The implementation function, will be returned. + * @param spec + * The method specification, with the following (optional) properties: + * request (object): a request template. + * response (object): a response template. + * oneway (bool): 'true' if no response should be sent. + */ +function method (fn, spec = {}) { + fn._methodSpec = Object.freeze(spec); + if (spec.request) Object.freeze(spec.request); + if (spec.response) Object.freeze(spec.response); + return fn; +}; + +/** + * Generates an actor specification from an actor description. + */ +var generateActorSpec = function (actorDesc) { + let actorSpec = { + typeName: actorDesc.typeName, + methods: [] + }; + + // Find method and form specifications attached to properties. + for (let name of Object.getOwnPropertyNames(actorDesc)) { + let desc = Object.getOwnPropertyDescriptor(actorDesc, name); + if (!desc.value) { + continue; + } + + if (name.startsWith("formType")) { + if (typeof (desc.value) === "string") { + actorSpec[name] = types.getType(desc.value); + } else if (desc.value.name && registeredTypes.has(desc.value.name)) { + actorSpec[name] = desc.value; + } else { + // Shorthand for a newly-registered DictType. + actorSpec[name] = types.addDictType(actorDesc.typeName + "__" + name, desc.value); + } + } + + if (desc.value._methodSpec) { + let methodSpec = desc.value._methodSpec; + let spec = {}; + spec.name = methodSpec.name || name; + spec.request = Request(merge({type: spec.name}, methodSpec.request || undefined)); + spec.response = Response(methodSpec.response || undefined); + spec.release = methodSpec.release; + spec.oneway = methodSpec.oneway; + + actorSpec.methods.push(spec); + } + } + + // Find additional method specifications + if (actorDesc.methods) { + for (let name in actorDesc.methods) { + let methodSpec = actorDesc.methods[name]; + let spec = {}; + + spec.name = methodSpec.name || name; + spec.request = Request(merge({type: spec.name}, methodSpec.request || undefined)); + spec.response = Response(methodSpec.response || undefined); + spec.release = methodSpec.release; + spec.oneway = methodSpec.oneway; + + actorSpec.methods.push(spec); + } + } + + // Find event specifications + if (actorDesc.events) { + actorSpec.events = new Map(); + for (let name in actorDesc.events) { + let eventRequest = actorDesc.events[name]; + Object.freeze(eventRequest); + actorSpec.events.set(name, Request(merge({type: name}, eventRequest))); + } + } + + if (!registeredTypes.has(actorSpec.typeName)) { + types.addActorType(actorSpec.typeName); + } + registeredTypes.get(actorSpec.typeName).actorSpec = actorSpec; + + return actorSpec; +}; +// exports.generateActorSpec = generateActorSpec; + +/** + * Generates request handlers as described by the given actor specification on + * the given actor prototype. Returns the actor prototype. + */ +var generateRequestHandlers = function (actorSpec, actorProto) { + if (actorProto._actorSpec) { + throw new Error("actorProto called twice on the same actor prototype!"); + } + + actorProto.typeName = actorSpec.typeName; + + // Generate request handlers for each method definition + actorProto.requestTypes = Object.create(null); + actorSpec.methods.forEach(spec => { + let handler = function (packet, conn) { + try { + let args; + try { + args = spec.request.read(packet, this); + } catch (ex) { + console.error("Error reading request: " + packet.type); + throw ex; + } + + let ret = this[spec.name].apply(this, args); + + let sendReturn = (ret) => { + if (spec.oneway) { + // No need to send a response. + return; + } + + let response; + try { + response = spec.response.write(ret, this); + } catch (ex) { + console.error("Error writing response to: " + spec.name); + throw ex; + } + response.from = this.actorID; + // If spec.release has been specified, destroy the object. + if (spec.release) { + try { + this.destroy(); + } catch (e) { + this.writeError(e); + return; + } + } + + conn.send(response); + }; + + this._queueResponse(p => { + return p + .then(() => ret) + .then(sendReturn) + .then(null, this.writeError.bind(this)); + }); + } catch (e) { + this._queueResponse(p => { + return p.then(() => this.writeError(e)); + }); + } + }; + + actorProto.requestTypes[spec.request.type] = handler; + }); + + actorProto._actorSpec = actorSpec; + + return actorProto; +}; + +/** + * THIS METHOD IS DEPRECATED, AND PRESERVED ONLY FOR ADD-ONS. IT SHOULD NOT BE + * USED INSIDE THE TREE. + * + * Create an actor class for the given actor prototype. + * + * @param object actorProto + * The actor prototype. Must have a 'typeName' property, + * should have method definitions, can have event definitions. + */ +function ActorClass (actorProto) { + return ActorClassWithSpec(generateActorSpec(actorProto), actorProto); +}; + +/** + * THIS METHOD IS DEPRECATED, AND PRESERVED ONLY FOR ADD-ONS. IT SHOULD NOT BE + * USED INSIDE THE TREE. + * + * Create an actor class for the given actor specification and prototype. + * + * @param object actorSpec + * The actor specification. Must have a 'typeName' property. + * @param object actorProto + * The actor prototype. Should have method definitions, can have event + * definitions. + */ +var ActorClassWithSpec = function (actorSpec, actorProto) { + if (!actorSpec.typeName) { + throw Error("Actor specification must have a typeName member."); + } + + actorProto.extends = Actor; + let cls = Class(generateRequestHandlers(actorSpec, actorProto)); + + return cls; +}; +// exports.ActorClassWithSpec = ActorClassWithSpec; + +/** + * Base class for client-side actor fronts. + */ +var Front = Class({ + extends: Pool, + + actorID: null, + + /** + * The base class for client-side actor fronts. + * + * @param optional conn + * Either a DebuggerServerConnection or a DebuggerClient. Must have + * addActorPool, removeActorPool, and poolFor. + * conn can be null if the subclass provides a conn property. + * @param optional form + * The json form provided by the server. + * @constructor + */ + initialize: function (conn = null, form = null, detail = null, context = null) { + Pool.prototype.initialize.call(this, conn); + this._requests = []; + + // protocol.js no longer uses this data in the constructor, only external + // uses do. External usage of manually-constructed fronts will be + // drastically reduced if we convert the root and tab actors to + // protocol.js, in which case this can probably go away. + if (form) { + this.actorID = form.actor; + form = types.getType(this.typeName).formType(detail).read(form, this, detail); + this.form(form, detail, context); + } + }, + + destroy: function () { + // Reject all outstanding requests, they won't make sense after + // the front is destroyed. + while (this._requests && this._requests.length > 0) { + let { deferred, to, type, stack } = this._requests.shift(); + let msg = "Connection closed, pending request to " + to + + ", type " + type + " failed" + + "\n\nRequest stack:\n" + stack.formattedStack; + deferred.reject(new Error(msg)); + } + Pool.prototype.destroy.call(this); + this.actorID = null; + }, + + manage: function (front) { + if (!front.actorID) { + throw new Error("Can't manage front without an actor ID.\n" + + "Ensure server supports " + front.typeName + "."); + } + return Pool.prototype.manage.call(this, front); + }, + + /** + * @returns a promise that will resolve to the actorID this front + * represents. + */ + actor: function () { return Promise.resolve(this.actorID); }, + + toString: function () { return "[Front for " + this.typeName + "/" + this.actorID + "]"; }, + + /** + * Update the actor from its representation. + * Subclasses should override this. + */ + form: function (form) {}, + + /** + * Send a packet on the connection. + */ + send: function (packet) { + if (packet.to) { + this.conn._transport.send(packet); + } else { + this.actor().then(actorID => { + packet.to = actorID; + this.conn._transport.send(packet); + }).then(null, e => console.error(e)); + } + }, + + /** + * Send a two-way request on the connection. + */ + request: function (packet) { + let deferred = Promise.defer(); + // Save packet basics for debugging + let { to, type } = packet; + this._requests.push({ + deferred, + to: to || this.actorID, + type, + stack: ""//getStack(), + }); + this.send(packet); + return deferred.promise; + }, + + /** + * Handler for incoming packets from the client's actor. + */ + onPacket: function (packet) { + // Pick off event packets + let type = packet.type || undefined; + if (this._clientSpec.events && this._clientSpec.events.has(type)) { + let event = this._clientSpec.events.get(packet.type); + let args; + try { + args = event.request.read(packet, this); + } catch (ex) { + console.error("Error reading event: " + packet.type); + console.exception(ex); + throw ex; + } + if (event.pre) { + let results = event.pre.map(pre => pre.apply(this, args)); + + // Check to see if any of the preEvents returned a promise -- if so, + // wait for their resolution before emitting. Otherwise, emit synchronously. + if (results.some(result => result && typeof result.then === "function")) { + Promise.all(results).then(() => events.emit.apply(null, [this, event.name].concat(args))); + return; + } + } + + events.emit.apply(null, [this, event.name].concat(args)); + return; + } + + // Remaining packets must be responses. + if (this._requests.length === 0) { + let msg = "Unexpected packet " + this.actorID + ", " + JSON.stringify(packet); + let err = Error(msg); + console.error(err); + throw err; + } + + let { deferred, stack } = this._requests.shift(); + // callFunctionWithAsyncStack(() => { + { + if (packet.error) { + // "Protocol error" is here to avoid TBPL heuristics. See also + // https://dxr.mozilla.org/webtools-central/source/tbpl/php/inc/GeneralErrorFilter.php + let message; + if (packet.error && packet.message) { + message = "Protocol error (" + packet.error + "): " + packet.message; + } else { + message = packet.error; + } + deferred.reject(message); + } else { + deferred.resolve(packet); + } + }//, stack, "DevTools RDP"); + } +}); +// exports.Front = Front; + +/** + * A method tagged with preEvent will be called after recieving a packet + * for that event, and before the front emits the event. + */ +function preEvent (eventName, fn) { + fn._preEvent = eventName; + return fn; +}; + +/** + * Mark a method as a custom front implementation, replacing the generated + * front method. + * + * @param function fn + * The front implementation, will be returned. + * @param object options + * Options object: + * impl (string): If provided, the generated front method will be + * stored as this property on the prototype. + */ +function custom (fn, options = {}) { + fn._customFront = options; + return fn; +}; + +function prototypeOf(obj) { + return typeof (obj) === "function" ? obj.prototype : obj; +} + +/** + * Generates request methods as described by the given actor specification on + * the given front prototype. Returns the front prototype. + */ +function generateRequestMethods (actorSpec, frontProto) { + if (frontProto._actorSpec) { + throw new Error("frontProto called twice on the same front prototype!"); + } + + frontProto.typeName = actorSpec.typeName; + + // Generate request methods. + let methods = actorSpec.methods; + methods.forEach(spec => { + let name = spec.name; + + // If there's already a property by this name in the front, it must + // be a custom front method. + if (name in frontProto) { + let custom = frontProto[spec.name]._customFront; + if (custom === undefined) { + throw Error("Existing method for " + spec.name + " not marked customFront while processing " + actorType.typeName + "."); + } + // If the user doesn't need the impl don't generate it. + if (!custom.impl) { + return; + } + name = custom.impl; + } + + frontProto[name] = function (...args) { + let packet; + try { + packet = spec.request.write(args, this); + } catch (ex) { + console.error("Error writing request: " + name); + throw ex; + } + if (spec.oneway) { + // Fire-and-forget oneway packets. + this.send(packet); + return undefined; + } + + return this.request(packet).then(response => { + let ret; + try { + ret = spec.response.read(response, this); + } catch (ex) { + console.error("Error reading response to: " + name); + throw ex; + } + return ret; + }); + }; + + // Release methods should call the destroy function on return. + if (spec.release) { + let fn = frontProto[name]; + frontProto[name] = function (...args) { + return fn.apply(this, args).then(result => { + this.destroy(); + return result; + }); + }; + } + }); + + + // Process event specifications + frontProto._clientSpec = {}; + + let events = actorSpec.events; + if (events) { + // This actor has events, scan the prototype for preEvent handlers... + let preHandlers = new Map(); + for (let name of Object.getOwnPropertyNames(frontProto)) { + let desc = Object.getOwnPropertyDescriptor(frontProto, name); + if (!desc.value) { + continue; + } + if (desc.value._preEvent) { + let preEvent = desc.value._preEvent; + if (!events.has(preEvent)) { + throw Error("preEvent for event that doesn't exist: " + preEvent); + } + let handlers = preHandlers.get(preEvent); + if (!handlers) { + handlers = []; + preHandlers.set(preEvent, handlers); + } + handlers.push(desc.value); + } + } + + frontProto._clientSpec.events = new Map(); + + for (let [name, request] of events) { + frontProto._clientSpec.events.set(request.type, { + name: name, + request: request, + pre: preHandlers.get(name) + }); + } + } + + frontProto._actorSpec = actorSpec; + + return frontProto; +}; + +/** + * Create a front class for the given actor class and front prototype. + * + * @param ActorClass actorType + * The actor class you're creating a front for. + * @param object frontProto + * The front prototype. Must have a 'typeName' property, + * should have method definitions, can have event definitions. + */ +function FrontClass (actorType, frontProto) { + return FrontClassWithSpec(prototypeOf(actorType)._actorSpec, frontProto); +}; + +/** + * Create a front class for the given actor specification and front prototype. + * + * @param object actorSpec + * The actor specification you're creating a front for. + * @param object proto + * The object prototype. Must have a 'typeName' property, + * should have method definitions, can have event definitions. + */ +function FrontClassWithSpec (actorSpec, frontProto) { + frontProto.extends = Front; + let cls = Class(generateRequestMethods(actorSpec, frontProto)); + + if (!registeredTypes.has(actorSpec.typeName)) { + types.addActorType(actorSpec.typeName); + } + registeredTypes.get(actorSpec.typeName).frontClass = cls; + + return cls; + }; +// exports.FrontClassWithSpec = FrontClassWithSpec; + +function dumpActorSpec (type) { + let actorSpec = type.actorSpec; + let ret = { + category: "actor", + typeName: type.name, + methods: [], + events: {} + }; + + for (let method of actorSpec.methods) { + ret.methods.push({ + name: method.name, + release: method.release || undefined, + oneway: method.oneway || undefined, + request: method.request.describe(), + response: method.response.describe() + }); + } + + if (actorSpec.events) { + for (let [name, request] of actorSpec.events) { + ret.events[name] = request.describe(); + } + } + + + JSON.stringify(ret); + + return ret; +}; + +function dumpProtocolSpec () { + let ret = { + types: {}, + }; + + for (let [name, type] of registeredTypes) { + // Force lazy instantiation if needed. + type = types.getType(name); + let category = type.category || undefined; + if (category === "dict") { + ret.types[name] = { + category: "dict", + typeName: name, + specializations: type.specializations + }; + } else if (category === "actor") { + ret.types[name] = dumpActorSpec(type); + } + } + + return ret; +}; diff --git a/native/cocos/scripting/js-bindings/script/debugger/sdk/event-core.js b/native/cocos/scripting/js-bindings/script/debugger/sdk/event-core.js new file mode 100644 index 0000000000..9c9626c6c2 --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/sdk/event-core.js @@ -0,0 +1,187 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public +* License, v. 2.0. If a copy of the MPL was not distributed with this +* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +const UNCAUGHT_ERROR = 'An error event was emitted for which there was no listener.'; +const BAD_LISTENER = 'The event listener must be a function.'; + +const EVENT_TYPE_PATTERN = /^on([A-Z]\w+$)/; + +// Count of total listeners ever added. +// This is used to keep track of when a listener was added, which can +// have an effect on when it is and isn't dispatched. See comments in +// emitOnObject for more details. +let listenerCount = 0; + +const observers = new DefaultWeakMap(() => { + return new DefaultMap(() => new Map()); +}); + +/** + * Registers an event `listener` that is called every time events of + * specified `type` is emitted on the given event `target`. + * @param {Object} target + * Event target object. + * @param {String} type + * The type of event. + * @param {Function} listener + * The listener function that processes the event. + */ +function on(target, type, listener) { + if (typeof(listener) !== 'function') + throw new Error(BAD_LISTENER); + + observers.get(target).get(type).set(listener, listenerCount++); +} +// exports.on = on; + + +// Map of wrapper functions for listeners added using `once`. +var onceWeakMap = new WeakMap(); + +/** + * Registers an event `listener` that is called only the next time an event + * of the specified `type` is emitted on the given event `target`. + * @param {Object} target + * Event target object. + * @param {String} type + * The type of the event. + * @param {Function} listener + * The listener function that processes the event. + */ +function once(target, type, listener) { + function replacement(...args) { + off(target, type, replacement); + onceWeakMap.delete(listener); + listener.apply(target, args); + }; + onceWeakMap.set(listener, replacement); + on(target, type, replacement); +} +// exports.once = once; + +/** + * Execute each of the listeners in order with the supplied arguments. + * All the exceptions that are thrown by listeners during the emit + * are caught and can be handled by listeners of 'error' event. Thrown + * exceptions are passed as an argument to an 'error' event listener. + * If no 'error' listener is registered exception will be logged into an + * error console. + * @param {Object} target + * Event target object. + * @param {String} type + * The type of event. + * @params {Object|Number|String|Boolean} args + * Arguments that will be passed to listeners. + */ +function emit (target, type, ...args) { + emitOnObject(target, type, target, ...args); +} +// exports.emit = emit; + +/** + * A variant of emit that allows setting the this property for event listeners + */ +function emitOnObject(target, type, thisArg, ...args) { + let allListeners = observers.get(target); + let listeners = allListeners.get(type); + + // If error event and there are no handlers (explicit or catch-all) + // then print error message to the console. + if (type === 'error' && !listeners.size && !allListeners.get('*').size) + console.exception(args[0]); + + let count = listenerCount; + for (let [listener, added] of listeners) + try { + // Since our contract unfortunately requires that we not dispatch to + // this event to listeners that were either added or removed during this + // dispatch, we need to check when each listener was added. + if (added >= count) + break; + listener.apply(thisArg, args); + } + catch (error) { + // If exception is not thrown by a error listener and error listener is + // registered emit `error` event. Otherwise dump exception to the console. + if (type !== 'error') + emitOnObject(target, 'error', target, error); + else + console.exception(error); + } + + // Also emit on `"*"` so that one could listen for all events. + if (type !== '*' && allListeners.get('*').size) + emitOnObject(target, '*', target, type, ...args); +} +// exports.emitOnObject = emitOnObject; + +/** + * Removes an event `listener` for the given event `type` on the given event + * `target`. If no `listener` is passed removes all listeners of the given + * `type`. If `type` is not passed removes all the listeners of the given + * event `target`. + * @param {Object} target + * The event target object. + * @param {String} type + * The type of event. + * @param {Function} listener + * The listener function that processes the event. + */ +function off(target, type, listener) { + let length = arguments.length; + if (length === 3) { + if (onceWeakMap.has(listener)) { + observers.get(target).get(type) + .delete(onceWeakMap.get(listener)); + onceWeakMap.delete(listener); + } + + observers.get(target).get(type).delete(listener); + } + else if (length === 2) { + observers.get(target).get(type).clear(); + observers.get(target).delete(type); + } + else if (length === 1) { + for (let listeners of observers.get(target).values()) + listeners.clear(); + observers.delete(target); + } +} +// exports.off = off; + +/** + * Returns a number of event listeners registered for the given event `type` + * on the given event `target`. + */ +function count(target, type) { + return observers.get(target).get(type).size; +} +// exports.count = count; + +/** + * Registers listeners on the given event `target` from the given `listeners` + * dictionary. Iterates over the listeners and if property name matches name + * pattern `onEventType` and property is a function, then registers it as + * an `eventType` listener on `target`. + * + * @param {Object} target + * The type of event. + * @param {Object} listeners + * Dictionary of listeners. + */ +function setListeners(target, listeners) { + Object.keys(listeners || {}).forEach(key => { + let match = EVENT_TYPE_PATTERN.exec(key); + let type = match && match[1].toLowerCase(); + if (!type) + return; + + let listener = listeners[key]; + if (typeof(listener) === 'function') + on(target, type, listener); + }); +} +// exports.setListeners = setListeners; \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/debugger/sdk/heritage.js b/native/cocos/scripting/js-bindings/script/debugger/sdk/heritage.js new file mode 100644 index 0000000000..6305ede3d4 --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/sdk/heritage.js @@ -0,0 +1,204 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +'use strict'; + +var getPrototypeOf = Object.getPrototypeOf; +function* getNames(x) { + yield* Object.getOwnPropertyNames(x); + yield* Object.getOwnPropertySymbols(x); +} +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var freeze = Object.freeze; + +// This shortcut makes sure that we do perform desired operations, even if +// associated methods have being overridden on the used object. +var hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); + +// Utility function to get own properties descriptor map. +function getOwnPropertyDescriptors(...objects) { + let descriptors = {}; + for (let object of objects) + for (let name of getNames(object)) + descriptors[name] = getOwnPropertyDescriptor(object, name); + return descriptors; +} + +function isDataProperty(property) { + var type = typeof(property.value); + return "value" in property && + type !== "function" && + (type !== "object" || property.value === null); +} + +function getDataProperties(object) { + var properties = getOwnPropertyDescriptors(object); + let result = {}; + for (let name of getNames(properties)) { + var property = properties[name]; + if (isDataProperty(property)) { + result[name] = { + value: property.value, + writable: true, + configurable: true, + enumerable: false + }; + } + } + return result; +} + +/** + * Takes `source` object as an argument and returns identical object + * with the difference that all own properties will be non-enumerable + */ +function obscure(source, prototype = getPrototypeOf(source)) { + let descriptors = {}; + for (let name of getNames(source)) { + let property = getOwnPropertyDescriptor(source, name); + property.enumerable = false; + descriptors[name] = property; + } + return Object.create(prototype, descriptors); +} +// exports.obscure = obscure; + +/** + * Takes arbitrary number of source objects and returns fresh one, that + * inherits from the same prototype as a first argument and implements all + * own properties of all argument objects. If two or more argument objects + * have own properties with the same name, the property is overridden, with + * precedence from right to left, implying, that properties of the object on + * the left are overridden by a same named property of the object on the right. + */ +var mix = function(...sources) { + return Object.create(getPrototypeOf(sources[0]), + getOwnPropertyDescriptors(...sources)); +}; +// exports.mix = mix; + +/** + * Returns a frozen object with that inherits from the given `prototype` and + * implements all own properties of the given `properties` object. + */ +function extend(prototype, properties) { + return Object.create(prototype, + getOwnPropertyDescriptors(properties)); +} +// exports.extend = extend; + +function prototypeOf(input) { + return typeof(input) === 'function' ? input.prototype : input; +} + +/** + * Returns a constructor function with a proper `prototype` setup. Returned + * constructor's `prototype` inherits from a given `options.extends` or + * `Class.prototype` if omitted and implements all the properties of the + * given `option`. If `options.implemens` array is passed, it's elements + * will be mixed into prototype as well. Also, `options.extends` can be + * a function or a prototype. If function than it's prototype is used as + * an ancestor of the prototype, if it's an object that it's used directly. + * Also `options.implements` may contain functions or objects, in case of + * functions their prototypes are used for mixing. + */ +function Class(options) { + // Create descriptor with normalized `options.extends` and + // `options.implements`. + var descriptor = { + // Normalize extends property of `options.extends` to a prototype object + // in case it's constructor. If property is missing that fallback to + // `Type.prototype`. + extends: hasOwnProperty(options, 'extends') ? + prototypeOf(options.extends) : Class.prototype, + + // Normalize `options.implements` to make sure that it's array of + // prototype objects instead of constructor functions. + implements: freeze(hasOwnProperty(options, 'implements') ? + options.implements.map(prototypeOf) : []), + }; + + // Create array of property descriptors who's properties will be defined + // on the resulting prototype. + var descriptors = [].concat(descriptor.implements, options, descriptor, + { constructor }); + + // Note: we use reflection `apply` in the constructor instead of method + // call since later may be overridden. + function constructor() { + var instance = Object.create(prototype, attributes); + if (initialize) + Reflect.apply(initialize, instance, arguments); + return instance; + } + // Create `prototype` that inherits from given ancestor passed as + // `options.extends`, falling back to `Type.prototype`, implementing all + // properties of given `options.implements` and `options` itself. + var prototype = Object.create(descriptor.extends, + getOwnPropertyDescriptors(...descriptors)); + var initialize = prototype.initialize; + + // Combine ancestor attributes with prototype's attributes so that + // ancestors attributes also become initializeable. + var attributes = mix(descriptor.extends.constructor.attributes || {}, + getDataProperties(prototype)); + + constructor.attributes = attributes; + Object.defineProperty(constructor, 'prototype', { + configurable: false, + writable: false, + value: prototype + }); + return constructor; +} +Class.prototype = obscure({ + constructor: function constructor() { + this.initialize.apply(this, arguments); + return this; + }, + initialize: function initialize() { + // Do your initialization logic here + }, + // Copy useful properties from `Object.prototype`. + toString: Object.prototype.toString, + toLocaleString: Object.prototype.toLocaleString, + toSource: Object.prototype.toSource, + valueOf: Object.prototype.valueOf, + isPrototypeOf: Object.prototype.isPrototypeOf +}, null); + +// From sdk/land/functional/helpers.js + +const arity = f => f.arity || f.length; +const name = f => f.displayName || f.name; +const derive = (f, source) => { + f.displayName = name(source); + f.arity = arity(source); + return f; +}; + +// From sdk/land/functional/core.js + +/** + * Takes variadic numeber of functions and returns composed one. + * Returned function pushes `this` pseudo-variable to the head + * of the passed arguments and invokes all the functions from + * left to right passing same arguments to them. Composite function + * returns return value of the right most funciton. + */ +const _method = (...lambdas) => { + return function method(...args) { + args.unshift(this); + return lambdas.reduce((_, lambda) => lambda.apply(this, args), + void(0)); + }; +}; + +/* + * Takes a funtion and returns a wrapped function that returns `this` + */ +const chainable = f => derive(function(...args) { + f.apply(this, args); + return this; +}, f); + diff --git a/native/cocos/scripting/js-bindings/script/debugger/sdk/object.js b/native/cocos/scripting/js-bindings/script/debugger/sdk/object.js new file mode 100644 index 0000000000..c8912796ec --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/sdk/object.js @@ -0,0 +1,136 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +"use strict"; + +// Create a shortcut for Array.prototype.slice.call(). +const unbind = Function.call.bind(Function.bind, Function.call); +const slice = unbind(Array.prototype.slice); + +class DefaultWeakMap extends WeakMap { + constructor(createItem, items = undefined) { + super(items); + + this.createItem = createItem; + } + + get(key) { + if (!this.has(key)) { + this.set(key, this.createItem(key)); + } + + return super.get(key); + } +} + +class DefaultMap extends Map { + constructor(createItem, items = undefined) { + super(items); + + this.createItem = createItem; + } + + get(key) { + if (!this.has(key)) { + this.set(key, this.createItem(key)); + } + + return super.get(key); + } +} + +// Object.assign(exports, {DefaultMap, DefaultWeakMap}); + +/** + * Merges all the properties of all arguments into first argument. If two or + * more argument objects have own properties with the same name, the property + * is overridden, with precedence from right to left, implying, that properties + * of the object on the left are overridden by a same named property of the + * object on the right. + * + * Any argument given with "falsy" value - commonly `null` and `undefined` in + * case of objects - are skipped. + * + * @examples + * var a = { bar: 0, a: 'a' } + * var b = merge(a, { foo: 'foo', bar: 1 }, { foo: 'bar', name: 'b' }); + * b === a // true + * b.a // 'a' + * b.foo // 'bar' + * b.bar // 1 + * b.name // 'b' + */ +function merge(source) { + let descriptor = {}; + + // `Boolean` converts the first parameter to a boolean value. Any object is + // converted to `true` where `null` and `undefined` becames `false`. Therefore + // the `filter` method will keep only objects that are defined and not null. + slice(arguments, 1).filter(Boolean).forEach(function onEach(properties) { + getOwnPropertyIdentifiers(properties).forEach(function(name) { + descriptor[name] = Object.getOwnPropertyDescriptor(properties, name); + }); + }); + return Object.defineProperties(source, descriptor); +} +// exports.merge = merge; + +/** + * Returns an object that inherits from the first argument and contains all the + * properties from all following arguments. + * `extend(source1, source2, source3)` is equivalent of + * `merge(Object.create(source1), source2, source3)`. + */ +function extend(source) { + let rest = slice(arguments, 1); + rest.unshift(Object.create(source)); + return merge.apply(null, rest); +} +// exports.extend = extend; + +function has(obj, key) { + return obj.hasOwnProperty(key); +} +// exports.has = has; + +function each(obj, fn) { + for (let key in obj) has(obj, key) && fn(obj[key], key, obj); +} +// exports.each = each; + +/** + * Like `merge`, except no property descriptors are manipulated, for use + * with platform objects. Identical to underscore's `extend`. Useful for + * merging XPCOM objects + */ +function safeMerge(source) { + slice(arguments, 1).forEach(function onEach (obj) { + for (let prop in obj) source[prop] = obj[prop]; + }); + return source; +} +// exports.safeMerge = safeMerge; + +/* + * Returns a copy of the object without omitted properties + */ +function omit(source, ...values) { + let copy = {}; + let keys = flatten(values); + for (let prop in source) + if (!~keys.indexOf(prop)) + copy[prop] = source[prop]; + return copy; +} +// exports.omit = omit; + +// get object's own property Symbols and/or Names, including nonEnumerables by default +function getOwnPropertyIdentifiers(object, options = { names: true, symbols: true, nonEnumerables: true }) { + const symbols = !options.symbols ? [] : + Object.getOwnPropertySymbols(object); + const names = !options.names ? [] : + options.nonEnumerables ? Object.getOwnPropertyNames(object) : + Object.keys(object); + return [...names, ...symbols]; +} +// exports.getOwnPropertyIdentifiers = getOwnPropertyIdentifiers; \ No newline at end of file diff --git a/native/cocos/scripting/js-bindings/script/debugger/sdk/target.js b/native/cocos/scripting/js-bindings/script/debugger/sdk/target.js new file mode 100644 index 0000000000..16058bca02 --- /dev/null +++ b/native/cocos/scripting/js-bindings/script/debugger/sdk/target.js @@ -0,0 +1,60 @@ +/** + * `EventTarget` is an exemplar for creating an objects that can be used to + * add / remove event listeners on them. Events on these objects may be emitted + * via `emit` function exported by 'event/core' module. + */ +const EventTarget = Class({ + /** + * Method initializes `this` event source. It goes through properties of a + * given `options` and registers listeners for the ones that look like an + * event listeners. + */ + /** + * Method initializes `this` event source. It goes through properties of a + * given `options` and registers listeners for the ones that look like an + * event listeners. + */ + initialize: function initialize(options) { + setListeners(this, options); + }, + /** + * Registers an event `listener` that is called every time events of + * specified `type` are emitted. + * @param {String} type + * The type of event. + * @param {Function} listener + * The listener function that processes the event. + * @example + * worker.on('message', function (data) { + * console.log('data received: ' + data) + * }) + */ + on: chainable(_method(on)), + /** + * Registers an event `listener` that is called once the next time an event + * of the specified `type` is emitted. + * @param {String} type + * The type of the event. + * @param {Function} listener + * The listener function that processes the event. + */ + once: chainable(_method(once)), + /** + * Removes an event `listener` for the given event `type`. + * @param {String} type + * The type of event. + * @param {Function} listener + * The listener function that processes the event. + */ + removeListener: function removeListener(type, listener) { + // Note: We can't just wrap `off` in `method` as we do it for other methods + // cause skipping a second or third argument will behave very differently + // than intended. This way we make sure all arguments are passed and only + // one listener is removed at most. + off(this, type, listener); + return this; + }, + // but we can wrap `off` here, as the semantics are the same + off: chainable(_method(off)) + +}); diff --git a/native/cocos/scripting/js-bindings/script/debugger/transport.js b/native/cocos/scripting/js-bindings/script/debugger/transport.js index 639a501a2c..fe59045500 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/transport.js +++ b/native/cocos/scripting/js-bindings/script/debugger/transport.js @@ -146,6 +146,7 @@ function DebuggerTransport(input, output) { let data = JSON.stringify(object); let data_for_len = DevToolsUtils.utf16to8(data); this._outgoing = data_for_len.length + ':' + data; + log("<<<<<<<<<< " + this._outgoing); this._flushOutgoing(); }, @@ -602,7 +603,7 @@ function DebuggerTransport(input, output) { dumpn("Sent bulk packet " + serial + " for actor " + actor); if (!this.other) { let error = new Error("startBulkSend: other side of transport missing"); - return promise.reject(error); + return Promise.reject(error); } let pipe = new Pipe(true, true, 0, 0, null); @@ -614,7 +615,7 @@ function DebuggerTransport(input, output) { } // Receiver - let deferred = promise.defer(); + let deferred = Promise.defer(); let packet = { actor: actor, type: type, @@ -637,12 +638,12 @@ function DebuggerTransport(input, output) { }, "LocalDebuggerTransport instance's this.other.hooks.onBulkPacket")); // Sender - let sendDeferred = promise.defer(); + let sendDeferred = Promise.defer(); // The remote transport is not capable of resolving immediately here, so we // shouldn't be able to either. DevToolsUtils.executeSoon(() => { - let copyDeferred = promise.defer(); + let copyDeferred = Promise.defer(); sendDeferred.resolve({ copyFrom: (input) => { diff --git a/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js b/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js index 8acbf6f4f6..e9b20c1a3c 100755 --- a/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js +++ b/native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js @@ -1,39 +1,26 @@ -/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft= javascript ts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; - -// const {Cc, Ci, Cu, components} = require("chrome"); -// const {isWindowIncluded} = require("devtools/toolkit/layout/utils"); - -// Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -// loader.lazyImporter(this, "Services", "resource://gre/modules/Services.jsm"); - -// TODO: Bug 842672 - browser/ imports modules from toolkit/. -// Note that these are only used in WebConsoleCommands, see $0 and pprint(). -// loader.lazyImporter(this, "VariablesView", "resource:///modules/devtools/VariablesView.jsm"); -// const DevToolsUtils = require("devtools/toolkit/DevToolsUtils"); - -// Match the function name from the result of toString() or toSource(). -// -// Examples: -// (function foobar(a, b) { ... -// function foobar2(a) { ... -// function() { ... - -var exports = exports || {}; - - -const REGEX_MATCH_FUNCTION_NAME = /^\(?function\s+([^(\s]+)\s*\(/; - -// Number of terminal entries for the self-xss prevention to go away -const CONSOLE_ENTRY_THRESHOLD = 5; - -const CONSOLE_WORKER_IDS = exports.CONSOLE_WORKER_IDS = [ + "use strict"; + + //const {Cc, Ci, Cu, components} = require("chrome"); + //const {isWindowIncluded} = require("devtools/shared/layout/utils"); + //const Services = require("Services"); + //const {XPCOMUtils} = require("resource://gre/modules/XPCOMUtils.jsm"); + + // TODO: Bug 842672 - browser/ imports modules from toolkit/. + // Note that these are only used in WebConsoleCommands, see $0 and pprint(). + //loader.lazyImporter(this, "VariablesView", "resource://devtools/client/shared/widgets/VariablesView.jsm"); + + //XPCOMUtils.defineLazyServiceGetter(this, + // "swm", + // "@mozilla.org/serviceworkers/manager;1", + // "nsIServiceWorkerManager"); + +const CONSOLE_WORKER_IDS = [ "SharedWorker", "ServiceWorker", "Worker" @@ -42,16 +29,14 @@ const CONSOLE_WORKER_IDS = exports.CONSOLE_WORKER_IDS = [ var WebConsoleUtils = { /** - * Wrap a string in an nsISupportsString object. + * Given a message, return one of CONSOLE_WORKER_IDS if it matches + * one of those. * - * @param string string - * @return nsISupportsString + * @return string */ - supportsString: function (string) { - let str = Cc["@mozilla.org/supports-string;1"] - .createInstance(Ci.nsISupportsString); - str.data = string; - return str; + getWorkerType: function (message) { + let id = message ? message.innerID : null; + return CONSOLE_WORKER_IDS[CONSOLE_WORKER_IDS.indexOf(id)] || null; }, /** @@ -99,20 +84,76 @@ var WebConsoleUtils = { }, /** - * Copies certain style attributes from one element to another. + * Gets the ID of the inner window of this DOM window. * - * @param nsIDOMNode from - * The target node. - * @param nsIDOMNode to - * The destination node. + * @param nsIDOMWindow window + * @return integer + * Inner ID for the given window. */ - copyTextStyles: function (from, to) { - let win = from.ownerDocument.defaultView; - let style = win.getComputedStyle(from); - to.style.fontFamily = style.getPropertyCSSValue("font-family").cssText; - to.style.fontSize = style.getPropertyCSSValue("font-size").cssText; - to.style.fontWeight = style.getPropertyCSSValue("font-weight").cssText; - to.style.fontStyle = style.getPropertyCSSValue("font-style").cssText; + getInnerWindowId: function (window) { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID; + }, + + /** + * Recursively gather a list of inner window ids given a + * top level window. + * + * @param nsIDOMWindow window + * @return Array + * list of inner window ids. + */ + getInnerWindowIDsForFrames: function (window) { + let innerWindowID = this.getInnerWindowId(window); + let ids = [innerWindowID]; + + if (window.frames) { + for (let i = 0; i < window.frames.length; i++) { + let frame = window.frames[i]; + ids = ids.concat(this.getInnerWindowIDsForFrames(frame)); + } + } + + return ids; + }, + + /** + * Get the property descriptor for the given object. + * + * @param object object + * The object that contains the property. + * @param string prop + * The property you want to get the descriptor for. + * @return object + * Property descriptor. + */ + getPropertyDescriptor: function (object, prop) { + let desc = null; + while (object) { + try { + if ((desc = Object.getOwnPropertyDescriptor(object, prop))) { + break; + } + } catch (ex) { + // Native getters throw here. See bug 520882. + // null throws TypeError. + if (ex.name != "NS_ERROR_XPC_BAD_CONVERT_JS" && + ex.name != "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO" && + ex.name != "TypeError") { + throw ex; + } + } + + try { + object = Object.getPrototypeOf(object); + } catch (ex) { + if (ex.name == "TypeError") { + return desc; + } + throw ex; + } + } + return desc; }, /** @@ -160,250 +201,863 @@ var WebConsoleUtils = { return null; } }, +}; + +// exports.Utils = WebConsoleUtils; + +// The page errors listener + +/** + * The nsIConsoleService listener. This is used to send all of the console + * messages (JavaScript, CSS and more) to the remote Web Console instance. + * + * @constructor + * @param nsIDOMWindow [window] + * Optional - the window object for which we are created. This is used + * for filtering out messages that belong to other windows. + * @param object listener + * The listener object must have one method: + * - onConsoleServiceMessage(). This method is invoked with one argument, + * the nsIConsoleMessage, whenever a relevant message is received. + */ +function ConsoleServiceListener(window, listener) { + this.window = window; + this.listener = listener; +} +// exports.ConsoleServiceListener = ConsoleServiceListener; + +ConsoleServiceListener.prototype = +{ +// QueryInterface: XPCOMUtils.generateQI([Ci.nsIConsoleListener]), /** - * Determine if the given request mixes HTTP with HTTPS content. - * - * @param string request - * Location of the requested content. - * @param string location - * Location of the current page. - * @return boolean - * True if the content is mixed, false if not. + * The content window for which we listen to page errors. + * @type nsIDOMWindow */ - isMixedHTTPSRequest: function (request, location) { - try { - let requestURI = Services.io.newURI(request, null, null); - let contentURI = Services.io.newURI(location, null, null); - return (contentURI.scheme == "https" && requestURI.scheme != "https"); - } catch (ex) { + window: null, + + /** + * The listener object which is notified of messages from the console service. + * @type object + */ + listener: null, + + /** + * Initialize the nsIConsoleService listener. + */ + init: function () { + Services.console.registerListener(this); + }, + + /** + * The nsIConsoleService observer. This method takes all the script error + * messages belonging to the current window and sends them to the remote Web + * Console instance. + * + * @param nsIConsoleMessage message + * The message object coming from the nsIConsoleService. + */ + observe: function (message) { + if (!this.listener) { + return; + } + + if (this.window) { + if (!(message instanceof Ci.nsIScriptError) || + !message.outerWindowID || + !this.isCategoryAllowed(message.category)) { + return; + } + + let errorWindow = Services.wm.getOuterWindowWithId(message.outerWindowID); + if (!errorWindow || !isWindowIncluded(this.window, errorWindow)) { + return; + } + } + + this.listener.onConsoleServiceMessage(message); + }, + + /** + * Check if the given message category is allowed to be tracked or not. + * We ignore chrome-originating errors as we only care about content. + * + * @param string category + * The message category you want to check. + * @return boolean + * True if the category is allowed to be logged, false otherwise. + */ + isCategoryAllowed: function (category) { + if (!category) { return false; } + + switch (category) { + case "XPConnect JavaScript": + case "component javascript": + case "chrome javascript": + case "chrome registration": + case "XBL": + case "XBL Prototype Handler": + case "XBL Content Sink": + case "xbl javascript": + return false; + } + + return true; }, /** - * Helper function to deduce the name of the provided function. + * Get the cached page errors for the current inner window and its (i)frames. * - * @param funtion function - * The function whose name will be returned. - * @return string - * Function name. + * @param boolean [includePrivate=false] + * Tells if you want to also retrieve messages coming from private + * windows. Defaults to false. + * @return array + * The array of cached messages. Each element is an nsIScriptError or + * an nsIConsoleMessage */ - getFunctionName: function (func) { - let name = null; - if (func.name) { - name = func.name; - } else { - let desc; - try { - desc = func.getOwnPropertyDescriptor("displayName"); - } catch (ex) { - // Ignore. - } - if (desc && typeof desc.value == "string") { - name = desc.value; - } - } - if (!name) { - try { - let str = (func.toString() || func.toSource()) + ""; - name = (str.match(REGEX_MATCH_FUNCTION_NAME) || [])[1]; - } catch (ex) { - // Ignore. - } - } - return name; - }, + getCachedMessages: function (includePrivate = false) { + let errors = Services.console.getMessageArray() || []; - /** - * Get the object class name. For example, the |window| object has the Window - * class name (based on [object Window]). - * - * @param object object - * The object you want to get the class name for. - * @return string - * The object class name. - */ - getObjectClassName: function (object) { - if (object === null) { - return "null"; - } - if (object === undefined) { - return "undefined"; - } + // if !this.window, we're in a browser console. Still need to filter + // private messages. + if (!this.window) { + return errors.filter((error) => { + if (error instanceof Ci.nsIScriptError) { + if (!includePrivate && error.isFromPrivateWindow) { + return false; + } + } - let type = typeof object; - if (type != "object") { - // Grip class names should start with an uppercase letter. - return type.charAt(0).toUpperCase() + type.substr(1); - } - - let className; - - try { - className = ((object + "").match(/^\[object (\S+)\]$/) || [])[1]; - if (!className) { - className = ((object.constructor + "") - .match(/^\[object (\S+)\]$/) || [])[1]; - } - if (!className && typeof object.constructor == "function") { - className = this.getFunctionName(object.constructor); - } - } catch (ex) { - // Ignore. - } - - return className; - }, - - /** - * Check if the given value is a grip with an actor. - * - * @param mixed grip - * Value you want to check if it is a grip with an actor. - * @return boolean - * True if the given value is a grip with an actor. - */ - isActorGrip: function (grip) { - return grip && typeof (grip) == "object" && grip.actor; - }, - /** - * Value of devtools.selfxss.count preference - * - * @type number - * @private - */ - _usageCount: 0, - get usageCount() { - if (WebConsoleUtils._usageCount < CONSOLE_ENTRY_THRESHOLD) { - WebConsoleUtils._usageCount = - Services.prefs.getIntPref("devtools.selfxss.count"); - if (Services.prefs.getBoolPref("devtools.chrome.enabled")) { - WebConsoleUtils.usageCount = CONSOLE_ENTRY_THRESHOLD; - } - } - return WebConsoleUtils._usageCount; - }, - set usageCount(newUC) { - if (newUC <= CONSOLE_ENTRY_THRESHOLD) { - WebConsoleUtils._usageCount = newUC; - Services.prefs.setIntPref("devtools.selfxss.count", newUC); - } - }, - /** - * The inputNode "paste" event handler generator. Helps prevent - * self-xss attacks - * - * @param nsIDOMElement inputField - * @param nsIDOMElement notificationBox - * @returns A function to be added as a handler to 'paste' and - *'drop' events on the input field - */ - pasteHandlerGen: function (inputField, notificationBox, msg, okstring) { - let handler = function (event) { - if (WebConsoleUtils.usageCount >= CONSOLE_ENTRY_THRESHOLD) { - inputField.removeEventListener("paste", handler); - inputField.removeEventListener("drop", handler); return true; - } - if (notificationBox.getNotificationWithValue("selfxss-notification")) { - event.preventDefault(); - event.stopPropagation(); + }); + } + + let ids = WebConsoleUtils.getInnerWindowIDsForFrames(this.window); + + return errors.filter((error) => { + if (error instanceof Ci.nsIScriptError) { + if (!includePrivate && error.isFromPrivateWindow) { + return false; + } + if (ids && + (ids.indexOf(error.innerWindowID) == -1 || + !this.isCategoryAllowed(error.category))) { + return false; + } + } else if (ids && ids[0]) { + // If this is not an nsIScriptError and we need to do window-based + // filtering we skip this message. return false; } + return true; + }); + }, - let notification = notificationBox.appendNotification(msg, - "selfxss-notification", null, - notificationBox.PRIORITY_WARNING_HIGH, null, - function (eventType) { - // Cleanup function if notification is dismissed - if (eventType == "removed") { - inputField.removeEventListener("keyup", pasteKeyUpHandler); - } - }); + /** + * Remove the nsIConsoleService listener. + */ + destroy: function () { + Services.console.unregisterListener(this); + this.listener = this.window = null; + }, +}; - function pasteKeyUpHandler(event2) { - let value = inputField.value || inputField.textContent; - if (value.includes(okstring)) { - notificationBox.removeNotification(notification); - inputField.removeEventListener("keyup", pasteKeyUpHandler); - WebConsoleUtils.usageCount = CONSOLE_ENTRY_THRESHOLD; - } +// The window.console API observer + +/** + * The window.console API observer. This allows the window.console API messages + * to be sent to the remote Web Console instance. + * + * @constructor + * @param nsIDOMWindow window + * Optional - the window object for which we are created. This is used + * for filtering out messages that belong to other windows. + * @param object owner + * The owner object must have the following methods: + * - onConsoleAPICall(). This method is invoked with one argument, the + * Console API message that comes from the observer service, whenever + * a relevant console API call is received. + * @param object filteringOptions + * Optional - The filteringOptions that this listener should listen to: + * - addonId: filter console messages based on the addonId. + */ +function ConsoleAPIListener(window, owner, {addonId} = {}) { + this.window = window; + this.owner = owner; + this.addonId = addonId; +} +// exports.ConsoleAPIListener = ConsoleAPIListener; + +ConsoleAPIListener.prototype = +{ +// QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), + + /** + * The content window for which we listen to window.console API calls. + * @type nsIDOMWindow + */ + window: null, + + /** + * The owner object which is notified of window.console API calls. It must + * have a onConsoleAPICall method which is invoked with one argument: the + * console API call object that comes from the observer service. + * + * @type object + * @see WebConsoleActor + */ + owner: null, + + /** + * The addonId that we listen for. If not null then only messages from this + * console will be returned. + */ + addonId: null, + + /** + * Initialize the window.console API observer. + */ + init: function () { + // Note that the observer is process-wide. We will filter the messages as + // needed, see CAL_observe(). +// Services.obs.addObserver(this, "console-api-log-event", false); + }, + + /** + * The console API message observer. When messages are received from the + * observer service we forward them to the remote Web Console instance. + * + * @param object message + * The message object receives from the observer service. + * @param string topic + * The message topic received from the observer service. + */ + observe: function (message, topic) { + if (!this.owner) { + return; + } + + // Here, wrappedJSObject is not a security wrapper but a property defined + // by the XPCOM component which allows us to unwrap the XPCOM interface and + // access the underlying JSObject. + let apiMessage = message.wrappedJSObject; + + if (!this.isMessageRelevant(apiMessage)) { + return; + } + + this.owner.onConsoleAPICall(apiMessage); + }, + + /** + * Given a message, return true if this window should show it and false + * if it should be ignored. + * + * @param message + * The message from the Storage Service + * @return bool + * Do we care about this message? + */ + isMessageRelevant: function (message) { + let workerType = WebConsoleUtils.getWorkerType(message); + + if (this.window && workerType === "ServiceWorker") { + // For messages from Service Workers, message.ID is the + // scope, which can be used to determine whether it's controlling + // a window. + let scope = message.ID; + + if (!swm.shouldReportToWindow(this.window, scope)) { + return false; + } + } + + if (this.window && !workerType) { + let msgWindow = Services.wm.getCurrentInnerWindowWithId(message.innerID); + if (!msgWindow || !isWindowIncluded(this.window, msgWindow)) { + // Not the same window! + return false; + } + } + + if (this.addonId) { + // ConsoleAPI.jsm messages contains a consoleID, (and it is currently + // used in Addon SDK add-ons), the standard 'console' object + // (which is used in regular webpages and in WebExtensions pages) + // contains the originAttributes of the source document principal. + + // Filtering based on the originAttributes used by + // the Console API object. + if (message.originAttributes && + message.originAttributes.addonId == this.addonId) { + return true; + } + + // Filtering based on the old-style consoleID property used by + // the legacy Console JSM module. + if (message.consoleID && message.consoleID == `addon/${this.addonId}`) { + return true; } - inputField.addEventListener("keyup", pasteKeyUpHandler); - event.preventDefault(); - event.stopPropagation(); return false; + } + + return true; + }, + + /** + * Get the cached messages for the current inner window and its (i)frames. + * + * @param boolean [includePrivate=false] + * Tells if you want to also retrieve messages coming from private + * windows. Defaults to false. + * @return array + * The array of cached messages. + */ + getCachedMessages: function (includePrivate = false) { + let messages = []; +// let ConsoleAPIStorage = Cc["@mozilla.org/consoleAPI-storage;1"] +// .getService(Ci.nsIConsoleAPIStorage); + + // if !this.window, we're in a browser console. Retrieve all events + // for filtering based on privacy. +// if (!this.window) { +// messages = ConsoleAPIStorage.getEvents(); +// } else { +// let ids = WebConsoleUtils.getInnerWindowIDsForFrames(this.window); +// ids.forEach((id) => { +// messages = messages.concat(ConsoleAPIStorage.getEvents(id)); +// }); +// } +// +// CONSOLE_WORKER_IDS.forEach((id) => { +// messages = messages.concat(ConsoleAPIStorage.getEvents(id)); +// }); + + messages = messages.filter(msg => { + return this.isMessageRelevant(msg); + }); + + if (includePrivate) { + return messages; + } + + return messages.filter((m) => !m.private); + }, + + /** + * Destroy the console API listener. + */ + destroy: function () { +// Services.obs.removeObserver(this, "console-api-log-event"); + this.window = this.owner = null; + }, +}; + +/** + * WebConsole commands manager. + * + * Defines a set of functions /variables ("commands") that are available from + * the Web Console but not from the web page. + * + */ +var WebConsoleCommands = { + _registeredCommands: new Map(), + _originalCommands: new Map(), + + /** + * @private + * Reserved for built-in commands. To register a command from the code of an + * add-on, see WebConsoleCommands.register instead. + * + * @see WebConsoleCommands.register + */ + _registerOriginal: function (name, command) { + this.register(name, command); + this._originalCommands.set(name, this.getCommand(name)); + }, + + /** + * Register a new command. + * @param {string} name The command name (exemple: "$") + * @param {(function|object)} command The command to register. + * It can be a function so the command is a function (like "$()"), + * or it can also be a property descriptor to describe a getter / value (like + * "$0"). + * + * The command function or the command getter are passed a owner object as + * their first parameter (see the example below). + * + * Note that setters don't work currently and "enumerable" and "configurable" + * are forced to true. + * + * @example + * + * WebConsoleCommands.register("$", function JSTH_$(owner, selector) + * { + * return owner.window.document.querySelector(selector); + * }); + * + * WebConsoleCommands.register("$0", { + * get: function(owner) { + * return owner.makeDebuggeeValue(owner.selectedNode); + * } + * }); + */ + register: function (name, command) { + this._registeredCommands.set(name, command); + }, + + /** + * Unregister a command. + * + * If the command being unregister overrode a built-in command, + * the latter is restored. + * + * @param {string} name The name of the command + */ + unregister: function (name) { + this._registeredCommands.delete(name); + if (this._originalCommands.has(name)) { + this.register(name, this._originalCommands.get(name)); + } + }, + + /** + * Returns a command by its name. + * + * @param {string} name The name of the command. + * + * @return {(function|object)} The command. + */ + getCommand: function (name) { + return this._registeredCommands.get(name); + }, + + /** + * Returns true if a command is registered with the given name. + * + * @param {string} name The name of the command. + * + * @return {boolean} True if the command is registered. + */ + hasCommand: function (name) { + return this._registeredCommands.has(name); + }, +}; + +// exports.WebConsoleCommands = WebConsoleCommands; + +/* + * Built-in commands. + * + * A list of helper functions used by Firebug can be found here: + * http://getfirebug.com/wiki/index.php/Command_Line_API + */ + +/** + * Find a node by ID. + * + * @param string id + * The ID of the element you want. + * @return nsIDOMNode or null + * The result of calling document.querySelector(selector). + */ +WebConsoleCommands._registerOriginal("$", function (owner, selector) { + return owner.window.document.querySelector(selector); +}); + +/** + * Find the nodes matching a CSS selector. + * + * @param string selector + * A string that is passed to window.document.querySelectorAll. + * @return nsIDOMNodeList + * Returns the result of document.querySelectorAll(selector). + */ +WebConsoleCommands._registerOriginal("$$", function (owner, selector) { + let nodes = owner.window.document.querySelectorAll(selector); + + // Calling owner.window.Array.from() doesn't work without accessing the + // wrappedJSObject, so just loop through the results instead. + let result = new owner.window.Array(); + for (let i = 0; i < nodes.length; i++) { + result.push(nodes[i]); + } + return result; +}); + +/** + * Returns the result of the last console input evaluation + * + * @return object|undefined + * Returns last console evaluation or undefined + */ +WebConsoleCommands._registerOriginal("$_", { + get: function (owner) { + return owner.consoleActor.getLastConsoleInputEvaluation(); + } +}); + +/** + * Runs an xPath query and returns all matched nodes. + * + * @param string xPath + * xPath search query to execute. + * @param [optional] nsIDOMNode context + * Context to run the xPath query on. Uses window.document if not set. + * @return array of nsIDOMNode + */ +WebConsoleCommands._registerOriginal("$x", function (owner, xPath, context) { + let nodes = new owner.window.Array(); + + // Not waiving Xrays, since we want the original Document.evaluate function, + // instead of anything that's been redefined. + let doc = owner.window.document; + context = context || doc; + + let results = doc.evaluate(xPath, context, null, + Ci.nsIDOMXPathResult.ANY_TYPE, null); + let node; + while ((node = results.iterateNext())) { + nodes.push(node); + } + + return nodes; +}); + +/** + * Returns the currently selected object in the highlighter. + * + * @return Object representing the current selection in the + * Inspector, or null if no selection exists. + */ +WebConsoleCommands._registerOriginal("$0", { + get: function (owner) { + return owner.makeDebuggeeValue(owner.selectedNode); + } +}); + +/** + * Clears the output of the WebConsole. + */ +WebConsoleCommands._registerOriginal("clear", function (owner) { + owner.helperResult = { + type: "clearOutput", + }; +}); + +/** + * Clears the input history of the WebConsole. + */ +WebConsoleCommands._registerOriginal("clearHistory", function (owner) { + owner.helperResult = { + type: "clearHistory", + }; +}); + +/** + * Returns the result of Object.keys(object). + * + * @param object object + * Object to return the property names from. + * @return array of strings + */ +WebConsoleCommands._registerOriginal("keys", function (owner, object) { + // Need to waive Xrays so we can iterate functions and accessor properties + return Cu.cloneInto(Object.keys(Cu.waiveXrays(object)), owner.window); +}); + +/** + * Returns the values of all properties on object. + * + * @param object object + * Object to display the values from. + * @return array of string + */ +WebConsoleCommands._registerOriginal("values", function (owner, object) { + let values = []; + // Need to waive Xrays so we can iterate functions and accessor properties + let waived = Cu.waiveXrays(object); + let names = Object.getOwnPropertyNames(waived); + + for (let name of names) { + values.push(waived[name]); + } + + return Cu.cloneInto(values, owner.window); +}); + +/** + * Opens a help window in MDN. + */ +WebConsoleCommands._registerOriginal("help", function (owner) { + owner.helperResult = { type: "help" }; +}); + +/** + * Change the JS evaluation scope. + * + * @param DOMElement|string|window window + * The window object to use for eval scope. This can be a string that + * is used to perform document.querySelector(), to find the iframe that + * you want to cd() to. A DOMElement can be given as well, the + * .contentWindow property is used. Lastly, you can directly pass + * a window object. If you call cd() with no arguments, the current + * eval scope is cleared back to its default (the top window). + */ +WebConsoleCommands._registerOriginal("cd", function (owner, window) { + if (!window) { + owner.consoleActor.evalWindow = null; + owner.helperResult = { type: "cd" }; + return; + } + + if (typeof window == "string") { + window = owner.window.document.querySelector(window); + } + if (window instanceof Ci.nsIDOMElement && window.contentWindow) { + window = window.contentWindow; + } + if (!(window instanceof Ci.nsIDOMWindow)) { + owner.helperResult = { + type: "error", + message: "cdFunctionInvalidArgument" }; - return handler; - }, + return; + } + owner.consoleActor.evalWindow = window; + owner.helperResult = { type: "cd" }; +}); -}; +/** + * Inspects the passed object. This is done by opening the PropertyPanel. + * + * @param object object + * Object to inspect. + */ +WebConsoleCommands._registerOriginal("inspect", function (owner, object) { + let dbgObj = owner.makeDebuggeeValue(object); + let grip = owner.createValueGrip(dbgObj); + owner.helperResult = { + type: "inspectObject", + input: owner.evalInput, + object: grip, + }; +}); -exports.Utils = WebConsoleUtils; +/** + * Prints object to the output. + * + * @param object object + * Object to print to the output. + * @return string + */ +WebConsoleCommands._registerOriginal("pprint", function (owner, object) { + if (object === null || object === undefined || object === true || + object === false) { + owner.helperResult = { + type: "error", + message: "helperFuncUnsupportedTypeError", + }; + return null; + } -// Localization + owner.helperResult = { rawOutput: true }; -WebConsoleUtils.L10n = function (bundleURI) { - this._helper = new LocalizationHelper(bundleURI); -}; + if (typeof object == "function") { + return object + "\n"; + } -WebConsoleUtils.L10n.prototype = { - /** - * Generates a formatted timestamp string for displaying in console messages. - * - * @param integer [milliseconds] - * Optional, allows you to specify the timestamp in milliseconds since - * the UNIX epoch. - * @return string - * The timestamp formatted for display. - */ - timestampString: function (milliseconds) { - let d = new Date(milliseconds ? milliseconds : null); - let hours = d.getHours(), minutes = d.getMinutes(); - let seconds = d.getSeconds(); - milliseconds = d.getMilliseconds(); - let parameters = [hours, minutes, seconds, milliseconds]; - return this.getFormatStr("timestampFormat", parameters); - }, + let output = []; - /** - * Retrieve a localized string. - * - * @param string name - * The string name you want from the Web Console string bundle. - * @return string - * The localized string. - */ - getStr: function (name) { - try { - return this._helper.getStr(name); - } catch (ex) { - console.error("Failed to get string: " + name); - throw ex; + let obj = object; + for (let name in obj) { + let desc = WebConsoleUtils.getPropertyDescriptor(obj, name) || {}; + if (desc.get || desc.set) { + // TODO: Bug 842672 - toolkit/ imports modules from browser/. + let getGrip = VariablesView.getGrip(desc.get); + let setGrip = VariablesView.getGrip(desc.set); + let getString = VariablesView.getString(getGrip); + let setString = VariablesView.getString(setGrip); + output.push(name + ":", " get: " + getString, " set: " + setString); + } else { + let valueGrip = VariablesView.getGrip(obj[name]); + let valueString = VariablesView.getString(valueGrip); + output.push(name + ": " + valueString); } + } + + return " " + output.join("\n "); +}); + +/** + * Print the String representation of a value to the output, as-is. + * + * @param any value + * A value you want to output as a string. + * @return void + */ +WebConsoleCommands._registerOriginal("print", function (owner, value) { + owner.helperResult = { rawOutput: true }; + if (typeof value === "symbol") { + return Symbol.prototype.toString.call(value); + } + // Waiving Xrays here allows us to see a closer representation of the + // underlying object. This may execute arbitrary content code, but that + // code will run with content privileges, and the result will be rendered + // inert by coercing it to a String. + return String(Cu.waiveXrays(value)); +}); + +/** + * Copy the String representation of a value to the clipboard. + * + * @param any value + * A value you want to copy as a string. + * @return void + */ +WebConsoleCommands._registerOriginal("copy", function (owner, value) { + let payload; + try { + if (value instanceof Ci.nsIDOMElement) { + payload = value.outerHTML; + } else if (typeof value == "string") { + payload = value; + } else { + payload = JSON.stringify(value, null, " "); + } + } catch (ex) { + payload = "/* " + ex + " */"; + } + owner.helperResult = { + type: "copyValueToClipboard", + value: payload, + }; +}); + +/** + * (Internal only) Add the bindings to |owner.sandbox|. + * This is intended to be used by the WebConsole actor only. + * + * @param object owner + * The owning object. + */ +function addWebConsoleCommands(owner) { + if (!owner) { + throw new Error("The owner is required"); + } + for (let [name, command] of WebConsoleCommands._registeredCommands) { + if (typeof command === "function") { + owner.sandbox[name] = command.bind(undefined, owner); + } else if (typeof command === "object") { + let clone = Object.assign({}, command, { + // We force the enumerability and the configurability (so the + // WebConsoleActor can reconfigure the property). + enumerable: true, + configurable: true + }); + + if (typeof command.get === "function") { + clone.get = command.get.bind(undefined, owner); + } + if (typeof command.set === "function") { + clone.set = command.set.bind(undefined, owner); + } + + Object.defineProperty(owner.sandbox, name, clone); + } + } +} + +//exports.addWebConsoleCommands = addWebConsoleCommands; + +/** + * A ReflowObserver that listens for reflow events from the page. + * Implements nsIReflowObserver. + * + * @constructor + * @param object window + * The window for which we need to track reflow. + * @param object owner + * The listener owner which needs to implement: + * - onReflowActivity(reflowInfo) + */ + +function ConsoleReflowListener(window, listener) { + this.docshell = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShell); + this.listener = listener; + this.docshell.addWeakReflowObserver(this); +} + +// exports.ConsoleReflowListener = ConsoleReflowListener; + +ConsoleReflowListener.prototype = +{ +// QueryInterface: XPCOMUtils.generateQI([Ci.nsIReflowObserver, +// Ci.nsISupportsWeakReference]), + docshell: null, + listener: null, + + /** + * Forward reflow event to listener. + * + * @param DOMHighResTimeStamp start + * @param DOMHighResTimeStamp end + * @param boolean interruptible + */ + sendReflow: function (start, end, interruptible) { + let frame;// = components.stack.caller.caller; + + let filename = frame ? frame.filename : null; + + if (filename) { + // Because filename could be of the form "xxx.js -> xxx.js -> xxx.js", + // we only take the last part. + filename = filename.split(" ").pop(); + } + + this.listener.onReflowActivity({ + interruptible: interruptible, + start: start, + end: end, + sourceURL: filename, + sourceLine: frame ? frame.lineNumber : null, + functionName: frame ? frame.name : null + }); }, /** - * Retrieve a localized string formatted with values coming from the given - * array. + * On uninterruptible reflow * - * @param string name - * The string name you want from the Web Console string bundle. - * @param array array - * The array of values you want in the formatted string. - * @return string - * The formatted local string. + * @param DOMHighResTimeStamp start + * @param DOMHighResTimeStamp end */ - getFormatStr: function (name, array) { - try { - return this._helper.getFormatStr(name, ...array); - } catch (ex) { - console.error("Failed to format string: " + name); - throw ex; - } + reflow: function (start, end) { + this.sendReflow(start, end, false); + }, + + /** + * On interruptible reflow + * + * @param DOMHighResTimeStamp start + * @param DOMHighResTimeStamp end + */ + reflowInterruptible: function (start, end) { + this.sendReflow(start, end, true); + }, + + /** + * Unregister listener. + */ + destroy: function () { + this.docshell.removeWeakReflowObserver(this); + this.listener = this.docshell = null; }, }; diff --git a/native/cocos/scripting/js-bindings/script/jsb_debugger.js b/native/cocos/scripting/js-bindings/script/jsb_debugger.js index a14954cae6..df1adfe653 100755 --- a/native/cocos/scripting/js-bindings/script/jsb_debugger.js +++ b/native/cocos/scripting/js-bindings/script/jsb_debugger.js @@ -68,7 +68,7 @@ function TestTabList(aConnection) { TestTabList.prototype = { constructor: TestTabList, getList: function () { - return resolve([...this._tabActors]); + return Promise.resolve([...this._tabActors]); } }; @@ -200,7 +200,7 @@ this.processInput = function (inputstr) { if (inputstr === "connected") { - DebuggerServer.init(); + DebuggerServer.init(); DebuggerServer.setRootActor(createRootActor); conn = DebuggerServer._onConnection(transport); @@ -232,6 +232,7 @@ this.processInput = function (inputstr) { let packet = inputString.substring(0, count); incomingData = inputString.substring(count); + log(">>>>>>>>>> " + packet); return packet; } @@ -257,17 +258,26 @@ this._prepareDebugger = function (global) { this.globalDebuggee = global; cc = global.cc; + // load all functions exported in DevToolsUtils to global(exports) // exports = global; - // load all functions exported in DevToolsUtils to global(exports) + // SDK cods from https://hg.mozilla.org/mozilla-central/file/d1c70c20e7b5/addon-sdk/source/lib/sdk/ + require('script/debugger/sdk/heritage.js', 'debug'); + require('script/debugger/sdk/object.js', 'debug'); + require('script/debugger/sdk/event-core.js', 'debug'); + require('script/debugger/sdk/target.js', 'debug'); + require('script/debugger/DevToolsUtils.js', 'debug'); require('script/debugger/event-emitter.js', 'debug'); require('script/debugger/actors/utils/ScriptStore.js', 'debug'); require('script/debugger/actors/common.js', 'debug'); require('script/debugger/transport.js', 'debug'); require('script/debugger/main.js', 'debug'); + require('script/debugger/protocol.js', 'debug'); require('script/debugger/actors/object.js', 'debug'); require('script/debugger/actors/root.js', 'debug'); + require('script/debugger/actors/source.js', 'debug'); + require('script/debugger/actors/breakpoint.js', 'debug'); require('script/debugger/actors/script.js', 'debug'); require('script/debugger/actors/webconsole.js', 'debug') require('script/debugger/actors/utils/TabSources.js', 'debug');