Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(366)

Side by Side Diff: third_party/WebKit/Source/devtools/front_end/protocol/Protocol.js

Issue 2453673002: [DevTools] Scope common protocol infrastructure under Protocol namespace in a separate module. (Closed)
Patch Set: Created 4 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * Copyright (C) 2011 Google Inc. All rights reserved. 2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * 3 *
4 * Redistribution and use in source and binary forms, with or without 4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are 5 * modification, are permitted provided that the following conditions are
6 * met: 6 * met:
7 * 7 *
8 * * Redistributions of source code must retain the above copyright 8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer. 9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above 10 * * Redistributions in binary form must reproduce the above
(...skipping 10 matching lines...) Expand all
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */ 29 */
30 30
31 /** 31 var Protocol = {};
32 * @constructor 32
33 */ 33 /** @typedef {string} */
34 function InspectorBackendClass() 34 Protocol.Error;
35 { 35
36 this._agentPrototypes = {}; 36 Protocol.Options = {
37 this._dispatcherPrototypes = {}; 37 dumpInspectorTimeStats: false,
38 this._initialized = false; 38 dumpInspectorProtocolMessages: false,
39 } 39 suppressRequestErrors: false
40 40 };
41 InspectorBackendClass._DevToolsErrorCode = -32000; 41
42 InspectorBackendClass.DevToolsStubErrorCode = -32015; 42 Protocol.StubErrorCode = -32015;
43
44 /**
45 * @param {string} error
46 * @param {!Object} messageObject
47 */
48 InspectorBackendClass.reportProtocolError = function(error, messageObject)
49 {
50 console.error(error + ": " + JSON.stringify(messageObject));
51 };
52
53 InspectorBackendClass.prototype = {
54 /**
55 * @return {boolean}
56 */
57 isInitialized: function()
58 {
59 return this._initialized;
60 },
61
62 /**
63 * @param {string} domain
64 */
65 _addAgentGetterMethodToProtocolTargetPrototype: function(domain)
66 {
67 var upperCaseLength = 0;
68 while (upperCaseLength < domain.length && domain[upperCaseLength].toLowe rCase() !== domain[upperCaseLength])
69 ++upperCaseLength;
70
71 var methodName = domain.substr(0, upperCaseLength).toLowerCase() + domai n.slice(upperCaseLength) + "Agent";
72
73 /**
74 * @this {Protocol.Target}
75 */
76 function agentGetter()
77 {
78 return this._agents[domain];
79 }
80
81 Protocol.Target.prototype[methodName] = agentGetter;
82
83 /**
84 * @this {Protocol.Target}
85 */
86 function registerDispatcher(dispatcher)
87 {
88 this.registerDispatcher(domain, dispatcher);
89 }
90
91 Protocol.Target.prototype["register" + domain + "Dispatcher"] = register Dispatcher;
92 },
93
94 /**
95 * @param {string} domain
96 * @return {!InspectorBackendClass._AgentPrototype}
97 */
98 _agentPrototype: function(domain)
99 {
100 if (!this._agentPrototypes[domain]) {
101 this._agentPrototypes[domain] = new InspectorBackendClass._AgentProt otype(domain);
102 this._addAgentGetterMethodToProtocolTargetPrototype(domain);
103 }
104
105 return this._agentPrototypes[domain];
106 },
107
108 /**
109 * @param {string} domain
110 * @return {!InspectorBackendClass._DispatcherPrototype}
111 */
112 _dispatcherPrototype: function(domain)
113 {
114 if (!this._dispatcherPrototypes[domain])
115 this._dispatcherPrototypes[domain] = new InspectorBackendClass._Disp atcherPrototype();
116 return this._dispatcherPrototypes[domain];
117 },
118
119 /**
120 * @param {string} method
121 * @param {!Array.<!Object>} signature
122 * @param {!Array.<string>} replyArgs
123 * @param {boolean} hasErrorData
124 */
125 registerCommand: function(method, signature, replyArgs, hasErrorData)
126 {
127 var domainAndMethod = method.split(".");
128 this._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod [1], signature, replyArgs, hasErrorData);
129 this._initialized = true;
130 },
131
132 /**
133 * @param {string} type
134 * @param {!Object} values
135 */
136 registerEnum: function(type, values)
137 {
138 var domainAndMethod = type.split(".");
139 var agentName = domainAndMethod[0] + "Agent";
140 if (!window[agentName])
141 window[agentName] = {};
142
143 window[agentName][domainAndMethod[1]] = values;
144 this._initialized = true;
145 },
146
147 /**
148 * @param {string} eventName
149 * @param {!Object} params
150 */
151 registerEvent: function(eventName, params)
152 {
153 var domain = eventName.split(".")[0];
154 this._dispatcherPrototype(domain).registerEvent(eventName, params);
155 this._initialized = true;
156 },
157
158 /**
159 * @param {function(T)} clientCallback
160 * @param {string} errorPrefix
161 * @param {function(new:T,S)=} constructor
162 * @param {T=} defaultValue
163 * @return {function(?string, S)}
164 * @template T,S
165 */
166 wrapClientCallback: function(clientCallback, errorPrefix, constructor, defau ltValue)
167 {
168 /**
169 * @param {?string} error
170 * @param {S} value
171 * @template S
172 */
173 function callbackWrapper(error, value)
174 {
175 if (error) {
176 console.error(errorPrefix + error);
177 clientCallback(defaultValue);
178 return;
179 }
180 if (constructor)
181 clientCallback(new constructor(value));
182 else
183 clientCallback(value);
184 }
185 return callbackWrapper;
186 }
187 };
188
189 var InspectorBackend = new InspectorBackendClass();
190 43
191 /** 44 /**
192 * @interface 45 * @interface
193 */ 46 */
194 InspectorBackendClass.Connection = function() 47 Protocol.Connection = function()
195 { 48 {
196 }; 49 };
197 50
198 InspectorBackendClass.Connection.prototype = { 51 Protocol.Connection.prototype = {
199 /** 52 /**
200 * @param {string} message 53 * @param {string} message
201 */ 54 */
202 sendMessage: function(message) { }, 55 sendMessage: function(message) { },
203 56
204 /** 57 /**
205 * @return {!Promise} 58 * @return {!Promise}
206 */ 59 */
207 disconnect: function() { }, 60 disconnect: function() { },
208 }; 61 };
209 62
210 /** 63 /**
211 * @typedef {!{ 64 * @typedef {!{
212 * onMessage: function((!Object|string)), 65 * onMessage: function((!Object|string)),
213 * onDisconnect: function(string) 66 * onDisconnect: function(string)
214 * }} 67 * }}
215 */ 68 */
216 InspectorBackendClass.Connection.Params; 69 Protocol.Connection.Params;
caseq 2016/10/26 23:43:20 Let's make it an interface instead.
217 70
218 /** 71 /**
219 * @typedef {function(!InspectorBackendClass.Connection.Params):!InspectorBacken dClass.Connection} 72 * @typedef {function(!Protocol.Connection.Params):!Protocol.Connection}
220 */ 73 */
221 InspectorBackendClass.Connection.Factory; 74 Protocol.Connection.Factory;
222 75
223 var Protocol = {}; 76 /**
224 77 * @return {boolean}
225 /** @typedef {string} */ 78 */
226 Protocol.Error; 79 Protocol.isInitialized = function()
80 {
81 return Protocol._initialized;
82 };
83
84 /**
85 * @param {string} method
86 * @param {!Array.<!Object>} signature
87 * @param {!Array.<string>} replyArgs
88 * @param {boolean} hasErrorData
89 */
90 Protocol.registerCommand = function(method, signature, replyArgs, hasErrorData)
91 {
92 var domainAndMethod = method.split(".");
93 Protocol._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod [1], signature, replyArgs, hasErrorData);
94 Protocol._initialized = true;
95 };
96
97 /**
98 * @param {string} type
99 * @param {!Object} values
100 */
101 Protocol.registerEnum = function(type, values)
102 {
103 var domainAndMethod = type.split(".");
104 var agentName = domainAndMethod[0] + "Agent";
105 if (!window[agentName])
106 window[agentName] = {};
107
108 window[agentName][domainAndMethod[1]] = values;
109 Protocol._initialized = true;
110 };
111
112 /**
113 * @param {string} eventName
114 * @param {!Object} params
115 */
116 Protocol.registerEvent = function(eventName, params)
117 {
118 var domain = eventName.split(".")[0];
119 Protocol._dispatcherPrototype(domain).registerEvent(eventName, params);
120 Protocol._initialized = true;
121 };
122
123 /**
124 * @param {function(T)} clientCallback
125 * @param {string} errorPrefix
126 * @param {function(new:T,S)=} constructor
127 * @param {T=} defaultValue
128 * @return {function(?string, S)}
129 * @template T,S
130 */
131 Protocol.wrapClientCallback = function(clientCallback, errorPrefix, constructor, defaultValue)
132 {
133 /**
134 * @param {?string} error
135 * @param {S} value
136 * @template S
137 */
138 function callbackWrapper(error, value)
139 {
140 if (error) {
141 console.error(errorPrefix + error);
142 clientCallback(defaultValue);
143 return;
144 }
145 if (constructor)
146 clientCallback(new constructor(value));
147 else
148 clientCallback(value);
149 }
150 return callbackWrapper;
151 };
152
153
154 Protocol._DisconnectedErrorCode = -32000;
caseq 2016/10/26 23:43:20 Let's move it up to the rest of error code -- perh
155
156 /**
157 * @param {string} error
158 * @param {!Object} messageObject
159 */
160 Protocol._reportError = function(error, messageObject)
161 {
162 console.error(error + ": " + JSON.stringify(messageObject));
163 };
164
165 /** @type {!Map<string, !Protocol._AgentPrototype>} */
166 Protocol._agentPrototypes = new Map();
167
168 /** @type {!Map<string, !Protocol._DispatcherPrototype>} */
169 Protocol._dispatcherPrototypes = new Map();
170
171 /** @type {boolean} */
172 Protocol._initialized = false;
173
174 /**
175 * @param {string} domain
176 */
177 Protocol._addAgentGetterMethodToProtocolTargetPrototype = function(domain)
178 {
179 var upperCaseLength = 0;
180 while (upperCaseLength < domain.length && domain[upperCaseLength].toLowerCas e() !== domain[upperCaseLength])
181 ++upperCaseLength;
182
183 var methodName = domain.substr(0, upperCaseLength).toLowerCase() + domain.sl ice(upperCaseLength) + "Agent";
184
185 /**
186 * @this {Protocol.Target}
187 */
188 function agentGetter()
189 {
190 return this._agents.get(domain);
191 }
192
193 Protocol.Target.prototype[methodName] = agentGetter;
194
195 /**
196 * @this {Protocol.Target}
197 */
198 function registerDispatcher(dispatcher)
199 {
200 this.registerDispatcher(domain, dispatcher);
201 }
202
203 Protocol.Target.prototype["register" + domain + "Dispatcher"] = registerDisp atcher;
204 };
205
206 /**
207 * @param {string} domain
208 * @return {!Protocol._AgentPrototype}
209 */
210 Protocol._agentPrototype = function(domain)
caseq 2016/10/26 23:43:20 So we now have Protocol._agentPrototype, Protocol.
211 {
212 if (!Protocol._agentPrototypes.has(domain)) {
213 Protocol._agentPrototypes.set(domain, new Protocol._AgentPrototype(domai n));
214 Protocol._addAgentGetterMethodToProtocolTargetPrototype(domain);
215 }
216 return Protocol._agentPrototypes.get(domain);
217 };
218
219 /**
220 * @param {string} domain
221 * @return {!Protocol._DispatcherPrototype}
222 */
223 Protocol._dispatcherPrototype = function(domain)
224 {
225 if (!Protocol._dispatcherPrototypes.has(domain))
226 Protocol._dispatcherPrototypes.set(domain, new Protocol._DispatcherProto type());
227 return Protocol._dispatcherPrototypes.get(domain);
228 };
229
230 /** @typedef {!{methodName: string, domain: string, callback: function(*):?, sen dRequestTime: (number|undefined)}} */
231 Protocol._WrappedCallback;
227 232
228 /** 233 /**
229 * @constructor 234 * @constructor
230 * @param {!InspectorBackendClass.Connection.Factory} connectionFactory 235 * @param {!Protocol.Connection.Factory} connectionFactory
231 */ 236 */
232 Protocol.Target = function(connectionFactory) 237 Protocol.Target = function(connectionFactory)
233 { 238 {
234 this._connection = connectionFactory({onMessage: this._onMessage.bind(this), onDisconnect: this._onDisconnect.bind(this)}); 239 this._connection = connectionFactory({onMessage: this._onMessage.bind(this), onDisconnect: this._onDisconnect.bind(this)});
235 this._lastMessageId = 1; 240 this._lastMessageId = 1;
236 this._pendingResponsesCount = 0; 241 this._pendingResponsesCount = 0;
237 this._agents = {}; 242 /** @type {!Map<string, !Protocol._AgentPrototype>} */
238 this._dispatchers = {}; 243 this._agents = new Map();
239 this._callbacks = {}; 244 /** @type {!Map<string, !Protocol._DispatcherPrototype>} */
240 this._initialize(InspectorBackend._agentPrototypes, InspectorBackend._dispat cherPrototypes); 245 this._dispatchers = new Map();
241 if (!InspectorBackendClass.deprecatedRunAfterPendingDispatches) 246 /** @type {!Map<number, !Protocol._WrappedCallback>} */
242 InspectorBackendClass.deprecatedRunAfterPendingDispatches = this._deprec atedRunAfterPendingDispatches.bind(this); 247 this._callbacks = new Map();
243 if (!InspectorBackendClass.sendRawMessageForTesting) 248
244 InspectorBackendClass.sendRawMessageForTesting = this._sendRawMessageFor Testing.bind(this); 249 for (var domain of Protocol._agentPrototypes.keys()) {
250 var agent = /** @type {!Protocol._AgentPrototype} */ (Object.create(Prot ocol._agentPrototypes.get(domain)));
251 agent.setTarget(this);
252 this._agents.set(domain, agent);
253 }
254
255 for (var domain of Protocol._dispatcherPrototypes.keys()) {
256 var dispatcher = /** @type {!Protocol._DispatcherPrototype} */ (Object.c reate(Protocol._dispatcherPrototypes.get(domain)));
257 this._dispatchers.set(domain, dispatcher);
258 }
259
260 if (!Protocol.deprecatedRunAfterPendingDispatches)
261 Protocol.deprecatedRunAfterPendingDispatches = this._deprecatedRunAfterP endingDispatches.bind(this);
262 if (!Protocol.sendRawMessageForTesting)
263 Protocol.sendRawMessageForTesting = this._sendRawMessageForTesting.bind( this);
245 }; 264 };
246 265
247 Protocol.Target.prototype = { 266 Protocol.Target.prototype = {
248 /** 267 /**
249 * @param {!Object.<string, !InspectorBackendClass._AgentPrototype>} agentPr ototypes
250 * @param {!Object.<string, !InspectorBackendClass._DispatcherPrototype>} di spatcherPrototypes
251 */
252 _initialize: function(agentPrototypes, dispatcherPrototypes)
253 {
254 for (var domain in agentPrototypes) {
255 this._agents[domain] = Object.create(agentPrototypes[domain]);
256 this._agents[domain].setTarget(this);
257 }
258
259 for (var domain in dispatcherPrototypes)
260 this._dispatchers[domain] = Object.create(dispatcherPrototypes[domai n]);
261 },
262
263 /**
264 * @return {number}
265 */
266 _nextMessageId: function()
267 {
268 return this._lastMessageId++;
269 },
270
271 /**
272 * @param {string} domain
273 * @return {!InspectorBackendClass._AgentPrototype}
274 */
275 _agent: function(domain)
276 {
277 return this._agents[domain];
278 },
279
280 /**
281 * @param {string} domain 268 * @param {string} domain
282 * @param {string} method 269 * @param {string} method
283 * @param {?Object} params 270 * @param {?Object} params
284 * @param {?function(*)} callback 271 * @param {?function(*)} callback
285 */ 272 */
286 _wrapCallbackAndSendMessageObject: function(domain, method, params, callback ) 273 _wrapCallbackAndSendMessageObject: function(domain, method, params, callback )
287 { 274 {
288 if (!this._connection) { 275 if (!this._connection) {
289 if (callback) 276 if (callback)
290 this._dispatchConnectionErrorResponse(domain, method, callback); 277 this._dispatchConnectionErrorResponse(domain, method, callback);
291 return; 278 return;
292 } 279 }
293 280
294 var messageObject = {}; 281 var messageObject = {};
295 var messageId = this._nextMessageId(); 282 var messageId = this._lastMessageId++;
296 messageObject.id = messageId; 283 messageObject.id = messageId;
297 messageObject.method = method; 284 messageObject.method = method;
298 if (params) 285 if (params)
299 messageObject.params = params; 286 messageObject.params = params;
300 287
301 var wrappedCallback = this._wrap(callback, domain, method); 288 var wrappedCallback = this._wrap(callback, domain, method);
302 var message = JSON.stringify(messageObject); 289 var message = JSON.stringify(messageObject);
303 290
304 if (InspectorBackendClass.Options.dumpInspectorProtocolMessages) 291 if (Protocol.Options.dumpInspectorProtocolMessages)
305 this._dumpProtocolMessage("frontend: " + message); 292 this._dumpProtocolMessage("frontend: " + message);
306 293
307 this._connection.sendMessage(message); 294 this._connection.sendMessage(message);
308 ++this._pendingResponsesCount; 295 ++this._pendingResponsesCount;
309 this._callbacks[messageId] = wrappedCallback; 296 this._callbacks.set(messageId, wrappedCallback);
310 }, 297 },
311 298
312 /** 299 /**
313 * @param {?function(*)} callback 300 * @param {?function(*)} callback
314 * @param {string} method 301 * @param {string} method
315 * @param {string} domain 302 * @param {string} domain
316 * @return {function(*)} 303 * @return {!Protocol._WrappedCallback}
317 */ 304 */
318 _wrap: function(callback, domain, method) 305 _wrap: function(callback, domain, method)
319 { 306 {
320 if (!callback) 307 callback = /** @type {function(*)} */ (callback || function() {});
321 callback = function() {}; 308 var result = {methodName: method, domain: domain, callback: callback, se ndRequestTime: undefined};
caseq 2016/10/26 23:43:20 nit: drop sendRequestTime?
322 309 if (Protocol.Options.dumpInspectorTimeStats)
323 callback.methodName = method; 310 result.sendRequestTime = Date.now();
324 callback.domain = domain; 311 return result;
325 if (InspectorBackendClass.Options.dumpInspectorTimeStats)
326 callback.sendRequestTime = Date.now();
327
328 return callback;
329 }, 312 },
330 313
331 /** 314 /**
332 * @param {string} method 315 * @param {string} method
333 * @param {?Object} params 316 * @param {?Object} params
334 * @param {?function(...*)} callback 317 * @param {?function(...*)} callback
335 */ 318 */
336 _sendRawMessageForTesting: function(method, params, callback) 319 _sendRawMessageForTesting: function(method, params, callback)
337 { 320 {
338 var domain = method.split(".")[0]; 321 var domain = method.split(".")[0];
339 this._wrapCallbackAndSendMessageObject(domain, method, params, callback) ; 322 this._wrapCallbackAndSendMessageObject(domain, method, params, callback) ;
340 }, 323 },
341 324
342 /** 325 /**
343 * @param {!Object|string} message 326 * @param {!Object|string} message
344 */ 327 */
345 _onMessage: function(message) 328 _onMessage: function(message)
346 { 329 {
347 if (InspectorBackendClass.Options.dumpInspectorProtocolMessages) 330 if (Protocol.Options.dumpInspectorProtocolMessages)
348 this._dumpProtocolMessage("backend: " + ((typeof message === "string ") ? message : JSON.stringify(message))); 331 this._dumpProtocolMessage("backend: " + ((typeof message === "string ") ? message : JSON.stringify(message)));
349 332
350 var messageObject = /** @type {!Object} */ ((typeof message === "string" ) ? JSON.parse(message) : message); 333 var messageObject = /** @type {!Object} */ ((typeof message === "string" ) ? JSON.parse(message) : message);
351 334
352 if ("id" in messageObject) { // just a response for some request 335 if ("id" in messageObject) { // just a response for some request
353 var callback = this._callbacks[messageObject.id]; 336 var callback = this._callbacks.get(messageObject.id);
354 if (!callback) { 337 if (!callback) {
355 InspectorBackendClass.reportProtocolError("Protocol Error: the m essage with wrong id", messageObject); 338 Protocol._reportError("Protocol Error: the message with wrong id ", messageObject);
356 return; 339 return;
357 } 340 }
358 341
359 var processingStartTime; 342 var processingStartTime;
360 if (InspectorBackendClass.Options.dumpInspectorTimeStats) 343 if (Protocol.Options.dumpInspectorTimeStats)
361 processingStartTime = Date.now(); 344 processingStartTime = Date.now();
362 345
363 this._agent(callback.domain).dispatchResponse(messageObject, callbac k.methodName, callback); 346 this._agents.get(callback.domain).dispatchResponse(messageObject, ca llback.methodName, callback.callback);
364 --this._pendingResponsesCount; 347 --this._pendingResponsesCount;
365 delete this._callbacks[messageObject.id]; 348 this._callbacks.delete(messageObject.id);
366 349
367 if (InspectorBackendClass.Options.dumpInspectorTimeStats) 350 if (Protocol.Options.dumpInspectorTimeStats)
368 console.log("time-stats: " + callback.methodName + " = " + (proc essingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingSt artTime)); 351 console.log("time-stats: " + callback.methodName + " = " + (proc essingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingSt artTime));
369 352
370 if (this._scripts && !this._pendingResponsesCount) 353 if (this._scripts && !this._pendingResponsesCount)
371 this._deprecatedRunAfterPendingDispatches(); 354 this._deprecatedRunAfterPendingDispatches();
372 } else { 355 } else {
373 if (!("method" in messageObject)) { 356 if (!("method" in messageObject)) {
374 InspectorBackendClass.reportProtocolError("Protocol Error: the m essage without method", messageObject); 357 Protocol._reportError("Protocol Error: the message without metho d", messageObject);
375 return; 358 return;
376 } 359 }
377 360
378 var method = messageObject.method.split("."); 361 var method = messageObject.method.split(".");
379 var domainName = method[0]; 362 var domainName = method[0];
380 if (!(domainName in this._dispatchers)) { 363 if (!this._dispatchers.has(domainName)) {
381 InspectorBackendClass.reportProtocolError("Protocol Error: the m essage " + messageObject.method + " is for non-existing domain '" + domainName + "'", messageObject); 364 Protocol._reportError("Protocol Error: the message " + messageOb ject.method + " is for non-existing domain '" + domainName + "'", messageObject) ;
382 return; 365 return;
383 } 366 }
384 367
385 this._dispatchers[domainName].dispatch(method[1], messageObject); 368 this._dispatchers.get(domainName).dispatch(method[1], messageObject) ;
386 } 369 }
387 }, 370 },
388 371
389 /** 372 /**
390 * @param {string} domain 373 * @param {string} domain
391 * @param {!Object} dispatcher 374 * @param {!Object} dispatcher
392 */ 375 */
393 registerDispatcher: function(domain, dispatcher) 376 registerDispatcher: function(domain, dispatcher)
394 { 377 {
395 if (!this._dispatchers[domain]) 378 console.assert(this._dispatchers.has(domain));
396 return; 379 this._dispatchers.get(domain).setDomainDispatcher(dispatcher);
397
398 this._dispatchers[domain].setDomainDispatcher(dispatcher);
399 }, 380 },
400 381
401 /** 382 /**
402 * @param {function()=} script 383 * @param {function()=} script
403 */ 384 */
404 _deprecatedRunAfterPendingDispatches: function(script) 385 _deprecatedRunAfterPendingDispatches: function(script)
405 { 386 {
406 if (!this._scripts) 387 if (!this._scripts)
407 this._scripts = []; 388 this._scripts = [];
408 389
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
456 /** 437 /**
457 * @return {boolean} 438 * @return {boolean}
458 */ 439 */
459 isDisposed: function() 440 isDisposed: function()
460 { 441 {
461 return !this._connection; 442 return !this._connection;
462 }, 443 },
463 444
464 _runPendingCallbacks: function() 445 _runPendingCallbacks: function()
465 { 446 {
466 var keys = Object.keys(this._callbacks).map(function(num) { return parse Int(num, 10); }); 447 var callbacks = Array.from(this._callbacks.values());
caseq 2016/10/26 23:43:20 You don't need a copy here, just iterate over valu
467 for (var i = 0; i < keys.length; ++i) { 448 for (var callback of callbacks)
468 var callback = this._callbacks[keys[i]]; 449 this._dispatchConnectionErrorResponse(callback.domain, callback.meth odName, callback.callback);
469 this._dispatchConnectionErrorResponse(callback.domain, callback.meth odName, callback); 450 this._callbacks.clear();
470 }
471 this._callbacks = {};
472 }, 451 },
473 452
474 /** 453 /**
475 * @param {string} domain 454 * @param {string} domain
476 * @param {string} methodName 455 * @param {string} methodName
477 * @param {function(*)} callback 456 * @param {function(*)} callback
478 */ 457 */
479 _dispatchConnectionErrorResponse: function(domain, methodName, callback) 458 _dispatchConnectionErrorResponse: function(domain, methodName, callback)
480 { 459 {
481 var error = { message: "Connection is closed, can't dispatch pending " + methodName, code: InspectorBackendClass._DevToolsErrorCode, data: null}; 460 var error = { message: "Connection is closed, can't dispatch pending " + methodName, code: Protocol._DisconnectedErrorCode, data: null};
482 var messageObject = {error: error}; 461 var messageObject = {error: error};
483 setTimeout(InspectorBackendClass._AgentPrototype.prototype.dispatchRespo nse.bind(this._agent(domain), messageObject, methodName, callback), 0); 462 setTimeout(Protocol._AgentPrototype.prototype.dispatchResponse.bind(this ._agents.get(domain), messageObject, methodName, callback), 0);
484 }, 463 },
485 }; 464 };
486 465
487 /** 466 /**
488 * @constructor 467 * @constructor
489 * @param {string} domain 468 * @param {string} domain
490 */ 469 */
491 InspectorBackendClass._AgentPrototype = function(domain) 470 Protocol._AgentPrototype = function(domain)
492 { 471 {
493 this._replyArgs = {}; 472 this._replyArgs = {};
494 this._hasErrorData = {}; 473 this._hasErrorData = {};
495 this._domain = domain; 474 this._domain = domain;
496 }; 475 };
497 476
498 InspectorBackendClass._AgentPrototype.prototype = { 477 Protocol._AgentPrototype.prototype = {
499 /** 478 /**
500 * @param {!Protocol.Target} target 479 * @param {!Protocol.Target} target
501 */ 480 */
502 setTarget: function(target) 481 setTarget: function(target)
503 { 482 {
504 this._target = target; 483 this._target = target;
505 }, 484 },
506 485
507 /** 486 /**
508 * @param {string} methodName 487 * @param {string} methodName
509 * @param {!Array.<!Object>} signature 488 * @param {!Array.<!Object>} signature
510 * @param {!Array.<string>} replyArgs 489 * @param {!Array.<string>} replyArgs
511 * @param {boolean} hasErrorData 490 * @param {boolean} hasErrorData
512 */ 491 */
513 registerCommand: function(methodName, signature, replyArgs, hasErrorData) 492 registerCommand: function(methodName, signature, replyArgs, hasErrorData)
514 { 493 {
515 var domainAndMethod = this._domain + "." + methodName; 494 var domainAndMethod = this._domain + "." + methodName;
516 495
517 /** 496 /**
518 * @param {...*} vararg 497 * @param {...*} vararg
519 * @this {InspectorBackendClass._AgentPrototype} 498 * @this {Protocol._AgentPrototype}
520 * @return {!Promise.<*>} 499 * @return {!Promise.<*>}
521 */ 500 */
522 function sendMessagePromise(vararg) 501 function sendMessagePromise(vararg)
523 { 502 {
524 var params = Array.prototype.slice.call(arguments); 503 var params = Array.prototype.slice.call(arguments);
525 return InspectorBackendClass._AgentPrototype.prototype._sendMessageT oBackendPromise.call(this, domainAndMethod, signature, params); 504 return Protocol._AgentPrototype.prototype._sendMessageToBackendPromi se.call(this, domainAndMethod, signature, params);
526 } 505 }
527 506
528 this[methodName] = sendMessagePromise; 507 this[methodName] = sendMessagePromise;
529 508
530 /** 509 /**
531 * @param {...*} vararg 510 * @param {...*} vararg
532 * @this {InspectorBackendClass._AgentPrototype} 511 * @this {Protocol._AgentPrototype}
533 */ 512 */
534 function invoke(vararg) 513 function invoke(vararg)
535 { 514 {
536 var params = [domainAndMethod].concat(Array.prototype.slice.call(arg uments)); 515 var params = [domainAndMethod].concat(Array.prototype.slice.call(arg uments));
537 InspectorBackendClass._AgentPrototype.prototype._invoke.apply(this, params); 516 Protocol._AgentPrototype.prototype._invoke.apply(this, params);
538 } 517 }
539 518
540 this["invoke_" + methodName] = invoke; 519 this["invoke_" + methodName] = invoke;
541 520
542 this._replyArgs[domainAndMethod] = replyArgs; 521 this._replyArgs[domainAndMethod] = replyArgs;
543 if (hasErrorData) 522 if (hasErrorData)
544 this._hasErrorData[domainAndMethod] = true; 523 this._hasErrorData[domainAndMethod] = true;
545 }, 524 },
546 525
547 /** 526 /**
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
613 var userCallback = (args.length && typeof args.peekLast() === "function" ) ? args.pop() : null; 592 var userCallback = (args.length && typeof args.peekLast() === "function" ) ? args.pop() : null;
614 var params = this._prepareParameters(method, signature, args, !userCallb ack, onError); 593 var params = this._prepareParameters(method, signature, args, !userCallb ack, onError);
615 if (errorMessage) 594 if (errorMessage)
616 return Promise.reject(new Error(errorMessage)); 595 return Promise.reject(new Error(errorMessage));
617 else 596 else
618 return new Promise(promiseAction.bind(this)); 597 return new Promise(promiseAction.bind(this));
619 598
620 /** 599 /**
621 * @param {function(?)} resolve 600 * @param {function(?)} resolve
622 * @param {function(!Error)} reject 601 * @param {function(!Error)} reject
623 * @this {InspectorBackendClass._AgentPrototype} 602 * @this {Protocol._AgentPrototype}
624 */ 603 */
625 function promiseAction(resolve, reject) 604 function promiseAction(resolve, reject)
626 { 605 {
627 /** 606 /**
628 * @param {...*} vararg 607 * @param {...*} vararg
629 */ 608 */
630 function callback(vararg) 609 function callback(vararg)
631 { 610 {
632 var result = userCallback ? userCallback.apply(null, arguments) : undefined; 611 var result = userCallback ? userCallback.apply(null, arguments) : undefined;
633 resolve(result); 612 resolve(result);
(...skipping 12 matching lines...) Expand all
646 this._target._wrapCallbackAndSendMessageObject(this._domain, method, arg s, callback); 625 this._target._wrapCallbackAndSendMessageObject(this._domain, method, arg s, callback);
647 }, 626 },
648 627
649 /** 628 /**
650 * @param {!Object} messageObject 629 * @param {!Object} messageObject
651 * @param {string} methodName 630 * @param {string} methodName
652 * @param {function(*)|function(?Protocol.Error, ?Object)} callback 631 * @param {function(*)|function(?Protocol.Error, ?Object)} callback
653 */ 632 */
654 dispatchResponse: function(messageObject, methodName, callback) 633 dispatchResponse: function(messageObject, methodName, callback)
655 { 634 {
656 if (messageObject.error && messageObject.error.code !== InspectorBackend Class._DevToolsErrorCode && messageObject.error.code !== InspectorBackendClass.D evToolsStubErrorCode && !InspectorBackendClass.Options.suppressRequestErrors) { 635 if (messageObject.error && messageObject.error.code !== Protocol._Discon nectedErrorCode && messageObject.error.code !== Protocol.StubErrorCode && !Proto col.Options.suppressRequestErrors) {
657 var id = InspectorBackendClass.Options.dumpInspectorProtocolMessages ? " with id = " + messageObject.id : ""; 636 var id = Protocol.Options.dumpInspectorProtocolMessages ? " with id = " + messageObject.id : "";
658 console.error("Request " + methodName + id + " failed. " + JSON.stri ngify(messageObject.error)); 637 console.error("Request " + methodName + id + " failed. " + JSON.stri ngify(messageObject.error));
659 } 638 }
660 639
661 var argumentsArray = []; 640 var argumentsArray = [];
662 argumentsArray[0] = messageObject.error ? messageObject.error.message : null; 641 argumentsArray[0] = messageObject.error ? messageObject.error.message : null;
663 642
664 if (this._hasErrorData[methodName]) 643 if (this._hasErrorData[methodName])
665 argumentsArray[1] = messageObject.error ? messageObject.error.data : null; 644 argumentsArray[1] = messageObject.error ? messageObject.error.data : null;
666 645
667 if (messageObject.result) { 646 if (messageObject.result) {
668 var paramNames = this._replyArgs[methodName] || []; 647 var paramNames = this._replyArgs[methodName] || [];
669 for (var i = 0; i < paramNames.length; ++i) 648 for (var i = 0; i < paramNames.length; ++i)
670 argumentsArray.push(messageObject.result[paramNames[i]]); 649 argumentsArray.push(messageObject.result[paramNames[i]]);
671 } 650 }
672 651
673 callback.apply(null, argumentsArray); 652 callback.apply(null, argumentsArray);
674 }, 653 },
675 }; 654 };
676 655
677 /** 656 /**
678 * @constructor 657 * @constructor
679 */ 658 */
680 InspectorBackendClass._DispatcherPrototype = function() 659 Protocol._DispatcherPrototype = function()
681 { 660 {
682 this._eventArgs = {}; 661 this._eventArgs = {};
683 this._dispatcher = null; 662 this._dispatcher = null;
684 }; 663 };
685 664
686 InspectorBackendClass._DispatcherPrototype.prototype = { 665 Protocol._DispatcherPrototype.prototype = {
687 666
688 /** 667 /**
689 * @param {string} eventName 668 * @param {string} eventName
690 * @param {!Object} params 669 * @param {!Object} params
691 */ 670 */
692 registerEvent: function(eventName, params) 671 registerEvent: function(eventName, params)
693 { 672 {
694 this._eventArgs[eventName] = params; 673 this._eventArgs[eventName] = params;
695 }, 674 },
696 675
697 /** 676 /**
698 * @param {!Object} dispatcher 677 * @param {!Object} dispatcher
699 */ 678 */
700 setDomainDispatcher: function(dispatcher) 679 setDomainDispatcher: function(dispatcher)
701 { 680 {
702 this._dispatcher = dispatcher; 681 this._dispatcher = dispatcher;
703 }, 682 },
704 683
705 /** 684 /**
706 * @param {string} functionName 685 * @param {string} functionName
707 * @param {!Object} messageObject 686 * @param {!Object} messageObject
708 */ 687 */
709 dispatch: function(functionName, messageObject) 688 dispatch: function(functionName, messageObject)
710 { 689 {
711 if (!this._dispatcher) 690 if (!this._dispatcher)
712 return; 691 return;
713 692
714 if (!(functionName in this._dispatcher)) { 693 if (!(functionName in this._dispatcher)) {
715 InspectorBackendClass.reportProtocolError("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'", messageObj ect); 694 Protocol._reportError("Protocol Error: Attempted to dispatch an unim plemented method '" + messageObject.method + "'", messageObject);
716 return; 695 return;
717 } 696 }
718 697
719 if (!this._eventArgs[messageObject.method]) { 698 if (!this._eventArgs[messageObject.method]) {
720 InspectorBackendClass.reportProtocolError("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'", messageObjec t); 699 Protocol._reportError("Protocol Error: Attempted to dispatch an unsp ecified method '" + messageObject.method + "'", messageObject);
721 return; 700 return;
722 } 701 }
723 702
724 var params = []; 703 var params = [];
725 if (messageObject.params) { 704 if (messageObject.params) {
726 var paramNames = this._eventArgs[messageObject.method]; 705 var paramNames = this._eventArgs[messageObject.method];
727 for (var i = 0; i < paramNames.length; ++i) 706 for (var i = 0; i < paramNames.length; ++i)
728 params.push(messageObject.params[paramNames[i]]); 707 params.push(messageObject.params[paramNames[i]]);
729 } 708 }
730 709
731 var processingStartTime; 710 var processingStartTime;
732 if (InspectorBackendClass.Options.dumpInspectorTimeStats) 711 if (Protocol.Options.dumpInspectorTimeStats)
733 processingStartTime = Date.now(); 712 processingStartTime = Date.now();
734 713
735 this._dispatcher[functionName].apply(this._dispatcher, params); 714 this._dispatcher[functionName].apply(this._dispatcher, params);
736 715
737 if (InspectorBackendClass.Options.dumpInspectorTimeStats) 716 if (Protocol.Options.dumpInspectorTimeStats)
738 console.log("time-stats: " + messageObject.method + " = " + (Date.no w() - processingStartTime)); 717 console.log("time-stats: " + messageObject.method + " = " + (Date.no w() - processingStartTime));
739 } 718 }
740 }; 719 };
741
742 InspectorBackendClass.Options = {
743 dumpInspectorTimeStats: false,
744 dumpInspectorProtocolMessages: false,
745 suppressRequestErrors: false
746 };
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698