webconsole.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  1. /* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. "use strict";
  6. const Services = require("Services");
  7. const { Cc, Ci, Cu } = require("chrome");
  8. const { DebuggerServer, ActorPool } = require("devtools/server/main");
  9. const { EnvironmentActor } = require("devtools/server/actors/environment");
  10. const { ThreadActor } = require("devtools/server/actors/script");
  11. const { ObjectActor, LongStringActor, createValueGrip, stringIsLong } = require("devtools/server/actors/object");
  12. const DevToolsUtils = require("devtools/shared/DevToolsUtils");
  13. const ErrorDocs = require("devtools/server/actors/errordocs");
  14. loader.lazyRequireGetter(this, "NetworkMonitor", "devtools/shared/webconsole/network-monitor", true);
  15. loader.lazyRequireGetter(this, "NetworkMonitorChild", "devtools/shared/webconsole/network-monitor", true);
  16. loader.lazyRequireGetter(this, "ConsoleProgressListener", "devtools/shared/webconsole/network-monitor", true);
  17. loader.lazyRequireGetter(this, "StackTraceCollector", "devtools/shared/webconsole/network-monitor", true);
  18. loader.lazyRequireGetter(this, "events", "sdk/event/core");
  19. loader.lazyRequireGetter(this, "ServerLoggingListener", "devtools/shared/webconsole/server-logger", true);
  20. loader.lazyRequireGetter(this, "JSPropertyProvider", "devtools/shared/webconsole/js-property-provider", true);
  21. loader.lazyRequireGetter(this, "Parser", "resource://devtools/shared/Parser.jsm", true);
  22. loader.lazyRequireGetter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm", true);
  23. for (let name of ["WebConsoleUtils", "ConsoleServiceListener",
  24. "ConsoleAPIListener", "addWebConsoleCommands",
  25. "ConsoleReflowListener", "CONSOLE_WORKER_IDS"]) {
  26. Object.defineProperty(this, name, {
  27. get: function (prop) {
  28. if (prop == "WebConsoleUtils") {
  29. prop = "Utils";
  30. }
  31. if (isWorker) {
  32. return require("devtools/server/actors/utils/webconsole-worker-utils")[prop];
  33. } else {
  34. return require("devtools/server/actors/utils/webconsole-utils")[prop];
  35. }
  36. }.bind(null, name),
  37. configurable: true,
  38. enumerable: true
  39. });
  40. }
  41. /**
  42. * The WebConsoleActor implements capabilities needed for the Web Console
  43. * feature.
  44. *
  45. * @constructor
  46. * @param object aConnection
  47. * The connection to the client, DebuggerServerConnection.
  48. * @param object [aParentActor]
  49. * Optional, the parent actor.
  50. */
  51. function WebConsoleActor(aConnection, aParentActor)
  52. {
  53. this.conn = aConnection;
  54. this.parentActor = aParentActor;
  55. this._actorPool = new ActorPool(this.conn);
  56. this.conn.addActorPool(this._actorPool);
  57. this._prefs = {};
  58. this.dbg = this.parentActor.makeDebugger();
  59. this._netEvents = new Map();
  60. this._gripDepth = 0;
  61. this._listeners = new Set();
  62. this._lastConsoleInputEvaluation = undefined;
  63. this.objectGrip = this.objectGrip.bind(this);
  64. this._onWillNavigate = this._onWillNavigate.bind(this);
  65. this._onChangedToplevelDocument = this._onChangedToplevelDocument.bind(this);
  66. events.on(this.parentActor, "changed-toplevel-document", this._onChangedToplevelDocument);
  67. this._onObserverNotification = this._onObserverNotification.bind(this);
  68. if (this.parentActor.isRootActor) {
  69. Services.obs.addObserver(this._onObserverNotification,
  70. "last-pb-context-exited", false);
  71. }
  72. this.traits = {
  73. customNetworkRequest: !this._parentIsContentActor,
  74. evaluateJSAsync: true,
  75. transferredResponseSize: true,
  76. selectedObjectActor: true, // 44+
  77. };
  78. }
  79. WebConsoleActor.prototype =
  80. {
  81. /**
  82. * Debugger instance.
  83. *
  84. * @see jsdebugger.jsm
  85. */
  86. dbg: null,
  87. /**
  88. * This is used by the ObjectActor to keep track of the depth of grip() calls.
  89. * @private
  90. * @type number
  91. */
  92. _gripDepth: null,
  93. /**
  94. * Actor pool for all of the actors we send to the client.
  95. * @private
  96. * @type object
  97. * @see ActorPool
  98. */
  99. _actorPool: null,
  100. /**
  101. * Web Console-related preferences.
  102. * @private
  103. * @type object
  104. */
  105. _prefs: null,
  106. /**
  107. * Holds a map between nsIChannel objects and NetworkEventActors for requests
  108. * created with sendHTTPRequest.
  109. *
  110. * @private
  111. * @type Map
  112. */
  113. _netEvents: null,
  114. /**
  115. * Holds a set of all currently registered listeners.
  116. *
  117. * @private
  118. * @type Set
  119. */
  120. _listeners: null,
  121. /**
  122. * The debugger server connection instance.
  123. * @type object
  124. */
  125. conn: null,
  126. /**
  127. * List of supported features by the console actor.
  128. * @type object
  129. */
  130. traits: null,
  131. /**
  132. * Boolean getter that tells if the parent actor is a ContentActor.
  133. *
  134. * @private
  135. * @type boolean
  136. */
  137. get _parentIsContentActor() {
  138. return "ContentActor" in DebuggerServer &&
  139. this.parentActor instanceof DebuggerServer.ContentActor;
  140. },
  141. /**
  142. * The window or sandbox we work with.
  143. * Note that even if it is named `window` it refers to the current
  144. * global we are debugging, which can be a Sandbox for addons
  145. * or browser content toolbox.
  146. *
  147. * @type nsIDOMWindow or Sandbox
  148. */
  149. get window() {
  150. if (this.parentActor.isRootActor) {
  151. return this._getWindowForBrowserConsole();
  152. }
  153. return this.parentActor.window;
  154. },
  155. /**
  156. * Get a window to use for the browser console.
  157. *
  158. * @private
  159. * @return nsIDOMWindow
  160. * The window to use, or null if no window could be found.
  161. */
  162. _getWindowForBrowserConsole: function WCA__getWindowForBrowserConsole()
  163. {
  164. // Check if our last used chrome window is still live.
  165. let window = this._lastChromeWindow && this._lastChromeWindow.get();
  166. // If not, look for a new one.
  167. if (!window || window.closed) {
  168. window = this.parentActor.window;
  169. if (!window) {
  170. // Try to find the Browser Console window to use instead.
  171. window = Services.wm.getMostRecentWindow("devtools:webconsole");
  172. // We prefer the normal chrome window over the console window,
  173. // so we'll look for those windows in order to replace our reference.
  174. let onChromeWindowOpened = () => {
  175. // We'll look for this window when someone next requests window()
  176. Services.obs.removeObserver(onChromeWindowOpened, "domwindowopened");
  177. this._lastChromeWindow = null;
  178. };
  179. Services.obs.addObserver(onChromeWindowOpened, "domwindowopened", false);
  180. }
  181. this._handleNewWindow(window);
  182. }
  183. return window;
  184. },
  185. /**
  186. * Store a newly found window on the actor to be used in the future.
  187. *
  188. * @private
  189. * @param nsIDOMWindow window
  190. * The window to store on the actor (can be null).
  191. */
  192. _handleNewWindow: function WCA__handleNewWindow(window)
  193. {
  194. if (window) {
  195. if (this._hadChromeWindow) {
  196. Services.console.logStringMessage('Webconsole context has changed');
  197. }
  198. this._lastChromeWindow = Cu.getWeakReference(window);
  199. this._hadChromeWindow = true;
  200. } else {
  201. this._lastChromeWindow = null;
  202. }
  203. },
  204. /**
  205. * Whether we've been using a window before.
  206. *
  207. * @private
  208. * @type boolean
  209. */
  210. _hadChromeWindow: false,
  211. /**
  212. * A weak reference to the last chrome window we used to work with.
  213. *
  214. * @private
  215. * @type nsIWeakReference
  216. */
  217. _lastChromeWindow: null,
  218. // The evalWindow is used at the scope for JS evaluation.
  219. _evalWindow: null,
  220. get evalWindow() {
  221. return this._evalWindow || this.window;
  222. },
  223. set evalWindow(aWindow) {
  224. this._evalWindow = aWindow;
  225. if (!this._progressListenerActive) {
  226. events.on(this.parentActor, "will-navigate", this._onWillNavigate);
  227. this._progressListenerActive = true;
  228. }
  229. },
  230. /**
  231. * Flag used to track if we are listening for events from the progress
  232. * listener of the tab actor. We use the progress listener to clear
  233. * this.evalWindow on page navigation.
  234. *
  235. * @private
  236. * @type boolean
  237. */
  238. _progressListenerActive: false,
  239. /**
  240. * The ConsoleServiceListener instance.
  241. * @type object
  242. */
  243. consoleServiceListener: null,
  244. /**
  245. * The ConsoleAPIListener instance.
  246. */
  247. consoleAPIListener: null,
  248. /**
  249. * The NetworkMonitor instance.
  250. */
  251. networkMonitor: null,
  252. /**
  253. * The NetworkMonitor instance living in the same (child) process.
  254. */
  255. networkMonitorChild: null,
  256. /**
  257. * The ConsoleProgressListener instance.
  258. */
  259. consoleProgressListener: null,
  260. /**
  261. * The ConsoleReflowListener instance.
  262. */
  263. consoleReflowListener: null,
  264. /**
  265. * The Web Console Commands names cache.
  266. * @private
  267. * @type array
  268. */
  269. _webConsoleCommandsCache: null,
  270. actorPrefix: "console",
  271. get globalDebugObject() {
  272. return this.parentActor.threadActor.globalDebugObject;
  273. },
  274. grip: function WCA_grip()
  275. {
  276. return { actor: this.actorID };
  277. },
  278. hasNativeConsoleAPI: function WCA_hasNativeConsoleAPI(aWindow) {
  279. let isNative = false;
  280. try {
  281. // We are very explicitly examining the "console" property of
  282. // the non-Xrayed object here.
  283. let console = aWindow.wrappedJSObject.console;
  284. isNative = new XPCNativeWrapper(console).IS_NATIVE_CONSOLE
  285. }
  286. catch (ex) { }
  287. return isNative;
  288. },
  289. _findProtoChain: ThreadActor.prototype._findProtoChain,
  290. _removeFromProtoChain: ThreadActor.prototype._removeFromProtoChain,
  291. /**
  292. * Destroy the current WebConsoleActor instance.
  293. */
  294. disconnect: function WCA_disconnect()
  295. {
  296. if (this.consoleServiceListener) {
  297. this.consoleServiceListener.destroy();
  298. this.consoleServiceListener = null;
  299. }
  300. if (this.consoleAPIListener) {
  301. this.consoleAPIListener.destroy();
  302. this.consoleAPIListener = null;
  303. }
  304. if (this.networkMonitor) {
  305. this.networkMonitor.destroy();
  306. this.networkMonitor = null;
  307. }
  308. if (this.networkMonitorChild) {
  309. this.networkMonitorChild.destroy();
  310. this.networkMonitorChild = null;
  311. }
  312. if (this.stackTraceCollector) {
  313. this.stackTraceCollector.destroy();
  314. this.stackTraceCollector = null;
  315. }
  316. if (this.consoleProgressListener) {
  317. this.consoleProgressListener.destroy();
  318. this.consoleProgressListener = null;
  319. }
  320. if (this.consoleReflowListener) {
  321. this.consoleReflowListener.destroy();
  322. this.consoleReflowListener = null;
  323. }
  324. if (this.serverLoggingListener) {
  325. this.serverLoggingListener.destroy();
  326. this.serverLoggingListener = null;
  327. }
  328. events.off(this.parentActor, "changed-toplevel-document",
  329. this._onChangedToplevelDocument);
  330. this.conn.removeActorPool(this._actorPool);
  331. if (this.parentActor.isRootActor) {
  332. Services.obs.removeObserver(this._onObserverNotification,
  333. "last-pb-context-exited");
  334. }
  335. this._actorPool = null;
  336. this._webConsoleCommandsCache = null;
  337. this._lastConsoleInputEvaluation = null;
  338. this._evalWindow = null;
  339. this._netEvents.clear();
  340. this.dbg.enabled = false;
  341. this.dbg = null;
  342. this.conn = null;
  343. },
  344. /**
  345. * Create and return an environment actor that corresponds to the provided
  346. * Debugger.Environment. This is a straightforward clone of the ThreadActor's
  347. * method except that it stores the environment actor in the web console
  348. * actor's pool.
  349. *
  350. * @param Debugger.Environment aEnvironment
  351. * The lexical environment we want to extract.
  352. * @return The EnvironmentActor for aEnvironment or undefined for host
  353. * functions or functions scoped to a non-debuggee global.
  354. */
  355. createEnvironmentActor: function WCA_createEnvironmentActor(aEnvironment) {
  356. if (!aEnvironment) {
  357. return undefined;
  358. }
  359. if (aEnvironment.actor) {
  360. return aEnvironment.actor;
  361. }
  362. let actor = new EnvironmentActor(aEnvironment, this);
  363. this._actorPool.addActor(actor);
  364. aEnvironment.actor = actor;
  365. return actor;
  366. },
  367. /**
  368. * Create a grip for the given value.
  369. *
  370. * @param mixed aValue
  371. * @return object
  372. */
  373. createValueGrip: function WCA_createValueGrip(aValue)
  374. {
  375. return createValueGrip(aValue, this._actorPool, this.objectGrip);
  376. },
  377. /**
  378. * Make a debuggee value for the given value.
  379. *
  380. * @param mixed aValue
  381. * The value you want to get a debuggee value for.
  382. * @param boolean aUseObjectGlobal
  383. * If |true| the object global is determined and added as a debuggee,
  384. * otherwise |this.window| is used when makeDebuggeeValue() is invoked.
  385. * @return object
  386. * Debuggee value for |aValue|.
  387. */
  388. makeDebuggeeValue: function WCA_makeDebuggeeValue(aValue, aUseObjectGlobal)
  389. {
  390. if (aUseObjectGlobal && typeof aValue == "object") {
  391. try {
  392. let global = Cu.getGlobalForObject(aValue);
  393. let dbgGlobal = this.dbg.makeGlobalObjectReference(global);
  394. return dbgGlobal.makeDebuggeeValue(aValue);
  395. }
  396. catch (ex) {
  397. // The above can throw an exception if aValue is not an actual object
  398. // or 'Object in compartment marked as invisible to Debugger'
  399. }
  400. }
  401. let dbgGlobal = this.dbg.makeGlobalObjectReference(this.window);
  402. return dbgGlobal.makeDebuggeeValue(aValue);
  403. },
  404. /**
  405. * Create a grip for the given object.
  406. *
  407. * @param object aObject
  408. * The object you want.
  409. * @param object aPool
  410. * An ActorPool where the new actor instance is added.
  411. * @param object
  412. * The object grip.
  413. */
  414. objectGrip: function WCA_objectGrip(aObject, aPool)
  415. {
  416. let actor = new ObjectActor(aObject, {
  417. getGripDepth: () => this._gripDepth,
  418. incrementGripDepth: () => this._gripDepth++,
  419. decrementGripDepth: () => this._gripDepth--,
  420. createValueGrip: v => this.createValueGrip(v),
  421. sources: () => DevToolsUtils.reportException("WebConsoleActor",
  422. Error("sources not yet implemented")),
  423. createEnvironmentActor: (env) => this.createEnvironmentActor(env),
  424. getGlobalDebugObject: () => this.globalDebugObject
  425. });
  426. aPool.addActor(actor);
  427. return actor.grip();
  428. },
  429. /**
  430. * Create a grip for the given string.
  431. *
  432. * @param string aString
  433. * The string you want to create the grip for.
  434. * @param object aPool
  435. * An ActorPool where the new actor instance is added.
  436. * @return object
  437. * A LongStringActor object that wraps the given string.
  438. */
  439. longStringGrip: function WCA_longStringGrip(aString, aPool)
  440. {
  441. let actor = new LongStringActor(aString);
  442. aPool.addActor(actor);
  443. return actor.grip();
  444. },
  445. /**
  446. * Create a long string grip if needed for the given string.
  447. *
  448. * @private
  449. * @param string aString
  450. * The string you want to create a long string grip for.
  451. * @return string|object
  452. * A string is returned if |aString| is not a long string.
  453. * A LongStringActor grip is returned if |aString| is a long string.
  454. */
  455. _createStringGrip: function NEA__createStringGrip(aString)
  456. {
  457. if (aString && stringIsLong(aString)) {
  458. return this.longStringGrip(aString, this._actorPool);
  459. }
  460. return aString;
  461. },
  462. /**
  463. * Get an object actor by its ID.
  464. *
  465. * @param string aActorID
  466. * @return object
  467. */
  468. getActorByID: function WCA_getActorByID(aActorID)
  469. {
  470. return this._actorPool.get(aActorID);
  471. },
  472. /**
  473. * Release an actor.
  474. *
  475. * @param object aActor
  476. * The actor instance you want to release.
  477. */
  478. releaseActor: function WCA_releaseActor(aActor)
  479. {
  480. this._actorPool.removeActor(aActor.actorID);
  481. },
  482. /**
  483. * Returns the latest web console input evaluation.
  484. * This is undefined if no evaluations have been completed.
  485. *
  486. * @return object
  487. */
  488. getLastConsoleInputEvaluation: function WCU_getLastConsoleInputEvaluation()
  489. {
  490. return this._lastConsoleInputEvaluation;
  491. },
  492. // Request handlers for known packet types.
  493. /**
  494. * Handler for the "startListeners" request.
  495. *
  496. * @param object aRequest
  497. * The JSON request object received from the Web Console client.
  498. * @return object
  499. * The response object which holds the startedListeners array.
  500. */
  501. onStartListeners: function WCA_onStartListeners(aRequest)
  502. {
  503. // XXXworkers: Not handling the Console API yet for workers (Bug 1209353).
  504. if (isWorker) {
  505. aRequest.listeners = [];
  506. }
  507. let startedListeners = [];
  508. let window = !this.parentActor.isRootActor ? this.window : null;
  509. let appId = null;
  510. let messageManager = null;
  511. if (this._parentIsContentActor) {
  512. appId = this.parentActor.docShell.appId;
  513. messageManager = this.parentActor.messageManager;
  514. }
  515. while (aRequest.listeners.length > 0) {
  516. let listener = aRequest.listeners.shift();
  517. switch (listener) {
  518. case "PageError":
  519. if (!this.consoleServiceListener) {
  520. this.consoleServiceListener =
  521. new ConsoleServiceListener(window, this);
  522. this.consoleServiceListener.init();
  523. }
  524. startedListeners.push(listener);
  525. break;
  526. case "ConsoleAPI":
  527. if (!this.consoleAPIListener) {
  528. // Create the consoleAPIListener (and apply the filtering options defined
  529. // in the parent actor).
  530. this.consoleAPIListener =
  531. new ConsoleAPIListener(window, this,
  532. this.parentActor.consoleAPIListenerOptions);
  533. this.consoleAPIListener.init();
  534. }
  535. startedListeners.push(listener);
  536. break;
  537. case "NetworkActivity":
  538. if (!this.networkMonitor) {
  539. // Create a StackTraceCollector that's going to be shared both by the
  540. // NetworkMonitorChild (getting messages about requests from parent) and
  541. // by the NetworkMonitor that directly watches service workers requests.
  542. this.stackTraceCollector = new StackTraceCollector({ window, appId });
  543. this.stackTraceCollector.init();
  544. let processBoundary = Services.appinfo.processType !=
  545. Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
  546. if ((appId || messageManager) && processBoundary) {
  547. // Start a network monitor in the parent process to listen to
  548. // most requests than happen in parent
  549. this.networkMonitor =
  550. new NetworkMonitorChild(appId, this.parentActor.outerWindowID,
  551. messageManager, this.conn, this);
  552. this.networkMonitor.init();
  553. // Spawn also one in the child to listen to service workers
  554. this.networkMonitorChild = new NetworkMonitor({ window }, this);
  555. this.networkMonitorChild.init();
  556. } else {
  557. this.networkMonitor = new NetworkMonitor({ window }, this);
  558. this.networkMonitor.init();
  559. }
  560. }
  561. startedListeners.push(listener);
  562. break;
  563. case "FileActivity":
  564. if (this.window instanceof Ci.nsIDOMWindow) {
  565. if (!this.consoleProgressListener) {
  566. this.consoleProgressListener =
  567. new ConsoleProgressListener(this.window, this);
  568. }
  569. this.consoleProgressListener.startMonitor(this.consoleProgressListener.
  570. MONITOR_FILE_ACTIVITY);
  571. startedListeners.push(listener);
  572. }
  573. break;
  574. case "ReflowActivity":
  575. if (!this.consoleReflowListener) {
  576. this.consoleReflowListener =
  577. new ConsoleReflowListener(this.window, this);
  578. }
  579. startedListeners.push(listener);
  580. break;
  581. case "ServerLogging":
  582. if (!this.serverLoggingListener) {
  583. this.serverLoggingListener =
  584. new ServerLoggingListener(this.window, this);
  585. }
  586. startedListeners.push(listener);
  587. break;
  588. }
  589. }
  590. // Update the live list of running listeners
  591. startedListeners.forEach(this._listeners.add, this._listeners);
  592. return {
  593. startedListeners: startedListeners,
  594. nativeConsoleAPI: this.hasNativeConsoleAPI(this.window),
  595. traits: this.traits,
  596. };
  597. },
  598. /**
  599. * Handler for the "stopListeners" request.
  600. *
  601. * @param object aRequest
  602. * The JSON request object received from the Web Console client.
  603. * @return object
  604. * The response packet to send to the client: holds the
  605. * stoppedListeners array.
  606. */
  607. onStopListeners: function WCA_onStopListeners(aRequest)
  608. {
  609. let stoppedListeners = [];
  610. // If no specific listeners are requested to be detached, we stop all
  611. // listeners.
  612. let toDetach = aRequest.listeners ||
  613. ["PageError", "ConsoleAPI", "NetworkActivity",
  614. "FileActivity", "ServerLogging"];
  615. while (toDetach.length > 0) {
  616. let listener = toDetach.shift();
  617. switch (listener) {
  618. case "PageError":
  619. if (this.consoleServiceListener) {
  620. this.consoleServiceListener.destroy();
  621. this.consoleServiceListener = null;
  622. }
  623. stoppedListeners.push(listener);
  624. break;
  625. case "ConsoleAPI":
  626. if (this.consoleAPIListener) {
  627. this.consoleAPIListener.destroy();
  628. this.consoleAPIListener = null;
  629. }
  630. stoppedListeners.push(listener);
  631. break;
  632. case "NetworkActivity":
  633. if (this.networkMonitor) {
  634. this.networkMonitor.destroy();
  635. this.networkMonitor = null;
  636. }
  637. if (this.networkMonitorChild) {
  638. this.networkMonitorChild.destroy();
  639. this.networkMonitorChild = null;
  640. }
  641. if (this.stackTraceCollector) {
  642. this.stackTraceCollector.destroy();
  643. this.stackTraceCollector = null;
  644. }
  645. stoppedListeners.push(listener);
  646. break;
  647. case "FileActivity":
  648. if (this.consoleProgressListener) {
  649. this.consoleProgressListener.stopMonitor(this.consoleProgressListener.
  650. MONITOR_FILE_ACTIVITY);
  651. this.consoleProgressListener = null;
  652. }
  653. stoppedListeners.push(listener);
  654. break;
  655. case "ReflowActivity":
  656. if (this.consoleReflowListener) {
  657. this.consoleReflowListener.destroy();
  658. this.consoleReflowListener = null;
  659. }
  660. stoppedListeners.push(listener);
  661. break;
  662. case "ServerLogging":
  663. if (this.serverLoggingListener) {
  664. this.serverLoggingListener.destroy();
  665. this.serverLoggingListener = null;
  666. }
  667. stoppedListeners.push(listener);
  668. break;
  669. }
  670. }
  671. // Update the live list of running listeners
  672. stoppedListeners.forEach(this._listeners.delete, this._listeners);
  673. return { stoppedListeners: stoppedListeners };
  674. },
  675. /**
  676. * Handler for the "getCachedMessages" request. This method sends the cached
  677. * error messages and the window.console API calls to the client.
  678. *
  679. * @param object aRequest
  680. * The JSON request object received from the Web Console client.
  681. * @return object
  682. * The response packet to send to the client: it holds the cached
  683. * messages array.
  684. */
  685. onGetCachedMessages: function WCA_onGetCachedMessages(aRequest)
  686. {
  687. let types = aRequest.messageTypes;
  688. if (!types) {
  689. return {
  690. error: "missingParameter",
  691. message: "The messageTypes parameter is missing.",
  692. };
  693. }
  694. let messages = [];
  695. while (types.length > 0) {
  696. let type = types.shift();
  697. switch (type) {
  698. case "ConsoleAPI": {
  699. if (!this.consoleAPIListener) {
  700. break;
  701. }
  702. // See `window` definition. It isn't always a DOM Window.
  703. let winStartTime = this.window && this.window.performance ?
  704. this.window.performance.timing.navigationStart : 0;
  705. let cache = this.consoleAPIListener
  706. .getCachedMessages(!this.parentActor.isRootActor);
  707. cache.forEach((aMessage) => {
  708. // Filter out messages that came from a ServiceWorker but happened
  709. // before the page was requested.
  710. if (aMessage.innerID === "ServiceWorker" &&
  711. winStartTime > aMessage.timeStamp) {
  712. return;
  713. }
  714. let message = this.prepareConsoleMessageForRemote(aMessage);
  715. message._type = type;
  716. messages.push(message);
  717. });
  718. break;
  719. }
  720. case "PageError": {
  721. if (!this.consoleServiceListener) {
  722. break;
  723. }
  724. let cache = this.consoleServiceListener
  725. .getCachedMessages(!this.parentActor.isRootActor);
  726. cache.forEach((aMessage) => {
  727. let message = null;
  728. if (aMessage instanceof Ci.nsIScriptError) {
  729. message = this.preparePageErrorForRemote(aMessage);
  730. message._type = type;
  731. }
  732. else {
  733. message = {
  734. _type: "LogMessage",
  735. message: this._createStringGrip(aMessage.message),
  736. timeStamp: aMessage.timeStamp,
  737. };
  738. }
  739. messages.push(message);
  740. });
  741. break;
  742. }
  743. }
  744. }
  745. return {
  746. from: this.actorID,
  747. messages: messages,
  748. };
  749. },
  750. /**
  751. * Handler for the "evaluateJSAsync" request. This method evaluates the given
  752. * JavaScript string and sends back a packet with a unique ID.
  753. * The result will be returned later as an unsolicited `evaluationResult`,
  754. * that can be associated back to this request via the `resultID` field.
  755. *
  756. * @param object aRequest
  757. * The JSON request object received from the Web Console client.
  758. * @return object
  759. * The response packet to send to with the unique id in the
  760. * `resultID` field.
  761. */
  762. onEvaluateJSAsync: function WCA_onEvaluateJSAsync(aRequest)
  763. {
  764. // We want to be able to run console commands without waiting
  765. // for the first to return (see Bug 1088861).
  766. // First, send a response packet with the id only.
  767. let resultID = Date.now();
  768. this.conn.send({
  769. from: this.actorID,
  770. resultID: resultID
  771. });
  772. // Then, execute the script that may pause.
  773. let response = this.onEvaluateJS(aRequest);
  774. response.resultID = resultID;
  775. // Finally, send an unsolicited evaluationResult packet with
  776. // the normal return value
  777. this.conn.sendActorEvent(this.actorID, "evaluationResult", response);
  778. },
  779. /**
  780. * Handler for the "evaluateJS" request. This method evaluates the given
  781. * JavaScript string and sends back the result.
  782. *
  783. * @param object aRequest
  784. * The JSON request object received from the Web Console client.
  785. * @return object
  786. * The evaluation response packet.
  787. */
  788. onEvaluateJS: function WCA_onEvaluateJS(aRequest)
  789. {
  790. let input = aRequest.text;
  791. let timestamp = Date.now();
  792. let evalOptions = {
  793. bindObjectActor: aRequest.bindObjectActor,
  794. frameActor: aRequest.frameActor,
  795. url: aRequest.url,
  796. selectedNodeActor: aRequest.selectedNodeActor,
  797. selectedObjectActor: aRequest.selectedObjectActor,
  798. };
  799. let evalInfo = this.evalWithDebugger(input, evalOptions);
  800. let evalResult = evalInfo.result;
  801. let helperResult = evalInfo.helperResult;
  802. let result, errorDocURL, errorMessage, errorNotes = null, errorGrip = null,
  803. frame = null;
  804. if (evalResult) {
  805. if ("return" in evalResult) {
  806. result = evalResult.return;
  807. } else if ("yield" in evalResult) {
  808. result = evalResult.yield;
  809. } else if ("throw" in evalResult) {
  810. let error = evalResult.throw;
  811. errorGrip = this.createValueGrip(error);
  812. errorMessage = String(error);
  813. if (typeof error === "object" && error !== null) {
  814. try {
  815. errorMessage = DevToolsUtils.callPropertyOnObject(error, "toString");
  816. } catch (e) {
  817. // If the debuggee is not allowed to access the "toString" property
  818. // of the error object, calling this property from the debuggee's
  819. // compartment will fail. The debugger should show the error object
  820. // as it is seen by the debuggee, so this behavior is correct.
  821. //
  822. // Unfortunately, we have at least one test that assumes calling the
  823. // "toString" property of an error object will succeed if the
  824. // debugger is allowed to access it, regardless of whether the
  825. // debuggee is allowed to access it or not.
  826. //
  827. // To accomodate these tests, if calling the "toString" property
  828. // from the debuggee compartment fails, we rewrap the error object
  829. // in the debugger's compartment, and then call the "toString"
  830. // property from there.
  831. if (typeof error.unsafeDereference === "function") {
  832. errorMessage = error.unsafeDereference().toString();
  833. }
  834. }
  835. }
  836. // It is possible that we won't have permission to unwrap an
  837. // object and retrieve its errorMessageName.
  838. try {
  839. errorDocURL = ErrorDocs.GetURL(error);
  840. } catch (ex) {}
  841. try {
  842. let line = error.errorLineNumber;
  843. let column = error.errorColumnNumber;
  844. if (typeof line === "number" && typeof column === "number") {
  845. // Set frame only if we have line/column numbers.
  846. frame = {
  847. source: "debugger eval code",
  848. line,
  849. column
  850. };
  851. }
  852. } catch (ex) {}
  853. try {
  854. let notes = error.errorNotes;
  855. if (notes && notes.length) {
  856. errorNotes = [];
  857. for (let note of notes) {
  858. errorNotes.push({
  859. messageBody: this._createStringGrip(note.message),
  860. frame: {
  861. source: note.fileName,
  862. line: note.lineNumber,
  863. column: note.columnNumber,
  864. }
  865. });
  866. }
  867. }
  868. } catch (ex) {}
  869. }
  870. }
  871. // If a value is encountered that the debugger server doesn't support yet,
  872. // the console should remain functional.
  873. let resultGrip;
  874. try {
  875. resultGrip = this.createValueGrip(result);
  876. } catch (e) {
  877. errorMessage = e;
  878. }
  879. this._lastConsoleInputEvaluation = result;
  880. return {
  881. from: this.actorID,
  882. input: input,
  883. result: resultGrip,
  884. timestamp: timestamp,
  885. exception: errorGrip,
  886. exceptionMessage: this._createStringGrip(errorMessage),
  887. exceptionDocURL: errorDocURL,
  888. frame,
  889. helperResult: helperResult,
  890. notes: errorNotes,
  891. };
  892. },
  893. /**
  894. * The Autocomplete request handler.
  895. *
  896. * @param object aRequest
  897. * The request message - what input to autocomplete.
  898. * @return object
  899. * The response message - matched properties.
  900. */
  901. onAutocomplete: function WCA_onAutocomplete(aRequest)
  902. {
  903. let frameActorId = aRequest.frameActor;
  904. let dbgObject = null;
  905. let environment = null;
  906. let hadDebuggee = false;
  907. // This is the case of the paused debugger
  908. if (frameActorId) {
  909. let frameActor = this.conn.getActor(frameActorId);
  910. try {
  911. // Need to try/catch since accessing frame.environment
  912. // can throw "Debugger.Frame is not live"
  913. let frame = frameActor.frame;
  914. environment = frame.environment;
  915. } catch (e) {
  916. DevToolsUtils.reportException("onAutocomplete",
  917. Error("The frame actor was not found: " + frameActorId));
  918. }
  919. }
  920. // This is the general case (non-paused debugger)
  921. else {
  922. hadDebuggee = this.dbg.hasDebuggee(this.evalWindow);
  923. dbgObject = this.dbg.addDebuggee(this.evalWindow);
  924. }
  925. let result = JSPropertyProvider(dbgObject, environment, aRequest.text,
  926. aRequest.cursor, frameActorId) || {};
  927. if (!hadDebuggee && dbgObject) {
  928. this.dbg.removeDebuggee(this.evalWindow);
  929. }
  930. let matches = result.matches || [];
  931. let reqText = aRequest.text.substr(0, aRequest.cursor);
  932. // We consider '$' as alphanumerc because it is used in the names of some
  933. // helper functions.
  934. let lastNonAlphaIsDot = /[.][a-zA-Z0-9$]*$/.test(reqText);
  935. if (!lastNonAlphaIsDot) {
  936. if (!this._webConsoleCommandsCache) {
  937. let helpers = {
  938. sandbox: Object.create(null)
  939. };
  940. addWebConsoleCommands(helpers);
  941. this._webConsoleCommandsCache =
  942. Object.getOwnPropertyNames(helpers.sandbox);
  943. }
  944. matches = matches.concat(this._webConsoleCommandsCache
  945. .filter(n => n.startsWith(result.matchProp)));
  946. }
  947. return {
  948. from: this.actorID,
  949. matches: matches.sort(),
  950. matchProp: result.matchProp,
  951. };
  952. },
  953. /**
  954. * The "clearMessagesCache" request handler.
  955. */
  956. onClearMessagesCache: function WCA_onClearMessagesCache()
  957. {
  958. // TODO: Bug 717611 - Web Console clear button does not clear cached errors
  959. let windowId = !this.parentActor.isRootActor ?
  960. WebConsoleUtils.getInnerWindowId(this.window) : null;
  961. let ConsoleAPIStorage = Cc["@mozilla.org/consoleAPI-storage;1"]
  962. .getService(Ci.nsIConsoleAPIStorage);
  963. ConsoleAPIStorage.clearEvents(windowId);
  964. CONSOLE_WORKER_IDS.forEach((aId) => {
  965. ConsoleAPIStorage.clearEvents(aId);
  966. });
  967. if (this.parentActor.isRootActor) {
  968. Services.console.logStringMessage(null); // for the Error Console
  969. Services.console.reset();
  970. }
  971. return {};
  972. },
  973. /**
  974. * The "getPreferences" request handler.
  975. *
  976. * @param object aRequest
  977. * The request message - which preferences need to be retrieved.
  978. * @return object
  979. * The response message - a { key: value } object map.
  980. */
  981. onGetPreferences: function WCA_onGetPreferences(aRequest)
  982. {
  983. let prefs = Object.create(null);
  984. for (let key of aRequest.preferences) {
  985. prefs[key] = this._prefs[key];
  986. }
  987. return { preferences: prefs };
  988. },
  989. /**
  990. * The "setPreferences" request handler.
  991. *
  992. * @param object aRequest
  993. * The request message - which preferences need to be updated.
  994. */
  995. onSetPreferences: function WCA_onSetPreferences(aRequest)
  996. {
  997. for (let key in aRequest.preferences) {
  998. this._prefs[key] = aRequest.preferences[key];
  999. if (this.networkMonitor) {
  1000. if (key == "NetworkMonitor.saveRequestAndResponseBodies") {
  1001. this.networkMonitor.saveRequestAndResponseBodies = this._prefs[key];
  1002. if (this.networkMonitorChild) {
  1003. this.networkMonitorChild.saveRequestAndResponseBodies =
  1004. this._prefs[key];
  1005. }
  1006. } else if (key == "NetworkMonitor.throttleData") {
  1007. this.networkMonitor.throttleData = this._prefs[key];
  1008. if (this.networkMonitorChild) {
  1009. this.networkMonitorChild.throttleData = this._prefs[key];
  1010. }
  1011. }
  1012. }
  1013. }
  1014. return { updated: Object.keys(aRequest.preferences) };
  1015. },
  1016. // End of request handlers.
  1017. /**
  1018. * Create an object with the API we expose to the Web Console during
  1019. * JavaScript evaluation.
  1020. * This object inherits properties and methods from the Web Console actor.
  1021. *
  1022. * @private
  1023. * @param object aDebuggerGlobal
  1024. * A Debugger.Object that wraps a content global. This is used for the
  1025. * Web Console Commands.
  1026. * @return object
  1027. * The same object as |this|, but with an added |sandbox| property.
  1028. * The sandbox holds methods and properties that can be used as
  1029. * bindings during JS evaluation.
  1030. */
  1031. _getWebConsoleCommands: function (aDebuggerGlobal)
  1032. {
  1033. let helpers = {
  1034. window: this.evalWindow,
  1035. chromeWindow: this.chromeWindow.bind(this),
  1036. makeDebuggeeValue: aDebuggerGlobal.makeDebuggeeValue.bind(aDebuggerGlobal),
  1037. createValueGrip: this.createValueGrip.bind(this),
  1038. sandbox: Object.create(null),
  1039. helperResult: null,
  1040. consoleActor: this,
  1041. };
  1042. addWebConsoleCommands(helpers);
  1043. let evalWindow = this.evalWindow;
  1044. function maybeExport(obj, name) {
  1045. if (typeof obj[name] != "function") {
  1046. return;
  1047. }
  1048. // By default, chrome-implemented functions that are exposed to content
  1049. // refuse to accept arguments that are cross-origin for the caller. This
  1050. // is generally the safe thing, but causes problems for certain console
  1051. // helpers like cd(), where we users sometimes want to pass a cross-origin
  1052. // window. To circumvent this restriction, we use exportFunction along
  1053. // with a special option designed for this purpose. See bug 1051224.
  1054. obj[name] =
  1055. Cu.exportFunction(obj[name], evalWindow, { allowCrossOriginArguments: true });
  1056. }
  1057. for (let name in helpers.sandbox) {
  1058. let desc = Object.getOwnPropertyDescriptor(helpers.sandbox, name);
  1059. // Workers don't have access to Cu so won't be able to exportFunction.
  1060. if (!isWorker) {
  1061. maybeExport(desc, "get");
  1062. maybeExport(desc, "set");
  1063. maybeExport(desc, "value");
  1064. }
  1065. if (desc.value) {
  1066. // Make sure the helpers can be used during eval.
  1067. desc.value = aDebuggerGlobal.makeDebuggeeValue(desc.value);
  1068. }
  1069. Object.defineProperty(helpers.sandbox, name, desc);
  1070. }
  1071. return helpers;
  1072. },
  1073. /**
  1074. * Evaluates a string using the debugger API.
  1075. *
  1076. * To allow the variables view to update properties from the Web Console we
  1077. * provide the "bindObjectActor" mechanism: the Web Console tells the
  1078. * ObjectActor ID for which it desires to evaluate an expression. The
  1079. * Debugger.Object pointed at by the actor ID is bound such that it is
  1080. * available during expression evaluation (executeInGlobalWithBindings()).
  1081. *
  1082. * Example:
  1083. * _self['foobar'] = 'test'
  1084. * where |_self| refers to the desired object.
  1085. *
  1086. * The |frameActor| property allows the Web Console client to provide the
  1087. * frame actor ID, such that the expression can be evaluated in the
  1088. * user-selected stack frame.
  1089. *
  1090. * For the above to work we need the debugger and the Web Console to share
  1091. * a connection, otherwise the Web Console actor will not find the frame
  1092. * actor.
  1093. *
  1094. * The Debugger.Frame comes from the jsdebugger's Debugger instance, which
  1095. * is different from the Web Console's Debugger instance. This means that
  1096. * for evaluation to work, we need to create a new instance for the Web
  1097. * Console Commands helpers - they need to be Debugger.Objects coming from the
  1098. * jsdebugger's Debugger instance.
  1099. *
  1100. * When |bindObjectActor| is used objects can come from different iframes,
  1101. * from different domains. To avoid permission-related errors when objects
  1102. * come from a different window, we also determine the object's own global,
  1103. * such that evaluation happens in the context of that global. This means that
  1104. * evaluation will happen in the object's iframe, rather than the top level
  1105. * window.
  1106. *
  1107. * @param string aString
  1108. * String to evaluate.
  1109. * @param object [aOptions]
  1110. * Options for evaluation:
  1111. * - bindObjectActor: the ObjectActor ID to use for evaluation.
  1112. * |evalWithBindings()| will be called with one additional binding:
  1113. * |_self| which will point to the Debugger.Object of the given
  1114. * ObjectActor.
  1115. * - selectedObjectActor: Like bindObjectActor, but executes with the
  1116. * top level window as the global.
  1117. * - frameActor: the FrameActor ID to use for evaluation. The given
  1118. * debugger frame is used for evaluation, instead of the global window.
  1119. * - selectedNodeActor: the NodeActor ID of the currently selected node
  1120. * in the Inspector (or null, if there is no selection). This is used
  1121. * for helper functions that make reference to the currently selected
  1122. * node, like $0.
  1123. * - url: the url to evaluate the script as. Defaults to
  1124. * "debugger eval code".
  1125. * @return object
  1126. * An object that holds the following properties:
  1127. * - dbg: the debugger where the string was evaluated.
  1128. * - frame: (optional) the frame where the string was evaluated.
  1129. * - window: the Debugger.Object for the global where the string was
  1130. * evaluated.
  1131. * - result: the result of the evaluation.
  1132. * - helperResult: any result coming from a Web Console commands
  1133. * function.
  1134. */
  1135. evalWithDebugger: function WCA_evalWithDebugger(aString, aOptions = {})
  1136. {
  1137. let trimmedString = aString.trim();
  1138. // The help function needs to be easy to guess, so we make the () optional.
  1139. if (trimmedString == "help" || trimmedString == "?") {
  1140. aString = "help()";
  1141. }
  1142. // Add easter egg for console.mihai().
  1143. if (trimmedString == "console.mihai()" || trimmedString == "console.mihai();") {
  1144. aString = "\"http://incompleteness.me/blog/2015/02/09/console-dot-mihai/\"";
  1145. }
  1146. // Find the Debugger.Frame of the given FrameActor.
  1147. let frame = null, frameActor = null;
  1148. if (aOptions.frameActor) {
  1149. frameActor = this.conn.getActor(aOptions.frameActor);
  1150. if (frameActor) {
  1151. frame = frameActor.frame;
  1152. }
  1153. else {
  1154. DevToolsUtils.reportException("evalWithDebugger",
  1155. Error("The frame actor was not found: " + aOptions.frameActor));
  1156. }
  1157. }
  1158. // If we've been given a frame actor in whose scope we should evaluate the
  1159. // expression, be sure to use that frame's Debugger (that is, the JavaScript
  1160. // debugger's Debugger) for the whole operation, not the console's Debugger.
  1161. // (One Debugger will treat a different Debugger's Debugger.Object instances
  1162. // as ordinary objects, not as references to be followed, so mixing
  1163. // debuggers causes strange behaviors.)
  1164. let dbg = frame ? frameActor.threadActor.dbg : this.dbg;
  1165. let dbgWindow = dbg.makeGlobalObjectReference(this.evalWindow);
  1166. // If we have an object to bind to |_self|, create a Debugger.Object
  1167. // referring to that object, belonging to dbg.
  1168. let bindSelf = null;
  1169. if (aOptions.bindObjectActor || aOptions.selectedObjectActor) {
  1170. let objActor = this.getActorByID(aOptions.bindObjectActor ||
  1171. aOptions.selectedObjectActor);
  1172. if (objActor) {
  1173. let jsObj = objActor.obj.unsafeDereference();
  1174. // If we use the makeDebuggeeValue method of jsObj's own global, then
  1175. // we'll get a D.O that sees jsObj as viewed from its own compartment -
  1176. // that is, without wrappers. The evalWithBindings call will then wrap
  1177. // jsObj appropriately for the evaluation compartment.
  1178. let global = Cu.getGlobalForObject(jsObj);
  1179. let _dbgWindow = dbg.makeGlobalObjectReference(global);
  1180. bindSelf = dbgWindow.makeDebuggeeValue(jsObj);
  1181. if (aOptions.bindObjectActor) {
  1182. dbgWindow = _dbgWindow;
  1183. }
  1184. }
  1185. }
  1186. // Get the Web Console commands for the given debugger window.
  1187. let helpers = this._getWebConsoleCommands(dbgWindow);
  1188. let bindings = helpers.sandbox;
  1189. if (bindSelf) {
  1190. bindings._self = bindSelf;
  1191. }
  1192. if (aOptions.selectedNodeActor) {
  1193. let actor = this.conn.getActor(aOptions.selectedNodeActor);
  1194. if (actor) {
  1195. helpers.selectedNode = actor.rawNode;
  1196. }
  1197. }
  1198. // Check if the Debugger.Frame or Debugger.Object for the global include
  1199. // $ or $$. We will not overwrite these functions with the Web Console
  1200. // commands.
  1201. let found$ = false, found$$ = false;
  1202. if (frame) {
  1203. let env = frame.environment;
  1204. if (env) {
  1205. found$ = !!env.find("$");
  1206. found$$ = !!env.find("$$");
  1207. }
  1208. }
  1209. else {
  1210. found$ = !!dbgWindow.getOwnPropertyDescriptor("$");
  1211. found$$ = !!dbgWindow.getOwnPropertyDescriptor("$$");
  1212. }
  1213. let $ = null, $$ = null;
  1214. if (found$) {
  1215. $ = bindings.$;
  1216. delete bindings.$;
  1217. }
  1218. if (found$$) {
  1219. $$ = bindings.$$;
  1220. delete bindings.$$;
  1221. }
  1222. // Ready to evaluate the string.
  1223. helpers.evalInput = aString;
  1224. let evalOptions;
  1225. if (typeof aOptions.url == "string") {
  1226. evalOptions = { url: aOptions.url };
  1227. }
  1228. // If the debugger object is changed from the last evaluation,
  1229. // adopt this._lastConsoleInputEvaluation value in the new debugger,
  1230. // to prevents "Debugger.Object belongs to a different Debugger" exceptions
  1231. // related to the $_ bindings.
  1232. if (this._lastConsoleInputEvaluation &&
  1233. this._lastConsoleInputEvaluation.global !== dbgWindow) {
  1234. this._lastConsoleInputEvaluation = dbg.adoptDebuggeeValue(
  1235. this._lastConsoleInputEvaluation
  1236. );
  1237. }
  1238. let result;
  1239. if (frame) {
  1240. result = frame.evalWithBindings(aString, bindings, evalOptions);
  1241. }
  1242. else {
  1243. result = dbgWindow.executeInGlobalWithBindings(aString, bindings, evalOptions);
  1244. // Attempt to initialize any declarations found in the evaluated string
  1245. // since they may now be stuck in an "initializing" state due to the
  1246. // error. Already-initialized bindings will be ignored.
  1247. if ("throw" in result) {
  1248. let ast;
  1249. // Parse errors will raise an exception. We can/should ignore the error
  1250. // since it's already being handled elsewhere and we are only interested
  1251. // in initializing bindings.
  1252. try {
  1253. ast = Parser.reflectionAPI.parse(aString);
  1254. } catch (ex) {
  1255. ast = {"body": []};
  1256. }
  1257. for (let line of ast.body) {
  1258. // Only let and const declarations put bindings into an
  1259. // "initializing" state.
  1260. if (!(line.kind == "let" || line.kind == "const"))
  1261. continue;
  1262. let identifiers = [];
  1263. for (let decl of line.declarations) {
  1264. switch (decl.id.type) {
  1265. case "Identifier":
  1266. // let foo = bar;
  1267. identifiers.push(decl.id.name);
  1268. break;
  1269. case "ArrayPattern":
  1270. // let [foo, bar] = [1, 2];
  1271. // let [foo=99, bar] = [1, 2];
  1272. for (let e of decl.id.elements) {
  1273. if (e.type == "Identifier") {
  1274. identifiers.push(e.name);
  1275. } else if (e.type == "AssignmentExpression") {
  1276. identifiers.push(e.left.name);
  1277. }
  1278. }
  1279. break;
  1280. case "ObjectPattern":
  1281. // let {bilbo, my} = {bilbo: "baggins", my: "precious"};
  1282. // let {blah: foo} = {blah: yabba()}
  1283. // let {blah: foo=99} = {blah: yabba()}
  1284. for (let prop of decl.id.properties) {
  1285. // key
  1286. if (prop.key.type == "Identifier")
  1287. identifiers.push(prop.key.name);
  1288. // value
  1289. if (prop.value.type == "Identifier") {
  1290. identifiers.push(prop.value.name);
  1291. } else if (prop.value.type == "AssignmentExpression") {
  1292. identifiers.push(prop.value.left.name);
  1293. }
  1294. }
  1295. break;
  1296. }
  1297. }
  1298. for (let name of identifiers)
  1299. dbgWindow.forceLexicalInitializationByName(name);
  1300. }
  1301. }
  1302. }
  1303. let helperResult = helpers.helperResult;
  1304. delete helpers.evalInput;
  1305. delete helpers.helperResult;
  1306. delete helpers.selectedNode;
  1307. if ($) {
  1308. bindings.$ = $;
  1309. }
  1310. if ($$) {
  1311. bindings.$$ = $$;
  1312. }
  1313. if (bindings._self) {
  1314. delete bindings._self;
  1315. }
  1316. return {
  1317. result: result,
  1318. helperResult: helperResult,
  1319. dbg: dbg,
  1320. frame: frame,
  1321. window: dbgWindow,
  1322. };
  1323. },
  1324. // Event handlers for various listeners.
  1325. /**
  1326. * Handler for messages received from the ConsoleServiceListener. This method
  1327. * sends the nsIConsoleMessage to the remote Web Console client.
  1328. *
  1329. * @param nsIConsoleMessage aMessage
  1330. * The message we need to send to the client.
  1331. */
  1332. onConsoleServiceMessage: function WCA_onConsoleServiceMessage(aMessage)
  1333. {
  1334. let packet;
  1335. if (aMessage instanceof Ci.nsIScriptError) {
  1336. packet = {
  1337. from: this.actorID,
  1338. type: "pageError",
  1339. pageError: this.preparePageErrorForRemote(aMessage),
  1340. };
  1341. }
  1342. else {
  1343. packet = {
  1344. from: this.actorID,
  1345. type: "logMessage",
  1346. message: this._createStringGrip(aMessage.message),
  1347. timeStamp: aMessage.timeStamp,
  1348. };
  1349. }
  1350. this.conn.send(packet);
  1351. },
  1352. /**
  1353. * Prepare an nsIScriptError to be sent to the client.
  1354. *
  1355. * @param nsIScriptError aPageError
  1356. * The page error we need to send to the client.
  1357. * @return object
  1358. * The object you can send to the remote client.
  1359. */
  1360. preparePageErrorForRemote: function WCA_preparePageErrorForRemote(aPageError)
  1361. {
  1362. let stack = null;
  1363. // Convert stack objects to the JSON attributes expected by client code
  1364. if (aPageError.stack) {
  1365. stack = [];
  1366. let s = aPageError.stack;
  1367. while (s !== null) {
  1368. stack.push({
  1369. filename: s.source,
  1370. lineNumber: s.line,
  1371. columnNumber: s.column,
  1372. functionName: s.functionDisplayName
  1373. });
  1374. s = s.parent;
  1375. }
  1376. }
  1377. let lineText = aPageError.sourceLine;
  1378. if (lineText && lineText.length > DebuggerServer.LONG_STRING_INITIAL_LENGTH) {
  1379. lineText = lineText.substr(0, DebuggerServer.LONG_STRING_INITIAL_LENGTH);
  1380. }
  1381. let notesArray = null;
  1382. let notes = aPageError.notes;
  1383. if (notes && notes.length) {
  1384. notesArray = [];
  1385. for (let i = 0, len = notes.length; i < len; i++) {
  1386. let note = notes.queryElementAt(i, Ci.nsIScriptErrorNote);
  1387. notesArray.push({
  1388. messageBody: this._createStringGrip(note.errorMessage),
  1389. frame: {
  1390. source: note.sourceName,
  1391. line: note.lineNumber,
  1392. column: note.columnNumber,
  1393. }
  1394. });
  1395. }
  1396. }
  1397. return {
  1398. errorMessage: this._createStringGrip(aPageError.errorMessage),
  1399. errorMessageName: aPageError.errorMessageName,
  1400. exceptionDocURL: ErrorDocs.GetURL(aPageError),
  1401. sourceName: aPageError.sourceName,
  1402. lineText: lineText,
  1403. lineNumber: aPageError.lineNumber,
  1404. columnNumber: aPageError.columnNumber,
  1405. category: aPageError.category,
  1406. timeStamp: aPageError.timeStamp,
  1407. warning: !!(aPageError.flags & aPageError.warningFlag),
  1408. error: !!(aPageError.flags & aPageError.errorFlag),
  1409. exception: !!(aPageError.flags & aPageError.exceptionFlag),
  1410. strict: !!(aPageError.flags & aPageError.strictFlag),
  1411. info: !!(aPageError.flags & aPageError.infoFlag),
  1412. private: aPageError.isFromPrivateWindow,
  1413. stacktrace: stack,
  1414. notes: notesArray,
  1415. };
  1416. },
  1417. /**
  1418. * Handler for window.console API calls received from the ConsoleAPIListener.
  1419. * This method sends the object to the remote Web Console client.
  1420. *
  1421. * @see ConsoleAPIListener
  1422. * @param object aMessage
  1423. * The console API call we need to send to the remote client.
  1424. */
  1425. onConsoleAPICall: function WCA_onConsoleAPICall(aMessage)
  1426. {
  1427. let packet = {
  1428. from: this.actorID,
  1429. type: "consoleAPICall",
  1430. message: this.prepareConsoleMessageForRemote(aMessage),
  1431. };
  1432. this.conn.send(packet);
  1433. },
  1434. /**
  1435. * Handler for network events. This method is invoked when a new network event
  1436. * is about to be recorded.
  1437. *
  1438. * @see NetworkEventActor
  1439. * @see NetworkMonitor from webconsole/utils.js
  1440. *
  1441. * @param object aEvent
  1442. * The initial network request event information.
  1443. * @return object
  1444. * A new NetworkEventActor is returned. This is used for tracking the
  1445. * network request and response.
  1446. */
  1447. onNetworkEvent: function WCA_onNetworkEvent(aEvent)
  1448. {
  1449. let actor = this.getNetworkEventActor(aEvent.channelId);
  1450. actor.init(aEvent);
  1451. let packet = {
  1452. from: this.actorID,
  1453. type: "networkEvent",
  1454. eventActor: actor.grip()
  1455. };
  1456. this.conn.send(packet);
  1457. return actor;
  1458. },
  1459. /**
  1460. * Get the NetworkEventActor for a nsIHttpChannel, if it exists,
  1461. * otherwise create a new one.
  1462. *
  1463. * @param string channelId
  1464. * The id of the channel for the network event.
  1465. * @return object
  1466. * The NetworkEventActor for the given channel.
  1467. */
  1468. getNetworkEventActor: function WCA_getNetworkEventActor(channelId) {
  1469. let actor = this._netEvents.get(channelId);
  1470. if (actor) {
  1471. // delete from map as we should only need to do this check once
  1472. this._netEvents.delete(channelId);
  1473. return actor;
  1474. }
  1475. actor = new NetworkEventActor(this);
  1476. this._actorPool.addActor(actor);
  1477. return actor;
  1478. },
  1479. /**
  1480. * Send a new HTTP request from the target's window.
  1481. *
  1482. * @param object message
  1483. * Object with 'request' - the HTTP request details.
  1484. */
  1485. onSendHTTPRequest(message) {
  1486. let { url, method, headers, body } = message.request;
  1487. // Set the loadingNode and loadGroup to the target document - otherwise the
  1488. // request won't show up in the opened netmonitor.
  1489. let doc = this.window.document;
  1490. let channel = NetUtil.newChannel({
  1491. uri: NetUtil.newURI(url),
  1492. loadingNode: doc,
  1493. securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  1494. contentPolicyType: Ci.nsIContentPolicy.TYPE_OTHER
  1495. });
  1496. channel.QueryInterface(Ci.nsIHttpChannel);
  1497. channel.loadGroup = doc.documentLoadGroup;
  1498. channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE |
  1499. Ci.nsIRequest.INHIBIT_CACHING |
  1500. Ci.nsIRequest.LOAD_ANONYMOUS;
  1501. channel.requestMethod = method;
  1502. for (let {name, value} of headers) {
  1503. channel.setRequestHeader(name, value, false);
  1504. }
  1505. if (body) {
  1506. channel.QueryInterface(Ci.nsIUploadChannel2);
  1507. let bodyStream = Cc["@mozilla.org/io/string-input-stream;1"]
  1508. .createInstance(Ci.nsIStringInputStream);
  1509. bodyStream.setData(body, body.length);
  1510. channel.explicitSetUploadStream(bodyStream, null, -1, method, false);
  1511. }
  1512. NetUtil.asyncFetch(channel, () => {});
  1513. let actor = this.getNetworkEventActor(channel.channelId);
  1514. // map channel to actor so we can associate future events with it
  1515. this._netEvents.set(channel.channelId, actor);
  1516. return {
  1517. from: this.actorID,
  1518. eventActor: actor.grip()
  1519. };
  1520. },
  1521. /**
  1522. * Handler for file activity. This method sends the file request information
  1523. * to the remote Web Console client.
  1524. *
  1525. * @see ConsoleProgressListener
  1526. * @param string aFileURI
  1527. * The requested file URI.
  1528. */
  1529. onFileActivity: function WCA_onFileActivity(aFileURI)
  1530. {
  1531. let packet = {
  1532. from: this.actorID,
  1533. type: "fileActivity",
  1534. uri: aFileURI,
  1535. };
  1536. this.conn.send(packet);
  1537. },
  1538. /**
  1539. * Handler for reflow activity. This method forwards reflow events to the
  1540. * remote Web Console client.
  1541. *
  1542. * @see ConsoleReflowListener
  1543. * @param Object aReflowInfo
  1544. */
  1545. onReflowActivity: function WCA_onReflowActivity(aReflowInfo)
  1546. {
  1547. let packet = {
  1548. from: this.actorID,
  1549. type: "reflowActivity",
  1550. interruptible: aReflowInfo.interruptible,
  1551. start: aReflowInfo.start,
  1552. end: aReflowInfo.end,
  1553. sourceURL: aReflowInfo.sourceURL,
  1554. sourceLine: aReflowInfo.sourceLine,
  1555. functionName: aReflowInfo.functionName
  1556. };
  1557. this.conn.send(packet);
  1558. },
  1559. /**
  1560. * Handler for server logging. This method forwards log events to the
  1561. * remote Web Console client.
  1562. *
  1563. * @see ServerLoggingListener
  1564. * @param object aMessage
  1565. * The console API call on the server we need to send to the remote client.
  1566. */
  1567. onServerLogCall: function WCA_onServerLogCall(aMessage)
  1568. {
  1569. // Clone all data into the content scope (that's where
  1570. // passed arguments comes from).
  1571. let msg = Cu.cloneInto(aMessage, this.window);
  1572. // All arguments within the message need to be converted into
  1573. // debuggees to properly send it to the client side.
  1574. // Use the default target: this.window as the global object
  1575. // since that's the correct scope for data in the message.
  1576. // The 'false' argument passed into prepareConsoleMessageForRemote()
  1577. // ensures that makeDebuggeeValue uses content debuggee.
  1578. // See also:
  1579. // * makeDebuggeeValue()
  1580. // * prepareConsoleMessageForRemote()
  1581. msg = this.prepareConsoleMessageForRemote(msg, false);
  1582. let packet = {
  1583. from: this.actorID,
  1584. type: "serverLogCall",
  1585. message: msg,
  1586. };
  1587. this.conn.send(packet);
  1588. },
  1589. // End of event handlers for various listeners.
  1590. /**
  1591. * Prepare a message from the console API to be sent to the remote Web Console
  1592. * instance.
  1593. *
  1594. * @param object aMessage
  1595. * The original message received from console-api-log-event.
  1596. * @param boolean aUseObjectGlobal
  1597. * If |true| the object global is determined and added as a debuggee,
  1598. * otherwise |this.window| is used when makeDebuggeeValue() is invoked.
  1599. * @return object
  1600. * The object that can be sent to the remote client.
  1601. */
  1602. prepareConsoleMessageForRemote:
  1603. function WCA_prepareConsoleMessageForRemote(aMessage, aUseObjectGlobal = true)
  1604. {
  1605. let result = WebConsoleUtils.cloneObject(aMessage);
  1606. result.workerType = WebConsoleUtils.getWorkerType(result) || "none";
  1607. delete result.wrappedJSObject;
  1608. delete result.ID;
  1609. delete result.innerID;
  1610. delete result.consoleID;
  1611. result.arguments = Array.map(aMessage.arguments || [], (aObj) => {
  1612. let dbgObj = this.makeDebuggeeValue(aObj, aUseObjectGlobal);
  1613. return this.createValueGrip(dbgObj);
  1614. });
  1615. result.styles = Array.map(aMessage.styles || [], (aString) => {
  1616. return this.createValueGrip(aString);
  1617. });
  1618. result.category = aMessage.category || "webdev";
  1619. return result;
  1620. },
  1621. /**
  1622. * Find the XUL window that owns the content window.
  1623. *
  1624. * @return Window
  1625. * The XUL window that owns the content window.
  1626. */
  1627. chromeWindow: function WCA_chromeWindow()
  1628. {
  1629. let window = null;
  1630. try {
  1631. window = this.window.QueryInterface(Ci.nsIInterfaceRequestor)
  1632. .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShell)
  1633. .chromeEventHandler.ownerDocument.defaultView;
  1634. }
  1635. catch (ex) {
  1636. // The above can fail because chromeEventHandler is not available for all
  1637. // kinds of |this.window|.
  1638. }
  1639. return window;
  1640. },
  1641. /**
  1642. * Notification observer for the "last-pb-context-exited" topic.
  1643. *
  1644. * @private
  1645. * @param object aSubject
  1646. * Notification subject - in this case it is the inner window ID that
  1647. * was destroyed.
  1648. * @param string aTopic
  1649. * Notification topic.
  1650. */
  1651. _onObserverNotification: function WCA__onObserverNotification(aSubject, aTopic)
  1652. {
  1653. switch (aTopic) {
  1654. case "last-pb-context-exited":
  1655. this.conn.send({
  1656. from: this.actorID,
  1657. type: "lastPrivateContextExited",
  1658. });
  1659. break;
  1660. }
  1661. },
  1662. /**
  1663. * The "will-navigate" progress listener. This is used to clear the current
  1664. * eval scope.
  1665. */
  1666. _onWillNavigate: function WCA__onWillNavigate({ window, isTopLevel })
  1667. {
  1668. if (isTopLevel) {
  1669. this._evalWindow = null;
  1670. events.off(this.parentActor, "will-navigate", this._onWillNavigate);
  1671. this._progressListenerActive = false;
  1672. }
  1673. },
  1674. /**
  1675. * This listener is called when we switch to another frame,
  1676. * mostly to unregister previous listeners and start listening on the new document.
  1677. */
  1678. _onChangedToplevelDocument: function WCA__onChangedToplevelDocument()
  1679. {
  1680. // Convert the Set to an Array
  1681. let listeners = [...this._listeners];
  1682. // Unregister existing listener on the previous document
  1683. // (pass a copy of the array as it will shift from it)
  1684. this.onStopListeners({listeners: listeners.slice()});
  1685. // This method is called after this.window is changed,
  1686. // so we register new listener on this new window
  1687. this.onStartListeners({listeners: listeners});
  1688. // Also reset the cached top level chrome window being targeted
  1689. this._lastChromeWindow = null;
  1690. },
  1691. };
  1692. WebConsoleActor.prototype.requestTypes =
  1693. {
  1694. startListeners: WebConsoleActor.prototype.onStartListeners,
  1695. stopListeners: WebConsoleActor.prototype.onStopListeners,
  1696. getCachedMessages: WebConsoleActor.prototype.onGetCachedMessages,
  1697. evaluateJS: WebConsoleActor.prototype.onEvaluateJS,
  1698. evaluateJSAsync: WebConsoleActor.prototype.onEvaluateJSAsync,
  1699. autocomplete: WebConsoleActor.prototype.onAutocomplete,
  1700. clearMessagesCache: WebConsoleActor.prototype.onClearMessagesCache,
  1701. getPreferences: WebConsoleActor.prototype.onGetPreferences,
  1702. setPreferences: WebConsoleActor.prototype.onSetPreferences,
  1703. sendHTTPRequest: WebConsoleActor.prototype.onSendHTTPRequest
  1704. };
  1705. exports.WebConsoleActor = WebConsoleActor;
  1706. /**
  1707. * Creates an actor for a network event.
  1708. *
  1709. * @constructor
  1710. * @param object webConsoleActor
  1711. * The parent WebConsoleActor instance for this object.
  1712. */
  1713. function NetworkEventActor(webConsoleActor) {
  1714. this.parent = webConsoleActor;
  1715. this.conn = this.parent.conn;
  1716. this._request = {
  1717. method: null,
  1718. url: null,
  1719. httpVersion: null,
  1720. headers: [],
  1721. cookies: [],
  1722. headersSize: null,
  1723. postData: {},
  1724. };
  1725. this._response = {
  1726. headers: [],
  1727. cookies: [],
  1728. content: {},
  1729. };
  1730. this._timings = {};
  1731. // Keep track of LongStringActors owned by this NetworkEventActor.
  1732. this._longStringActors = new Set();
  1733. }
  1734. NetworkEventActor.prototype =
  1735. {
  1736. _request: null,
  1737. _response: null,
  1738. _timings: null,
  1739. _longStringActors: null,
  1740. actorPrefix: "netEvent",
  1741. /**
  1742. * Returns a grip for this actor for returning in a protocol message.
  1743. */
  1744. grip: function NEA_grip()
  1745. {
  1746. return {
  1747. actor: this.actorID,
  1748. startedDateTime: this._startedDateTime,
  1749. timeStamp: Date.parse(this._startedDateTime),
  1750. url: this._request.url,
  1751. method: this._request.method,
  1752. isXHR: this._isXHR,
  1753. cause: this._cause,
  1754. fromCache: this._fromCache,
  1755. fromServiceWorker: this._fromServiceWorker,
  1756. private: this._private,
  1757. };
  1758. },
  1759. /**
  1760. * Releases this actor from the pool.
  1761. */
  1762. release: function NEA_release()
  1763. {
  1764. for (let grip of this._longStringActors) {
  1765. let actor = this.parent.getActorByID(grip.actor);
  1766. if (actor) {
  1767. this.parent.releaseActor(actor);
  1768. }
  1769. }
  1770. this._longStringActors = new Set();
  1771. if (this.channel) {
  1772. this.parent._netEvents.delete(this.channel);
  1773. }
  1774. this.parent.releaseActor(this);
  1775. },
  1776. /**
  1777. * Handle a protocol request to release a grip.
  1778. */
  1779. onRelease: function NEA_onRelease()
  1780. {
  1781. this.release();
  1782. return {};
  1783. },
  1784. /**
  1785. * Set the properties of this actor based on it's corresponding
  1786. * network event.
  1787. *
  1788. * @param object aNetworkEvent
  1789. * The network event associated with this actor.
  1790. */
  1791. init: function NEA_init(aNetworkEvent)
  1792. {
  1793. this._startedDateTime = aNetworkEvent.startedDateTime;
  1794. this._isXHR = aNetworkEvent.isXHR;
  1795. this._cause = aNetworkEvent.cause;
  1796. this._fromCache = aNetworkEvent.fromCache;
  1797. this._fromServiceWorker = aNetworkEvent.fromServiceWorker;
  1798. for (let prop of ["method", "url", "httpVersion", "headersSize"]) {
  1799. this._request[prop] = aNetworkEvent[prop];
  1800. }
  1801. this._discardRequestBody = aNetworkEvent.discardRequestBody;
  1802. this._discardResponseBody = aNetworkEvent.discardResponseBody;
  1803. this._private = aNetworkEvent.private;
  1804. },
  1805. /**
  1806. * The "getRequestHeaders" packet type handler.
  1807. *
  1808. * @return object
  1809. * The response packet - network request headers.
  1810. */
  1811. onGetRequestHeaders: function NEA_onGetRequestHeaders()
  1812. {
  1813. return {
  1814. from: this.actorID,
  1815. headers: this._request.headers,
  1816. headersSize: this._request.headersSize,
  1817. rawHeaders: this._request.rawHeaders,
  1818. };
  1819. },
  1820. /**
  1821. * The "getRequestCookies" packet type handler.
  1822. *
  1823. * @return object
  1824. * The response packet - network request cookies.
  1825. */
  1826. onGetRequestCookies: function NEA_onGetRequestCookies()
  1827. {
  1828. return {
  1829. from: this.actorID,
  1830. cookies: this._request.cookies,
  1831. };
  1832. },
  1833. /**
  1834. * The "getRequestPostData" packet type handler.
  1835. *
  1836. * @return object
  1837. * The response packet - network POST data.
  1838. */
  1839. onGetRequestPostData: function NEA_onGetRequestPostData()
  1840. {
  1841. return {
  1842. from: this.actorID,
  1843. postData: this._request.postData,
  1844. postDataDiscarded: this._discardRequestBody,
  1845. };
  1846. },
  1847. /**
  1848. * The "getSecurityInfo" packet type handler.
  1849. *
  1850. * @return object
  1851. * The response packet - connection security information.
  1852. */
  1853. onGetSecurityInfo: function NEA_onGetSecurityInfo()
  1854. {
  1855. return {
  1856. from: this.actorID,
  1857. securityInfo: this._securityInfo,
  1858. };
  1859. },
  1860. /**
  1861. * The "getResponseHeaders" packet type handler.
  1862. *
  1863. * @return object
  1864. * The response packet - network response headers.
  1865. */
  1866. onGetResponseHeaders: function NEA_onGetResponseHeaders()
  1867. {
  1868. return {
  1869. from: this.actorID,
  1870. headers: this._response.headers,
  1871. headersSize: this._response.headersSize,
  1872. rawHeaders: this._response.rawHeaders,
  1873. };
  1874. },
  1875. /**
  1876. * The "getResponseCookies" packet type handler.
  1877. *
  1878. * @return object
  1879. * The response packet - network response cookies.
  1880. */
  1881. onGetResponseCookies: function NEA_onGetResponseCookies()
  1882. {
  1883. return {
  1884. from: this.actorID,
  1885. cookies: this._response.cookies,
  1886. };
  1887. },
  1888. /**
  1889. * The "getResponseContent" packet type handler.
  1890. *
  1891. * @return object
  1892. * The response packet - network response content.
  1893. */
  1894. onGetResponseContent: function NEA_onGetResponseContent()
  1895. {
  1896. return {
  1897. from: this.actorID,
  1898. content: this._response.content,
  1899. contentDiscarded: this._discardResponseBody,
  1900. };
  1901. },
  1902. /**
  1903. * The "getEventTimings" packet type handler.
  1904. *
  1905. * @return object
  1906. * The response packet - network event timings.
  1907. */
  1908. onGetEventTimings: function NEA_onGetEventTimings()
  1909. {
  1910. return {
  1911. from: this.actorID,
  1912. timings: this._timings,
  1913. totalTime: this._totalTime
  1914. };
  1915. },
  1916. /** ****************************************************************
  1917. * Listeners for new network event data coming from NetworkMonitor.
  1918. ******************************************************************/
  1919. /**
  1920. * Add network request headers.
  1921. *
  1922. * @param array aHeaders
  1923. * The request headers array.
  1924. * @param string aRawHeaders
  1925. * The raw headers source.
  1926. */
  1927. addRequestHeaders: function NEA_addRequestHeaders(aHeaders, aRawHeaders)
  1928. {
  1929. this._request.headers = aHeaders;
  1930. this._prepareHeaders(aHeaders);
  1931. var rawHeaders = this.parent._createStringGrip(aRawHeaders);
  1932. if (typeof rawHeaders == "object") {
  1933. this._longStringActors.add(rawHeaders);
  1934. }
  1935. this._request.rawHeaders = rawHeaders;
  1936. let packet = {
  1937. from: this.actorID,
  1938. type: "networkEventUpdate",
  1939. updateType: "requestHeaders",
  1940. headers: aHeaders.length,
  1941. headersSize: this._request.headersSize,
  1942. };
  1943. this.conn.send(packet);
  1944. },
  1945. /**
  1946. * Add network request cookies.
  1947. *
  1948. * @param array aCookies
  1949. * The request cookies array.
  1950. */
  1951. addRequestCookies: function NEA_addRequestCookies(aCookies)
  1952. {
  1953. this._request.cookies = aCookies;
  1954. this._prepareHeaders(aCookies);
  1955. let packet = {
  1956. from: this.actorID,
  1957. type: "networkEventUpdate",
  1958. updateType: "requestCookies",
  1959. cookies: aCookies.length,
  1960. };
  1961. this.conn.send(packet);
  1962. },
  1963. /**
  1964. * Add network request POST data.
  1965. *
  1966. * @param object aPostData
  1967. * The request POST data.
  1968. */
  1969. addRequestPostData: function NEA_addRequestPostData(aPostData)
  1970. {
  1971. this._request.postData = aPostData;
  1972. aPostData.text = this.parent._createStringGrip(aPostData.text);
  1973. if (typeof aPostData.text == "object") {
  1974. this._longStringActors.add(aPostData.text);
  1975. }
  1976. let packet = {
  1977. from: this.actorID,
  1978. type: "networkEventUpdate",
  1979. updateType: "requestPostData",
  1980. dataSize: aPostData.text.length,
  1981. discardRequestBody: this._discardRequestBody,
  1982. };
  1983. this.conn.send(packet);
  1984. },
  1985. /**
  1986. * Add the initial network response information.
  1987. *
  1988. * @param object aInfo
  1989. * The response information.
  1990. * @param string aRawHeaders
  1991. * The raw headers source.
  1992. */
  1993. addResponseStart: function NEA_addResponseStart(aInfo, aRawHeaders)
  1994. {
  1995. var rawHeaders = this.parent._createStringGrip(aRawHeaders);
  1996. if (typeof rawHeaders == "object") {
  1997. this._longStringActors.add(rawHeaders);
  1998. }
  1999. this._response.rawHeaders = rawHeaders;
  2000. this._response.httpVersion = aInfo.httpVersion;
  2001. this._response.status = aInfo.status;
  2002. this._response.statusText = aInfo.statusText;
  2003. this._response.headersSize = aInfo.headersSize;
  2004. this._discardResponseBody = aInfo.discardResponseBody;
  2005. let packet = {
  2006. from: this.actorID,
  2007. type: "networkEventUpdate",
  2008. updateType: "responseStart",
  2009. response: aInfo
  2010. };
  2011. this.conn.send(packet);
  2012. },
  2013. /**
  2014. * Add connection security information.
  2015. *
  2016. * @param object info
  2017. * The object containing security information.
  2018. */
  2019. addSecurityInfo: function NEA_addSecurityInfo(info)
  2020. {
  2021. this._securityInfo = info;
  2022. let packet = {
  2023. from: this.actorID,
  2024. type: "networkEventUpdate",
  2025. updateType: "securityInfo",
  2026. state: info.state,
  2027. };
  2028. this.conn.send(packet);
  2029. },
  2030. /**
  2031. * Add network response headers.
  2032. *
  2033. * @param array aHeaders
  2034. * The response headers array.
  2035. */
  2036. addResponseHeaders: function NEA_addResponseHeaders(aHeaders)
  2037. {
  2038. this._response.headers = aHeaders;
  2039. this._prepareHeaders(aHeaders);
  2040. let packet = {
  2041. from: this.actorID,
  2042. type: "networkEventUpdate",
  2043. updateType: "responseHeaders",
  2044. headers: aHeaders.length,
  2045. headersSize: this._response.headersSize,
  2046. };
  2047. this.conn.send(packet);
  2048. },
  2049. /**
  2050. * Add network response cookies.
  2051. *
  2052. * @param array aCookies
  2053. * The response cookies array.
  2054. */
  2055. addResponseCookies: function NEA_addResponseCookies(aCookies)
  2056. {
  2057. this._response.cookies = aCookies;
  2058. this._prepareHeaders(aCookies);
  2059. let packet = {
  2060. from: this.actorID,
  2061. type: "networkEventUpdate",
  2062. updateType: "responseCookies",
  2063. cookies: aCookies.length,
  2064. };
  2065. this.conn.send(packet);
  2066. },
  2067. /**
  2068. * Add network response content.
  2069. *
  2070. * @param object aContent
  2071. * The response content.
  2072. * @param boolean aDiscardedResponseBody
  2073. * Tells if the response content was recorded or not.
  2074. */
  2075. addResponseContent:
  2076. function NEA_addResponseContent(aContent, aDiscardedResponseBody)
  2077. {
  2078. this._response.content = aContent;
  2079. aContent.text = this.parent._createStringGrip(aContent.text);
  2080. if (typeof aContent.text == "object") {
  2081. this._longStringActors.add(aContent.text);
  2082. }
  2083. let packet = {
  2084. from: this.actorID,
  2085. type: "networkEventUpdate",
  2086. updateType: "responseContent",
  2087. mimeType: aContent.mimeType,
  2088. contentSize: aContent.size,
  2089. encoding: aContent.encoding,
  2090. transferredSize: aContent.transferredSize,
  2091. discardResponseBody: aDiscardedResponseBody,
  2092. };
  2093. this.conn.send(packet);
  2094. },
  2095. /**
  2096. * Add network event timing information.
  2097. *
  2098. * @param number aTotal
  2099. * The total time of the network event.
  2100. * @param object aTimings
  2101. * Timing details about the network event.
  2102. */
  2103. addEventTimings: function NEA_addEventTimings(aTotal, aTimings)
  2104. {
  2105. this._totalTime = aTotal;
  2106. this._timings = aTimings;
  2107. let packet = {
  2108. from: this.actorID,
  2109. type: "networkEventUpdate",
  2110. updateType: "eventTimings",
  2111. totalTime: aTotal
  2112. };
  2113. this.conn.send(packet);
  2114. },
  2115. /**
  2116. * Prepare the headers array to be sent to the client by using the
  2117. * LongStringActor for the header values, when needed.
  2118. *
  2119. * @private
  2120. * @param array aHeaders
  2121. */
  2122. _prepareHeaders: function NEA__prepareHeaders(aHeaders)
  2123. {
  2124. for (let header of aHeaders) {
  2125. header.value = this.parent._createStringGrip(header.value);
  2126. if (typeof header.value == "object") {
  2127. this._longStringActors.add(header.value);
  2128. }
  2129. }
  2130. },
  2131. };
  2132. NetworkEventActor.prototype.requestTypes =
  2133. {
  2134. "release": NetworkEventActor.prototype.onRelease,
  2135. "getRequestHeaders": NetworkEventActor.prototype.onGetRequestHeaders,
  2136. "getRequestCookies": NetworkEventActor.prototype.onGetRequestCookies,
  2137. "getRequestPostData": NetworkEventActor.prototype.onGetRequestPostData,
  2138. "getResponseHeaders": NetworkEventActor.prototype.onGetResponseHeaders,
  2139. "getResponseCookies": NetworkEventActor.prototype.onGetResponseCookies,
  2140. "getResponseContent": NetworkEventActor.prototype.onGetResponseContent,
  2141. "getEventTimings": NetworkEventActor.prototype.onGetEventTimings,
  2142. "getSecurityInfo": NetworkEventActor.prototype.onGetSecurityInfo,
  2143. };