michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: 'use strict'; michael@0: michael@0: module.metadata = { michael@0: 'stability': 'experimental' michael@0: }; michael@0: michael@0: let { request: hostReq, response: hostRes } = require('./host'); michael@0: let { defer: async } = require('../lang/functional'); michael@0: let { defer } = require('../core/promise'); michael@0: let { emit: emitSync, on, off } = require('../event/core'); michael@0: let { uuid } = require('../util/uuid'); michael@0: let emit = async(emitSync); michael@0: michael@0: // Map of IDs to deferreds michael@0: let requests = new Map(); michael@0: michael@0: // May not be necessary to wrap this in `async` michael@0: // once promises are async via bug 881047 michael@0: let receive = async(function ({data, id, error}) { michael@0: let request = requests.get(id); michael@0: if (request) { michael@0: if (error) request.reject(error); michael@0: else request.resolve(clone(data)); michael@0: requests.delete(id); michael@0: } michael@0: }); michael@0: on(hostRes, 'data', receive); michael@0: michael@0: /* michael@0: * Send is a helper to be used in client APIs to send michael@0: * a request to host michael@0: */ michael@0: function send (eventName, data) { michael@0: let id = uuid(); michael@0: let deferred = defer(); michael@0: requests.set(id, deferred); michael@0: emit(hostReq, 'data', { michael@0: id: id, michael@0: data: clone(data), michael@0: event: eventName michael@0: }); michael@0: return deferred.promise; michael@0: } michael@0: exports.send = send; michael@0: michael@0: /* michael@0: * Implement internal structured cloning algorithm in the future? michael@0: * http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm michael@0: */ michael@0: function clone (obj) JSON.parse(JSON.stringify(obj || {}))