/
messaging.js
343 lines (315 loc) · 8.8 KB
/
messaging.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const TAG = 'amp-viewer-messaging';
export const APP = '__AMPHTML__';
/**
* @enum {string}
*/
export const MessageType = {
REQUEST: 'q',
RESPONSE: 's',
};
/**
* @typedef {{
* app: string,
* type: string,
* requestid: number,
* name: string,
* data: *,
* rsvp: (boolean|undefined),
* error: (string|undefined),
* }}
*/
export let Message;
/**
* @typedef {function(string, *, boolean):(!Promise<*>|undefined)}
*/
export let RequestHandler;
/**
* @param {*} message
* @return {?Message}
*/
export function parseMessage(message) {
if (typeof message != 'string') {
return /** @type {Message} */(message);
}
if (message.charAt(0) != '{') {
return null;
}
try {
return /** @type {?Message} */ (
JSON.parse(/** @type {string} */ (message)));
} catch (e) {
return null;
}
}
/**
* @fileoverview This class is a de-facto implementation of MessagePort
* from Channel Messaging API:
* https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API
*/
export class WindowPortEmulator {
/**
* @param {!Window} win
* @param {string} origin
* @param {!Window} target
*/
constructor(win, origin, target) {
/** @const {!Window} */
this.win = win;
/** @private {string} */
this.origin_ = origin;
/** @const {!Window} */
this.target_ = target;
}
/**
* @param {string} eventType
* @param {function(!Event):undefined} handler
*/
addEventListener(eventType, handler) {
this.win.addEventListener('message', e => {
if (e.origin == this.origin_ &&
e.source == this.target_ && e.data.app == APP) {
handler(e);
}
});
}
/**
* @param {Object} data
*/
postMessage(data) {
this.target_./*OK*/postMessage(data, this.origin_);
}
start() {
}
}
/**
* @fileoverview This is used in amp-viewer-integration.js for the
* communication protocol between AMP and the viewer. In the comments, I will
* refer to the communication as a conversation between me and Bob. The
* messaging protocol should support both sides, but at this point I'm the
* ampdoc and Bob is the viewer.
*/
export class Messaging {
/**
* Conversation (messaging protocol) between me and Bob.
* @param {!Window} win
* @param {!MessagePort|!WindowPortEmulator} port
* @param {boolean} opt_isWebview
*/
constructor(win, port, opt_isWebview) {
/** @const {!Window} */
this.win = win;
/** @const @private {!MessagePort|!WindowPortEmulator} */
this.port_ = port;
/** @const @private */
this.isWebview_ = !!opt_isWebview;
/** @private {!number} */
this.requestIdCounter_ = 0;
/** @private {!Object<number, {resolve: function(*), reject: function(!Error)}>} */
this.waitingForResponse_ = {};
/**
* A map from message names to request handlers.
* @private {!Object<string, !RequestHandler>}
*/
this.messageHandlers_ = {};
/** @private {?RequestHandler} */
this.defaultHandler_ = null;
this.port_.addEventListener('message', this.handleMessage_.bind(this));
this.port_.start();
}
/**
* Registers a method that will handle requests sent to the specified
* message name.
* @param {string} messageName The name of the message to handle.
* @param {!RequestHandler} requestHandler
*/
registerHandler(messageName, requestHandler) {
this.messageHandlers_[messageName] = requestHandler;
}
/**
* Unregisters the handler for the specified message name.
* @param {string} messageName The name of the message to unregister.
*/
unregisterHandler(messageName) {
delete this.messageHandlers_[messageName];
}
/**
* @param {?RequestHandler} requestHandler
*/
setDefaultHandler(requestHandler) {
this.defaultHandler_ = requestHandler;
}
/**
* Bob sent me a message. I need to decide if it's a new request or
* a response to a previous 'conversation' we were having.
* @param {!Event} event
* @private
*/
handleMessage_(event) {
const message = parseMessage(event.data);
if (!message) {
return;
}
if (message.type == MessageType.REQUEST) {
this.handleRequest_(message);
} else if (message.type == MessageType.RESPONSE) {
this.handleResponse_(message);
}
}
/**
* I'm sending Bob a new outgoing request.
* @param {string} messageName
* @param {*} messageData
* @param {boolean} awaitResponse
* @return {!Promise<*>|undefined}
*/
sendRequest(messageName, messageData, awaitResponse) {
const requestId = ++this.requestIdCounter_;
let promise = undefined;
if (awaitResponse) {
promise = new Promise((resolve, reject) => {
this.waitingForResponse_[requestId] = {resolve, reject};
});
}
this.sendMessage_({
app: APP,
requestid: requestId,
type: MessageType.REQUEST,
name: messageName,
data: messageData,
rsvp: awaitResponse,
});
return promise;
}
/**
* I'm responding to a request that Bob made earlier.
* @param {number} requestId
* @param {string} messageName
* @param {*} messageData
* @private
*/
sendResponse_(requestId, messageName, messageData) {
this.sendMessage_({
app: APP,
requestid: requestId,
type: MessageType.RESPONSE,
name: messageName,
data: messageData,
});
}
/**
* @param {number} requestId
* @param {string} messageName
* @param {*} reason !Error most of time, string sometimes, * rarely.
* @private
*/
sendResponseError_(requestId, messageName, reason) {
const errString = this.errorToString_(reason);
this.logError_(
TAG + ': sendResponseError_, Message name: ' + messageName, errString);
this.sendMessage_({
app: APP,
requestid: requestId,
type: MessageType.RESPONSE,
name: messageName,
data: null,
error: errString,
});
}
/**
* @param {Message} message
* @private
*/
sendMessage_(message) {
this.port_./*OK*/postMessage(
this.isWebview_ ? JSON.stringify(message) : message);
}
/**
* I'm handing an incoming request from Bob. I'll either respond normally
* (ex: "got it Bob!") or with an error (ex: "I didn't get a word of what
* you said!").
* @param {Message} message
* @private
*/
handleRequest_(message) {
let handler = this.messageHandlers_[message.name];
if (!handler) {
handler = this.defaultHandler_;
}
if (!handler) {
const error = new Error(
'Cannot handle request because handshake is not yet confirmed!');
error.args = message.name;
throw error;
}
const promise = handler(message.name, message.data, !!message.rsvp);
if (message.rsvp) {
const requestId = message.requestid;
if (!promise) {
this.sendResponseError_(
requestId, message.name, new Error('no response'));
throw new Error('expected response but none given: ' + message.name);
}
promise.then(data => {
this.sendResponse_(requestId, message.name, data);
}, reason => {
this.sendResponseError_(requestId, message.name, reason);
});
}
}
/**
* I sent out a request to Bob. He responded. And now I'm handling that
* response.
* @param {Message} message
* @private
*/
handleResponse_(message) {
const requestId = message.requestid;
const pending = this.waitingForResponse_[requestId];
if (pending) {
delete this.waitingForResponse_[requestId];
if (message.error) {
this.logError_(TAG + ': handleResponse_ error: ', message.error);
pending.reject(
new Error(`Request ${message.name} failed: ${message.error}`));
} else {
pending.resolve(message.data);
}
}
}
/**
* @param {string} state
* @param {!Error|string} opt_data
* @private
*/
logError_(state, opt_data) {
let stateStr = 'amp-messaging-error-logger: ' + state;
const dataStr = ' data: ' + this.errorToString_(opt_data);
stateStr += dataStr;
this.win['viewerState'] = stateStr;
};
/**
* @param {*} err !Error most of time, string sometimes, * rarely.
* @return {string}
* @private
*/
errorToString_(err) {
return err ?
(err.message ? err.message : String(err)) :
'unknown error';
}
}