-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
202 lines (170 loc) · 4.83 KB
/
index.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
/* global Promise:false, define:false, module:false, self:false, MessageChannel:false */
'use strict'
var shortid = require('shortid')
var defer = require('mini-defer')
// Proxy references for testing
try {
var _self = self
var _MessageChannel = MessageChannel
} catch (err) {}
// ---
// API
// ---
/**
* Initialise a client or worker to send and receive messages.
* @param {Object} messageHandlers
* @param {ServiceWorkerRegistration} worker
* @returns {Channel}
*/
function msgr (messageHandlers, worker) {
return new Channel(messageHandlers, worker)
}
/**
* Initialise a worker to send and receive messages to and from the client.
* @param {Object} messageHandlers
* @returns {Channel}
*/
msgr.worker = function (messageHandlers) {
return msgr(messageHandlers, null)
}
/**
* Initialise a client to send and receive messages to and from the worker.
* @param {ServiceWorkerRegistration} worker
* @param {Object} messageHandlers
* @returns {Channel}
*/
msgr.client = function (worker, messageHandlers, __mockMessageChannel) {
_self = __mockMessageChannel ? {} : self
_MessageChannel = __mockMessageChannel || MessageChannel
return msgr(messageHandlers, worker)
}
// Reserved message types
msgr.types = {
CONNECT: '@@MSGR/CONNECT',
UNKNOWN: '@@MSGR/UNKNOWN',
RESPONSE: '@@MSGR/RESPONSE'
}
// ---
// Channel
// ---
function Channel (handlers, worker) {
this.handlers = handlers
this.isClient = Boolean(worker)
this.isWorker = !this.isClient
// Is the comms channel open?
this.open = defer()
// Handlers for unknown message types
this.receiveHandlers = []
// Deferreds for sent messages so we can resolve
// the promise if they receive a response
this.promises = {}
if (this.isClient) {
this.open.resolve()
this.recipient = worker
this.messageChannel = new _MessageChannel()
this.messageChannel.port1.onmessage = this._handleMessage.bind(this)
this.send(msgr.types.CONNECT)
} else {
_self.onmessage = this._handleMessage.bind(this)
}
}
/**
* Handle a message received from the client or worker.
* @param {Object} event
* @private
*/
Channel.prototype._handleMessage = function (event) {
try {
var request = JSON.parse(event.data)
var id = request.id
var type = request.type
if (!id || !type) throw new Error()
} catch (err) {
throw new Error('msgr: malformed message')
}
var responder = function (data) {
this.send(msgr.types.RESPONSE, data, id)
}.bind(this)
if (this.isWorker && request.data === msgr.types.CONNECT) {
// Special init message type that gives us the port
// that we will be sending messages to the client over
this.recipient = event.ports[0]
this.open.resolve()
}
if (request.type === msgr.types.UNKNOWN && request.data in this.handlers) {
// Known message type without data, invoke registered handler
this.handlers[request.data](null, responder)
} else if (request.type in this.handlers) {
// Known message type with data, invoke registered handler
this.handlers[request.type](request.data, responder)
} else if (id && id in this.promises) {
// Response to a message, invoke registered response handler
var promise = this.promises[id]
promise.resolve(request.data)
this.promises[id] = null
} else {
// Unknown message type, invoke receive handlers
this.receiveHandlers.forEach(function (handler) {
handler(request.data, responder)
})
}
}
Channel.prototype.ready = function (fn) {
this.open.promise.then(fn)
}
/**
* Receive an "unknown" message that does not have a predefined handler.
* @param {Function} handler
*/
Channel.prototype.receive = function (handler) {
if (typeof handler !== 'function') {
throw new Error('msgr: expecting handler to be a function')
}
this.receiveHandlers.push(handler)
}
/**
* Send a message.
* @param {String|*} type The message type or message data
* @param {*} [data] The message data
* @returns {Object}
*/
Channel.prototype.send = function (type, data, _id) {
var id = _id || shortid.generate()
if (!data) {
data = type
if (type !== msgr.types.RESPONSE) {
type = msgr.types.UNKNOWN
}
}
var deferred = defer()
var payload = JSON.stringify({
__msgr: true,
id: id,
type: type,
data: data
})
var args = [payload]
if (this.isClient && data === msgr.types.CONNECT) {
args.push([this.messageChannel.port2])
}
this.open.promise.then(function () {
this.recipient.postMessage.apply(this.recipient, args)
}.bind(this))
this.promises[id] = deferred
return deferred.promise
}
// ---
// Export
// ---
var api = {
client: msgr.client,
worker: msgr.worker,
types: msgr.types
}
if (typeof define === 'function' && define.amd) {
define('msgr', function () { return api })
} else if (typeof module === 'object' && module.exports) {
module.exports = api
} else {
self.msgr = api
}