Bug 1568151 - Replace `target.getInspector()` by `target.getFront("inspector")`....
[gecko.git] / remote / JSONHandler.jsm
blob3c4578c2bc96c51a307b88e84d9d4bf955e1a835
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 "use strict";
7 var EXPORTED_SYMBOLS = ["JSONHandler"];
9 const { HTTP_404, HTTP_505 } = ChromeUtils.import(
10   "chrome://remote/content/server/HTTPD.jsm"
12 const { Log } = ChromeUtils.import("chrome://remote/content/Log.jsm");
13 const { Protocol } = ChromeUtils.import("chrome://remote/content/Protocol.jsm");
14 const { RemoteAgentError } = ChromeUtils.import(
15   "chrome://remote/content/Error.jsm"
18 class JSONHandler {
19   constructor(agent) {
20     this.agent = agent;
21     this.routes = {
22       "/json/version": this.getVersion.bind(this),
23       "/json/protocol": this.getProtocol.bind(this),
24       "/json/list": this.getTargetList.bind(this),
25     };
26   }
28   getVersion() {
29     const mainProcessTarget = this.agent.targets.getMainProcessTarget();
30     return {
31       Browser: "Firefox",
32       "Protocol-Version": "1.0",
33       "User-Agent": "Mozilla",
34       "V8-Version": "1.0",
35       "WebKit-Version": "1.0",
36       webSocketDebuggerUrl: mainProcessTarget.toJSON().webSocketDebuggerUrl,
37     };
38   }
40   getProtocol() {
41     return Protocol.Description;
42   }
44   getTargetList() {
45     return [...this.agent.targets];
46   }
48   // nsIHttpRequestHandler
50   handle(request, response) {
51     if (request.method != "GET") {
52       throw HTTP_404;
53     }
55     if (!(request.path in this.routes)) {
56       throw HTTP_404;
57     }
59     try {
60       const body = this.routes[request.path]();
61       const payload = JSON.stringify(
62         body,
63         sanitise,
64         Log.verbose ? "\t" : undefined
65       );
67       response.setStatusLine(request.httpVersion, 200, "OK");
68       response.setHeader("Content-Type", "application/json");
69       response.write(payload);
70     } catch (e) {
71       new RemoteAgentError(e).notify();
72       throw HTTP_505;
73     }
74   }
76   // XPCOM
78   get QueryInterface() {
79     return ChromeUtils.generateQI([Ci.nsIHttpRequestHandler]);
80   }
83 // Filters out null and empty strings
84 function sanitise(key, value) {
85   if (value === null || (typeof value == "string" && value.length == 0)) {
86     return undefined;
87   }
88   return value;