|
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/. */ |
|
4 |
|
5 'use strict'; |
|
6 |
|
7 module.metadata = { |
|
8 'stability': 'experimental' |
|
9 }; |
|
10 |
|
11 let { request: hostReq, response: hostRes } = require('./host'); |
|
12 let { defer: async } = require('../lang/functional'); |
|
13 let { defer } = require('../core/promise'); |
|
14 let { emit: emitSync, on, off } = require('../event/core'); |
|
15 let { uuid } = require('../util/uuid'); |
|
16 let emit = async(emitSync); |
|
17 |
|
18 // Map of IDs to deferreds |
|
19 let requests = new Map(); |
|
20 |
|
21 // May not be necessary to wrap this in `async` |
|
22 // once promises are async via bug 881047 |
|
23 let receive = async(function ({data, id, error}) { |
|
24 let request = requests.get(id); |
|
25 if (request) { |
|
26 if (error) request.reject(error); |
|
27 else request.resolve(clone(data)); |
|
28 requests.delete(id); |
|
29 } |
|
30 }); |
|
31 on(hostRes, 'data', receive); |
|
32 |
|
33 /* |
|
34 * Send is a helper to be used in client APIs to send |
|
35 * a request to host |
|
36 */ |
|
37 function send (eventName, data) { |
|
38 let id = uuid(); |
|
39 let deferred = defer(); |
|
40 requests.set(id, deferred); |
|
41 emit(hostReq, 'data', { |
|
42 id: id, |
|
43 data: clone(data), |
|
44 event: eventName |
|
45 }); |
|
46 return deferred.promise; |
|
47 } |
|
48 exports.send = send; |
|
49 |
|
50 /* |
|
51 * Implement internal structured cloning algorithm in the future? |
|
52 * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm |
|
53 */ |
|
54 function clone (obj) JSON.parse(JSON.stringify(obj || {})) |