Files: 77a1bfaba1bb16319fa986e845f5669830fbafce / index.js
1142 bytesRaw
1 | function isOriginCompatible(a, b) { |
2 | return !a || a === '*' || a.slice(0, b.length) === b |
3 | } |
4 | |
5 | module.exports = function (win, origin) { |
6 | var cbs = [], queue = [], _read |
7 | |
8 | if(origin && origin[0] === '/') { |
9 | origin = location.origin + origin |
10 | } |
11 | |
12 | function gotWin(_win) { |
13 | win = _win |
14 | if(_read) doRead() |
15 | } |
16 | |
17 | function onMessage(e) { |
18 | if(isOriginCompatible(origin, e.origin)) { |
19 | if(!win) gotWin(e.source) |
20 | if(!origin) origin = e.origin |
21 | if(cbs.length) cbs.shift()(null, e.data) |
22 | else queue.push(e.data) |
23 | } |
24 | } |
25 | |
26 | var sinkEnded, sourceEnded |
27 | |
28 | window.addEventListener('message', onMessage, false) |
29 | |
30 | return { |
31 | source: function (end, cb) { |
32 | if(sourceEnded = end) { |
33 | window.removeEventListener('message', onMessage, false) |
34 | return cb(null) |
35 | } |
36 | if(queue.length) cb(null, queue.shift()) |
37 | else cbs.push(cb) |
38 | }, |
39 | |
40 | sink: function (read) { |
41 | _read = read |
42 | if(win) doRead() |
43 | } |
44 | } |
45 | |
46 | function doRead() { |
47 | _read(null, function next(end, data) { |
48 | if(sinkEnded = end) return |
49 | win.postMessage(data, origin || '*') |
50 | _read(null, next) |
51 | }) |
52 | } |
53 | } |
54 |
Built with git-ssb-web